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/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/RehashClusterListenerTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.testng.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.Flag;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.InCacheMode;
import org.infinispan.util.ControlledConsistentHashFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Test to ensure when a rehash occurs that cluster listeners are not notified.
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "org.infinispan.notifications.cachelistener.cluster.RehashClusterListenerTest")
public class RehashClusterListenerTest extends MultipleCacheManagersTest {
protected final static String CACHE_NAME = "cluster-listener";
protected final static String KEY = "key";
protected final static String VALUE = "value";
protected ConfigurationBuilder builderUsed;
protected final ControlledConsistentHashFactory factory;
public RehashClusterListenerTest() {
this.factory = null;
}
public RehashClusterListenerTest(ControlledConsistentHashFactory factory) {
this.factory = factory;
}
@Override
public Object[] factory() {
return new Object[]{
new RehashClusterListenerTest(new ControlledConsistentHashFactory.Default(1, 2)).cacheMode(CacheMode.DIST_SYNC),
};
}
@BeforeMethod
protected void beforeMethod() throws Exception {
factory.setOwnerIndexes(1, 2);
factory.triggerRebalance(cache(0, CACHE_NAME));
TestingUtil.waitForNoRebalance(caches(CACHE_NAME));
}
@Override
protected void createCacheManagers() throws Throwable {
builderUsed = new ConfigurationBuilder();
builderUsed.clustering().cacheMode(cacheMode).hash().consistentHashFactory(factory).numSegments(1);
createClusteredCaches(3, CACHE_NAME, builderUsed);
}
public void testClusterListenerNodeBecomingPrimaryFromNotAnOwner() throws Exception {
final Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
cache1.put(KEY, VALUE);
ClusterListener listener = new ClusterListener();
cache0.addListener(listener);
factory.setOwnerIndexes(0, 1);
log.trace("Triggering rebalance to cause segment ownership to change");
factory.triggerRebalance(cache0);
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
return cache0.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).containsKey(KEY);
}
});
TestingUtil.waitForNoRebalance(cache0, cache1, cache2);
assertEquals(listener.events.size(), 0);
}
@InCacheMode(CacheMode.DIST_SYNC)
public void testClusterListenerNodeBecomingBackupFromNotAnOwner() throws Exception {
final Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
cache1.put(KEY, VALUE);
ClusterListener listener = new ClusterListener();
cache0.addListener(listener);
factory.setOwnerIndexes(1, 0);
log.trace("Triggering rebalance to cause segment ownership to change");
factory.triggerRebalance(cache0);
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
return cache0.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).containsKey(KEY);
}
});
TestingUtil.waitForNoRebalance(cache0, cache1, cache2);
assertEquals(listener.events.size(), 0);
}
public void testOtherNodeBecomingBackupFromNotAnOwner() throws Exception {
final Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
cache1.put(KEY, VALUE);
ClusterListener listener = new ClusterListener();
cache2.addListener(listener);
factory.setOwnerIndexes(1, 0);
log.trace("Triggering rebalance to cause segment ownership to change");
factory.triggerRebalance(cache0);
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
if (cacheMode.isDistributed()) {
return cache0.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL, Flag.SKIP_OWNERSHIP_CHECK).containsKey(KEY);
}
// Scattered always writes to next owner and 1 is always the primary
return cache2.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL, Flag.SKIP_OWNERSHIP_CHECK).containsKey(KEY);
}
});
TestingUtil.waitForNoRebalance(cache0, cache1, cache2);
assertEquals(listener.events.size(), 0);
}
public void testOtherNodeBecomingPrimaryFromNotAnOwner() throws Exception {
final Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
cache1.put(KEY, VALUE);
ClusterListener listener = new ClusterListener();
cache2.addListener(listener);
factory.setOwnerIndexes(0, 1);
log.trace("Triggering rebalance to cause segment ownership to change");
factory.triggerRebalance(cache0);
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
return cache0.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).containsKey(KEY);
}
});
TestingUtil.waitForNoRebalance(cache0, cache1, cache2);
assertEquals(listener.events.size(), 0);
}
@Listener(clustered = true)
protected class ClusterListener {
List<CacheEntryEvent> events = Collections.synchronizedList(new ArrayList<CacheEntryEvent>());
@CacheEntryCreated
@CacheEntryModified
@CacheEntryRemoved
public void onCacheEvent(CacheEntryEvent event) {
log.debugf("Adding new cluster event %s", event);
events.add(event);
}
}
}
| 6,814
| 34.494792
| 125
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerLocalTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.testng.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.Event;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* @author Galder Zamarreño
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerLocalTest")
public class ClusterListenerLocalTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder());
}
public void testInsertEvent() {
Cache<Object, String> cache0 = cache();
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
cache.put(1, "v1");
verifySimpleInsertionEvents(clusterListener, 1, "v1");
}
protected void verifySimpleInsertionEvents(ClusterListener listener, Object key, Object expectedValue) {
assertEquals(listener.events.size(), 1);
CacheEntryEvent event = listener.events.get(0);
assertEquals(Event.Type.CACHE_ENTRY_CREATED, event.getType());
assertEquals(key, event.getKey());
assertEquals(expectedValue, event.getValue());
}
@Listener(clustered = true)
protected class ClusterListener {
List<CacheEntryEvent> events = Collections.synchronizedList(new ArrayList<CacheEntryEvent>());
@CacheEntryCreated
@CacheEntryModified
@CacheEntryRemoved
public void onCacheEvent(CacheEntryEvent event) {
log.debugf("Adding new cluster event %s", event);
events.add(event);
}
}
}
| 2,356
| 35.828125
| 107
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerStressTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.testng.Assert.assertEquals;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import org.infinispan.Cache;
import org.infinispan.commons.executors.BlockingThreadPoolExecutorFactory;
import org.infinispan.commons.test.TestResourceTracker;
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.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.fwk.InCacheMode;
import org.testng.annotations.Test;
/**
* Stress test that simultates multiple writers to different cache nodes to verify cluster listener is notified
* properly.
*
* @author wburns
* @since 7.0
*/
@Test(groups = "stress", testName = "notifications.cachelistener.cluster.ClusterListenerStressTest", timeOut = 15*60*1000)
@InCacheMode({ CacheMode.DIST_SYNC })
public class ClusterListenerStressTest extends MultipleCacheManagersTest {
protected final static String CACHE_NAME = "cluster-listener";
protected final static String KEY = "ClusterListenerStressTestKey";
private static final int NUM_NODES = 3;
protected ConfigurationBuilder builderUsed;
@Override
protected void createCacheManagers() throws Throwable {
Configuration distConfig = getDefaultClusteredCacheConfig(cacheMode, false).build();
for (int i = 0; i < NUM_NODES; i++) {
GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();
gcb.transport().defaultTransport().nodeName(TestResourceTracker.getNameForIndex(i));
BlockingThreadPoolExecutorFactory remoteExecutorFactory = new BlockingThreadPoolExecutorFactory(
10, 1, 0, 60000);
gcb.transport().remoteCommandThreadPool().threadPoolFactory(remoteExecutorFactory);
EmbeddedCacheManager cm = new DefaultCacheManager(gcb.build());
registerCacheManager(cm);
cm.defineConfiguration(CACHE_NAME, distConfig);
log.infof("Started cache manager %s", cm.getAddress());
}
waitForClusterToForm(CACHE_NAME);
}
@Listener(clustered = true)
private static class ClusterListenerAggregator {
AtomicInteger creationCount = new AtomicInteger();
AtomicInteger modifyCount = new AtomicInteger();
AtomicInteger removalCount = new AtomicInteger();
@CacheEntryCreated
public void listenForModifications(CacheEntryEvent<String, Integer> event) {
creationCount.incrementAndGet();
}
@CacheEntryModified
public void modified(CacheEntryEvent<String, Integer> event) {
modifyCount.incrementAndGet();
}
@CacheEntryRemoved
public void removed(CacheEntryEvent<String, Integer> event) {
removalCount.incrementAndGet();
}
}
private static class CreateModifyRemovals {
private final int creationCount;
private final int modifyCount;
private final int removalCount;
public CreateModifyRemovals(int creationCount, int modifyCount, int removalCount) {
this.creationCount = creationCount;
this.modifyCount = modifyCount;
this.removalCount = removalCount;
}
}
@Test
public void runStressTestMultipleWriters() throws ExecutionException, InterruptedException {
Cache<String, Integer> cache0 = cache(0, CACHE_NAME);
Cache<String, Integer> cache1 = cache(1, CACHE_NAME);
Cache<String, Integer> cache2 = cache(2, CACHE_NAME);
ClusterListenerAggregator listener = new ClusterListenerAggregator();
cache0.addListener(listener);
cache0.addListener(listener);
cache0.addListener(listener);
cache1.addListener(listener);
cache1.addListener(listener);
cache2.addListener(listener);
long begin = System.currentTimeMillis();
int threadCount = 10;
final CountDownLatch latch = new CountDownLatch(threadCount);
Callable<CreateModifyRemovals> callable = new Callable<CreateModifyRemovals>() {
@Override
public CreateModifyRemovals call() throws Exception {
latch.countDown();
latch.await();
int creationCount = 0;
int modifyCount = 0;
int removalCount = 0;
for (int i = 0; i < 1000; i++) {
int random = ThreadLocalRandom.current().nextInt(0, 23);
boolean key = (random & 1) == 1;
int cache = random / 8;
int operation = random & 3;
Cache<String, Integer> cacheToUse = cache(cache, CACHE_NAME);
String keyToUse = key ? KEY : KEY + "2";
// 0 - regular put operation (detects if create modify)
// 1 - remove operation
// 2 - conditional replace/putIfAbsent
// 3 - conditional remove
switch (operation) {
case 0:
Integer prevValue = cacheToUse.put(keyToUse, i);
if (prevValue != null) {
modifyCount++;
} else {
creationCount++;
}
break;
case 1:
cacheToUse.remove(keyToUse);
removalCount++;
break;
case 2:
prevValue = cacheToUse.get(keyToUse);
if (prevValue != null) {
if (cacheToUse.replace(keyToUse, prevValue, i)) {
modifyCount++;
}
} else {
if (cacheToUse.putIfAbsent(keyToUse, i) == null) {
creationCount++;
}
}
break;
case 3:
prevValue = cacheToUse.get(keyToUse);
if (prevValue != null) {
cacheToUse.remove(keyToUse, prevValue);
// We always notify on a removal even if it didn't remove it!
removalCount++;
}
break;
default:
throw new IllegalArgumentException("Unsupported case!, provided " + operation);
}
}
return new CreateModifyRemovals(creationCount, modifyCount, removalCount);
}
};
Future<CreateModifyRemovals>[] futures = new Future[threadCount];
for (int i = 0; i < threadCount; ++i) {
futures[i] = fork(callable);
}
int creationCount = 0;
int modifyCount = 0;
int removalCount = 0;
for (Future<CreateModifyRemovals> future : futures) {
CreateModifyRemovals cmr = future.get();
creationCount += cmr.creationCount;
modifyCount += cmr.modifyCount;
removalCount += cmr.removalCount;
}
int listenerCount = 6;
assertEquals(listener.creationCount.get(), creationCount * listenerCount);
assertEquals(listener.modifyCount.get(), modifyCount * listenerCount);
assertEquals(listener.removalCount.get(), removalCount * listenerCount);
System.out.println("Took " + (System.currentTimeMillis() - begin) + " milliseconds");
}
}
| 8,122
| 39.014778
| 122
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerReplTxTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* Cluster listener test having a configuration of transactional and replication
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerReplTxTest")
public class ClusterListenerReplTxTest extends AbstractClusterListenerTxTest {
public ClusterListenerReplTxTest() {
super(CacheMode.REPL_SYNC);
}
}
| 540
| 29.055556
| 104
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/NoOpCacheEventFilterConverterWithDependencies.java
|
package org.infinispan.notifications.cachelistener.cluster;
import org.infinispan.Cache;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.AbstractCacheEventFilterConverter;
import org.infinispan.notifications.cachelistener.filter.EventType;
import org.infinispan.protostream.annotations.ProtoName;
/**
* @author anistor@redhat.com
* @since 7.2
*/
@Scope(Scopes.NONE)
@ProtoName("NoOpCacheEventFilterConverterWithDependencies")
public class NoOpCacheEventFilterConverterWithDependencies<K, V> extends AbstractCacheEventFilterConverter<K, V, V> {
private transient Cache cache;
@Inject
protected void injectDependencies(Cache cache) {
this.cache = cache;
}
@Override
public V filterAndConvert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) {
if (cache == null) {
throw new IllegalStateException("Dependencies were not injected");
}
return newValue;
}
}
| 1,156
| 32.057143
| 126
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/AbstractClusterListenerTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import java.io.Serializable;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.distribution.MagicKey;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent;
import org.infinispan.notifications.cachelistener.event.Event;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilter;
import org.infinispan.notifications.cachelistener.filter.KeyValueFilterAsCacheEventFilter;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
/**
* Base class to be used for cluster listener tests for both tx and nontx caches
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional")
public abstract class AbstractClusterListenerTest extends AbstractClusterListenerUtilTest {
protected AbstractClusterListenerTest(boolean tx, CacheMode cacheMode) {
super(tx, cacheMode);
}
protected ClusterListener listener() {
return new ClusterListener();
}
@Test
public void testCreateFromNonOwnerWithListenerNotOwner() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
MagicKey key = new MagicKey(cache1, cache2);
verifySimpleInsertion(cache2, key, FIRST_VALUE, null, clusterListener, FIRST_VALUE);
}
@Test
public void testCreateFromNonOwnerWithListenerAsBackupOwner() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
MagicKey key = new MagicKey(cache1, cache0);
verifySimpleInsertion(cache2, key, FIRST_VALUE, null, clusterListener, FIRST_VALUE);
}
@Test
public void testLocalNodeOwnerAndClusterListener() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
MagicKey key = new MagicKey(cache0);
verifySimpleInsertion(cache0, key, FIRST_VALUE, null, clusterListener, FIRST_VALUE);
}
@Test
public void testLocalNodeNonOwnerAndClusterListener() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
MagicKey key = new MagicKey(cache1, cache2);
verifySimpleInsertion(cache0, key, FIRST_VALUE, null, clusterListener, FIRST_VALUE);
}
@Test
public void testSimpleFilterNotOwner() {
testSimpleFilter(new MagicKey(cache(1, CACHE_NAME), cache(2, CACHE_NAME)));
}
@Test
public void testSimpleFilterLocalOnly() {
testSimpleFilter(new MagicKey(cache(0, CACHE_NAME)));
}
@Test
public void testMetadataFilterNotOwner() {
final String keyToFilterOut = "filter-me";
testFilter(keyToFilterOut, new MagicKey(cache(1, CACHE_NAME), cache(2, CACHE_NAME)), 1000l,
new KeyValueFilterAsCacheEventFilter(new LifespanFilter<Object, String>(100)));
}
@Test
public void testMetadataFilterLocalOnly() {
final String keyToFilterOut = "filter-me";
testFilter(keyToFilterOut, new MagicKey(cache(0, CACHE_NAME)), 1000l,
new KeyValueFilterAsCacheEventFilter(new LifespanFilter<Object, String>(100)));
}
protected void testSimpleFilter(Object key) {
final String keyToFilterOut = "filter-me";
testFilter(keyToFilterOut, key, null, filter(key));
}
protected void testFilter(Object keyToFilterOut, Object keyToUse, Long lifespan, CacheEventFilter<? super Object, ? super String> filter) {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener, filter, null);
cache0.put(keyToFilterOut, FIRST_VALUE);
// We should not have gotten the message since it was filtered
assertEquals(clusterListener.events.size(), 0);
verifySimpleInsertion(cache0, keyToUse, FIRST_VALUE, lifespan, clusterListener, FIRST_VALUE);
}
@Test
public void testSimpleConverterNotOwner() {
testSimpleConverter(new MagicKey(cache(1, CACHE_NAME), cache(2, CACHE_NAME)));
}
@Test
public void testSimpleConverterLocalOnly() {
testSimpleConverter(new MagicKey(cache(0, CACHE_NAME)));
}
@Test
public void testMetadataConverterSuccessNotOwner() {
long lifespan = 25000;
LifespanConverter converter = new LifespanConverter(true, 500);
testConverter(new MagicKey(cache(1, CACHE_NAME), cache(2, CACHE_NAME)), FIRST_VALUE, lifespan, lifespan, converter);
}
@Test
public void testMetadataConverterSuccessLocalOnly() {
long lifespan = 25000;
LifespanConverter converter = new LifespanConverter(true, 500);
testConverter(new MagicKey(cache(0, CACHE_NAME)), FIRST_VALUE, lifespan, lifespan, converter);
}
@Test
public void testMetadataConverterNoPassReturnOriginalNotOwner() {
long lifespan = 25000;
LifespanConverter converter = new LifespanConverter(true, Long.MAX_VALUE);
testConverter(new MagicKey(cache(1, CACHE_NAME), cache(2, CACHE_NAME)), FIRST_VALUE, FIRST_VALUE, lifespan, converter);
}
@Test
public void testMetadataConverterNoPassReturnOriginalLocalOnly() {
long lifespan = 25000;
LifespanConverter converter = new LifespanConverter(true, Long.MAX_VALUE);
testConverter(new MagicKey(cache(0, CACHE_NAME)), FIRST_VALUE, FIRST_VALUE, lifespan, converter);
}
@Test
public void testMetadataConverterNoPassReturnNullNotOwner() {
long lifespan = 25000;
LifespanConverter converter = new LifespanConverter(false, Long.MAX_VALUE);
testConverter(new MagicKey(cache(1, CACHE_NAME), cache(2, CACHE_NAME)), FIRST_VALUE, null, lifespan, converter);
}
@Test
public void testMetadataConverterNoPassReturnNullLocalOnly() {
long lifespan = 25000;
LifespanConverter converter = new LifespanConverter(false, Long.MAX_VALUE);
testConverter(new MagicKey(cache(0, CACHE_NAME)), FIRST_VALUE, null, lifespan, converter);
}
protected void testSimpleConverter(Object key) {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener, null, new StringTruncator(0, 2));
verifySimpleInsertion(cache0, key, FIRST_VALUE, null, clusterListener, FIRST_VALUE.substring(0, 2));
}
protected <C> void testConverter(Object key, String value, Object resultingValue, Long lifespan,
CacheEventConverter<Object, ? super String, C> converter) {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener, null, converter);
verifySimpleInsertion(cache0, key, value, lifespan, clusterListener, resultingValue);
}
@Test
public void testClusterListenerNodeGoesDown() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
int cache1ListenerSize = cache1.getAdvancedCache().getListeners().size();
int cache2ListenerSize = cache2.getAdvancedCache().getListeners().size();
log.info("Killing node 0 ..");
TestingUtil.killCacheManagers(manager(0));
cacheManagers.remove(0);
log.info("Node 0 killed");
TestingUtil.blockUntilViewsReceived(60000, false, cache1, cache2);
TestingUtil.waitForNoRebalance(cache1, cache2);
assertEquals(cache1.getAdvancedCache().getListeners().size(), cache1ListenerSize -
(cacheMode.isDistributed() ? 1 : 0));
assertEquals(cache2.getAdvancedCache().getListeners().size(), cache2ListenerSize -
(cacheMode.isDistributed() ? 1 : 0));
}
@Test
public void testNodeComesUpWithClusterListenerAlreadyInstalled() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
addClusteredCacheManager();
waitForClusterToForm(CACHE_NAME);
Cache<Object, String> cache3 = cache(3, CACHE_NAME);
MagicKey key = new MagicKey(cache3);
verifySimpleInsertion(cache3, key, FIRST_VALUE, null, clusterListener, FIRST_VALUE);
}
@Test
public void testNodeComesUpWithClusterListenerAlreadyInstalledFilterAndConverter() {
final String keyToFilter = "filter-me";
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener, filter(keyToFilter), new StringTruncator(0, 3));
addClusteredCacheManager();
waitForClusterToForm(CACHE_NAME);
Cache<Object, String> cache3 = cache(3, CACHE_NAME);
MagicKey key = new MagicKey(cache3);
cache3.put(key, FIRST_VALUE);
// Should be filtered
assertEquals(clusterListener.events.size(), 0);
verifySimpleInsertion(cache3, keyToFilter, FIRST_VALUE, null, clusterListener, FIRST_VALUE.substring(0, 3));
}
@Test
public void testSimpleClusterListenerRemoved() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
int initialCache0ListenerSize = cache0.getAdvancedCache().getListeners().size();
int initialCache1ListenerSize = cache1.getAdvancedCache().getListeners().size();
int initialCache2ListenerSize = cache2.getAdvancedCache().getListeners().size();
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
// Adding a cluster listener should add to each node in cluster
assertEquals(cache0.getAdvancedCache().getListeners().size(), initialCache0ListenerSize + 1);
assertEquals(cache1.getAdvancedCache().getListeners().size(), initialCache1ListenerSize +
(cacheMode.isDistributed() ? 1 : 0));
assertEquals(cache2.getAdvancedCache().getListeners().size(), initialCache2ListenerSize +
(cacheMode.isDistributed() ? 1 : 0));
cache0.removeListener(clusterListener);
assertEquals(cache0.getAdvancedCache().getListeners().size(), initialCache0ListenerSize);
assertEquals(cache1.getAdvancedCache().getListeners().size(), initialCache1ListenerSize);
assertEquals(cache2.getAdvancedCache().getListeners().size(), initialCache2ListenerSize);
}
@Test
public void testClusterListenerRemovedWithMultipleInstalledOnSameNode() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
int initialCache0ListenerSize = cache0.getAdvancedCache().getListeners().size();
int initialCache1ListenerSize = cache1.getAdvancedCache().getListeners().size();
int initialCache2ListenerSize = cache2.getAdvancedCache().getListeners().size();
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
// Adding a cluster listener should add to each node in cluster
assertEquals(cache0.getAdvancedCache().getListeners().size(), initialCache0ListenerSize + 1);
assertEquals(cache1.getAdvancedCache().getListeners().size(), initialCache1ListenerSize +
(cacheMode.isDistributed() ? 1 : 0));
assertEquals(cache2.getAdvancedCache().getListeners().size(), initialCache2ListenerSize +
(cacheMode.isDistributed() ? 1 : 0));
ClusterListener clusterListener2 = listener();
cache0.addListener(clusterListener2);
// Adding a second cluster listener should add to each node in cluster as well
assertEquals(cache0.getAdvancedCache().getListeners().size(), initialCache0ListenerSize + 2);
assertEquals(cache1.getAdvancedCache().getListeners().size(), initialCache1ListenerSize +
(cacheMode.isDistributed() ? 2 : 0));
assertEquals(cache2.getAdvancedCache().getListeners().size(), initialCache2ListenerSize +
(cacheMode.isDistributed() ? 2 : 0));
MagicKey key = new MagicKey(cache2, cache1);
cache1.put(key, FIRST_VALUE);
// Both listeners should have been notified
assertEquals(clusterListener.events.size(), 1);
assertEquals(clusterListener2.events.size(), 1);
verifySimpleInsertionEvents(clusterListener, key, FIRST_VALUE);
verifySimpleInsertionEvents(clusterListener2, key, FIRST_VALUE);
cache0.removeListener(clusterListener);
assertEquals(cache0.getAdvancedCache().getListeners().size(), initialCache0ListenerSize + 1);
assertEquals(cache1.getAdvancedCache().getListeners().size(), initialCache1ListenerSize +
(cacheMode.isDistributed() ? 1 : 0));
assertEquals(cache2.getAdvancedCache().getListeners().size(), initialCache2ListenerSize +
(cacheMode.isDistributed() ? 1 : 0));
// Change the value again to make sure other listener is still working properly
cache2.put(key, SECOND_VALUE);
assertEquals(clusterListener2.events.size(), 2);
CacheEntryEvent event = clusterListener2.events.get(1);
assertEquals(Event.Type.CACHE_ENTRY_MODIFIED, event.getType());
assertEquals(key, event.getKey());
assertEquals(SECOND_VALUE, ((CacheEntryModifiedEvent)event).getValue());
}
@Test
public void testMemberLeavesThatClusterListenerNotNotified() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
Object key = new MagicKey(cache1, cache2);
cache1.put(key, "some-key");
final ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
log.info("Killing node 1 ..");
TestingUtil.killCacheManagers(manager(1));
cacheManagers.remove(1);
log.info("Node 1 killed");
TestingUtil.blockUntilViewsReceived(10000, false, cacheManagers);
TestingUtil.waitForNoRebalance(caches(CACHE_NAME));
assertEquals(clusterListener.hasIncludeState() ? 1 : 0, clusterListener.events.size());
}
@Test
public void testPreviousValueConverterEventRaisedLocalNode() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
String previousValue = "myOldValue";
long previousExpiration = 10000000;
MagicKey key = new MagicKey(cache0);
cache0.put(key, previousValue, previousExpiration, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener, null, new StringAppender());
String newValue = "myBrandSpankingNewValue";
long newExpiration = 314159;
verifySimpleModification(cache0, key, newValue, newExpiration, clusterListener,
previousValue + previousExpiration + newValue + newExpiration);
}
@Test
public void testPreviousValueConverterEventRaisedNonOwnerNode() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
String previousValue = "myOldValue";
long previousExpiration = 10000000;
MagicKey key = new MagicKey(cache0, cache1);
cache0.put(key, previousValue, previousExpiration, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache2.addListener(clusterListener, null, new StringAppender());
String newValue = "myBrandSpankingNewValue";
long newExpiration = 314159;
verifySimpleModification(cache0, key, newValue, newExpiration, clusterListener,
previousValue + previousExpiration + newValue + newExpiration);
}
@Test
public void testPreviousValueConverterEventRaisedBackupOwnerNode() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
String previousValue = "myOldValue";
long previousExpiration = 10000000;
MagicKey key = new MagicKey(cache0, cache1);
cache0.put(key, previousValue, previousExpiration, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache1.addListener(clusterListener, null, new StringAppender());
String newValue = "myBrandSpankingNewValue";
long newExpiration = 314159265;
verifySimpleModification(cache0, key, newValue, newExpiration, clusterListener,
previousValue + previousExpiration + newValue + newExpiration);
}
@Test
public void testPreviousValueFilterEventRaisedLocalNode() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
String previousValue = "myOldValue";
long previousExpiration = 10000000;
MagicKey key = new MagicKey(cache0, cache1);
cache0.put(key, previousValue, previousExpiration, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache1.addListener(clusterListener, new NewLifespanLargerFilter<Object, String>(), null);
// This event is ignored because lifespan is shorter
cache0.put(key, previousValue, previousExpiration - 100, TimeUnit.MILLISECONDS);
String newValue = "myBrandSpankingNewValue";
long newExpiration = 314159265;
verifySimpleModification(cache0, key, newValue, newExpiration, clusterListener, newValue);
}
@Test
public void testPreviousValueFilterEventRaisedNonOwnerNode() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
String previousValue = "myOldValue";
long previousExpiration = 10000000;
MagicKey key = new MagicKey(cache0, cache1);
// This event is ignored because no previous lifespan
cache0.put(key, previousValue, previousExpiration, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache2.addListener(clusterListener, new NewLifespanLargerFilter<Object, String>(), null);
// This event is ignored because lifespan is shorter
cache0.put(key, previousValue, previousExpiration - 100, TimeUnit.MILLISECONDS);
String newValue = "myBrandSpankingNewValue";
long newExpiration = 314159265;
verifySimpleModification(cache0, key, newValue, newExpiration, clusterListener, newValue);
}
@Test
public void testPreviousValueFilterEventRaisedBackupOwnerNode() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
String previousValue = "myOldValue";
long previousExpiration = 10000000;
MagicKey key = new MagicKey(cache0, cache1);
// This event is ignored because no previous lifespan
cache0.put(key, previousValue, previousExpiration, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache1.addListener(clusterListener, new NewLifespanLargerFilter<Object, String>(), null);
// This event is ignored because lifespan is shorter
cache0.put(key, previousValue, previousExpiration - 100, TimeUnit.MILLISECONDS);
String newValue = "myBrandSpankingNewValue";
long newExpiration = 314159265;
verifySimpleModification(cache0, key, newValue, newExpiration, clusterListener, newValue);
}
@Test
public void testCacheEventFilterConverter() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(0, CACHE_NAME);
Cache<Object, String> cache2 = cache(0, CACHE_NAME);
String convertedValue = "my-value";
FilterConverter filterConverter = new FilterConverter(true, convertedValue);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener, filterConverter, filterConverter);
MagicKey key = new MagicKey(cache1, cache2);
verifySimpleInsertion(cache0, key, "doesn't-matter", null, clusterListener, convertedValue);
}
@Test
public void testListenerOnPrimaryNodeReadPrimary() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
MagicKey key = new MagicKey(cache0);
String expectedValue = key + "-expiring";
cache0.put(key, key + "-expiring", 10, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
ts0.advance(11);
assertNull(cache0.get(key));
int expectCount = clusterListener.hasIncludeState() ? 2 : 1;
eventually(() -> clusterListener.events.size() >= expectCount, 200000);
assertEquals(expectCount, clusterListener.events.size());
CacheEntryEvent event = clusterListener.events.get(clusterListener.hasIncludeState() ? 1 : 0);
assertEquals(Event.Type.CACHE_ENTRY_EXPIRED, event.getType());
assertEquals(key, event.getKey());
assertEquals(expectedValue, event.getValue());
}
@Test
public void testListenerOnPrimaryNodeReadBackup() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
MagicKey key = new MagicKey(cache0, cache1);
String expectedValue = key + "-expiring";
cache0.put(key, key + "-expiring", 10, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
ts1.advance(11);
assertNull(cache1.get(key));
int expectCount = clusterListener.hasIncludeState() ? 2 : 1;
eventually(() -> clusterListener.events.size() >= expectCount);
assertEquals(expectCount, clusterListener.events.size());
CacheEntryEvent event = clusterListener.events.get(clusterListener.hasIncludeState() ? 1 : 0);
assertEquals(Event.Type.CACHE_ENTRY_EXPIRED, event.getType());
assertEquals(key, event.getKey());
assertEquals(expectedValue, event.getValue());
}
public void testListenerOnBackupOwnerNodePrimaryRead() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
MagicKey key = new MagicKey(cache0, cache1);
String expectedValue = key + "-expiring";
cache0.put(key, key + "-expiring", 10, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache1.addListener(clusterListener);
ts0.advance(11);
ts1.advance(11);
ts2.advance(11);
assertNull(cache0.get(key));
int expectCount = clusterListener.hasIncludeState() ? 2 : 1;
eventually(() -> clusterListener.events.size() >= expectCount);
assertEquals(expectCount, clusterListener.events.size());
CacheEntryEvent event = clusterListener.events.get(clusterListener.hasIncludeState() ? 1 : 0);
assertEquals(Event.Type.CACHE_ENTRY_EXPIRED, event.getType());
assertEquals(key, event.getKey());
assertEquals(expectedValue, event.getValue());
}
public void testListenerOnBackupOwnerNodeBackupRead() {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
MagicKey key = new MagicKey(cache0, cache1);
String expectedValue = key + "-expiring";
cache0.put(key, key + "-expiring", 10, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
ts1.advance(11);
assertNull(cache1.get(key));
int expectCount = clusterListener.hasIncludeState() ? 2 : 1;
eventually(() -> clusterListener.events.size() >= expectCount);
assertEquals(expectCount, clusterListener.events.size());
CacheEntryEvent event = clusterListener.events.get(clusterListener.hasIncludeState() ? 1 : 0);
assertEquals(Event.Type.CACHE_ENTRY_EXPIRED, event.getType());
assertEquals(key, event.getKey());
assertEquals(expectedValue, event.getValue());
}
public void testAllExpire() throws InterruptedException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
MagicKey key = new MagicKey(cache0);
String expectedValue = key + "-expiring";
cache0.put(key, key + "-expiring", 1000, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
advanceTimeServices(1001, TimeUnit.MILLISECONDS);
assertNull(cache0.get(key));
assertNull(cache1.get(key));
assertNull(cache2.get(key));
int expectCount = clusterListener.hasIncludeState() ? 2 : 1;
eventually(() -> clusterListener.events.size() >= expectCount);
// We can't assert size here, thiis is because expiration is done asynchronously. As such you could have more
// than 1 expire command come at the same time, although from different nodes. Currently we assume a null is
// okay to say it was expired, so you can get multiple expirations
CacheEntryEvent event = clusterListener.events.get(clusterListener.hasIncludeState() ? 1 : 0);
assertEquals(Event.Type.CACHE_ENTRY_EXPIRED, event.getType());
assertEquals(key, event.getKey());
assertEquals(expectedValue, event.getValue());
}
@Test
public void testSimpleExpirationFilterNotOwner() {
testSimpleExpirationFilter(new MagicKey(cache(1, CACHE_NAME), cache(2, CACHE_NAME)));
}
@Test
public void testExpirationMetadataFilterNotOwner() {
final String keyToFilterOut = "filter-me";
testExpirationFilter(keyToFilterOut, 50l, new MagicKey(cache(1, CACHE_NAME), cache(2, CACHE_NAME)), 1000l,
new KeyValueFilterAsCacheEventFilter(new LifespanFilter<Object, String>(100)));
}
protected void testSimpleExpirationFilter(Object key) {
final String keyToFilterOut = "filter-me";
final long commonLifespan = 1000l;
testExpirationFilter(keyToFilterOut, commonLifespan, key, commonLifespan, filter(key));
}
protected void testExpirationFilter(Object keyToFilterOut, Long keyToFilterOutLifespan, Object keyToUse, Long keyToUselifespan, CacheEventFilter<? super Object, ? super String> filter) {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
//put from a non-owner
cache0.put(keyToFilterOut, FIRST_VALUE, keyToFilterOutLifespan, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener, filter, null);
advanceTimeServices(keyToFilterOutLifespan + 1, TimeUnit.MILLISECONDS);
assertNull(cache0.get(keyToFilterOut));
// We should not have gotten the message since it was filtered
assertEquals(clusterListener.events.size(), 0);
String expectedValue = keyToUse + "-expiring";
cache0.put(keyToUse, keyToUse + "-expiring", keyToUselifespan, TimeUnit.MILLISECONDS);
advanceTimeServices(keyToUselifespan + 1, TimeUnit.MILLISECONDS);
assertNull(cache0.get(keyToUse));
verifySimpleExpirationEvents(clusterListener, 2, keyToUse, expectedValue);
}
@Test
public void testSimpleExpirationConverterNotOwner() {
long lifespan = 1000;
StringTruncator converter = new StringTruncator(0, 2);
testExpirationConverter(new MagicKey(cache(1, CACHE_NAME), cache(2, CACHE_NAME)), FIRST_VALUE, FIRST_VALUE.substring(0, 2), lifespan, converter);
}
@Test
public void testMetadataExpirationConverterSuccessNotOwner() {
long lifespan = 25000;
LifespanConverter converter = new LifespanConverter(true, 500);
testExpirationConverter(new MagicKey(cache(1, CACHE_NAME), cache(2, CACHE_NAME)), FIRST_VALUE, lifespan, lifespan, converter);
}
protected <C> void testExpirationConverter(Object key, String value, Object expectedValue, Long lifespan,
CacheEventConverter<Object, ? super String, C> converter) {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
cache0.put(key, value, lifespan, TimeUnit.MILLISECONDS);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener, null, converter);
advanceTimeServices(lifespan + 1, TimeUnit.MILLISECONDS);
assertNull(cache0.get(key));
verifySimpleExpirationEvents(clusterListener, clusterListener.hasIncludeState() ? 2 : 1, key, expectedValue);
}
private CacheEventFilter<Object, String> filter(Object keyToFilter) {
return (Serializable & CacheEventFilter<Object, String>)
(k, oldValue, oldMetadata, newValue, newMetadata, eventType) -> Objects.equals(k, keyToFilter);
}
}
| 29,740
| 39.299458
| 189
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerDistTxTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* Cluster listener test having a configuration of transactional and dist
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerDistTxTest")
public class ClusterListenerDistTxTest extends AbstractClusterListenerTxTest {
public ClusterListenerDistTxTest() {
super(CacheMode.DIST_SYNC);
}
}
| 533
| 28.666667
| 104
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/AbstractClusterListenerUtilTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.notNull;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;
import static org.testng.AssertJUnit.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.commons.time.TimeService;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.filter.KeyValueFilter;
import org.infinispan.manager.CacheContainer;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent;
import org.infinispan.notifications.cachelistener.event.Event;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverter;
import org.infinispan.notifications.cachelistener.filter.EventType;
import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CheckPoint;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.ControlledTimeService;
import org.infinispan.util.concurrent.IsolationLevel;
import org.mockito.AdditionalAnswers;
import org.mockito.stubbing.Answer;
/**
* Base class to be used for cluster listener tests for both tx and nontx caches
*
* @author wburns
* @since 7.0
*/
public abstract class AbstractClusterListenerUtilTest extends MultipleCacheManagersTest {
protected final static String CACHE_NAME = "cluster-listener";
protected final static String FIRST_VALUE = "first-value";
protected final static String SECOND_VALUE = "second-value";
protected ConfigurationBuilder builderUsed;
protected SerializationContextInitializer sci;
protected final boolean tx;
protected final CacheMode cacheMode;
protected ControlledTimeService ts0;
protected ControlledTimeService ts1;
protected ControlledTimeService ts2;
protected AbstractClusterListenerUtilTest(boolean tx, CacheMode cacheMode) {
// Have to have cleanup after each method since listeners need to be cleaned up
cleanup = CleanupPhase.AFTER_METHOD;
this.tx = tx;
this.cacheMode = cacheMode;
this.sci = new ListenerSerializationContextImpl();
}
protected void addClusteredCacheManager() {
// First we add the new node, but block the dist exec execution
log.info("Adding a new node ..");
EmbeddedCacheManager manager = addClusterEnabledCacheManager(sci);
manager.defineConfiguration(CACHE_NAME, builderUsed.build());
log.info("Added a new node");
}
@Override
protected void createCacheManagers() throws Throwable {
builderUsed = new ConfigurationBuilder();
builderUsed.clustering().cacheMode(cacheMode);
if (tx) {
builderUsed.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
builderUsed.locking().isolationLevel(IsolationLevel.READ_COMMITTED);
}
builderUsed.expiration().disableReaper();
createClusteredCaches(3, CACHE_NAME, sci, builderUsed);
injectTimeServices();
}
protected void injectTimeServices() {
ts0 = new ControlledTimeService();
TestingUtil.replaceComponent(manager(0), TimeService.class, ts0, true);
ts1 = new ControlledTimeService();
TestingUtil.replaceComponent(manager(1), TimeService.class, ts1, true);
ts2 = new ControlledTimeService();
TestingUtil.replaceComponent(manager(2), TimeService.class, ts2, true);
}
void advanceTimeServices(long time, TimeUnit unit) {
long millis = unit.toMillis(time);
ts0.advance(millis);
ts1.advance(millis);
ts2.advance(millis);
}
@Listener(clustered = true)
protected class ClusterListener {
List<CacheEntryEvent> events = Collections.synchronizedList(new ArrayList<>());
@CacheEntryCreated
public void onCreatedEvent(CacheEntryCreatedEvent event) {
onCacheEvent(event);
}
@CacheEntryModified
public void onModifiedEvent(CacheEntryModifiedEvent event) {
onCacheEvent(event);
}
@CacheEntryRemoved
public void onRemoveEvent(CacheEntryRemovedEvent event) {
onCacheEvent(event);
}
@CacheEntryExpired
public void onExpireEvent(CacheEntryExpiredEvent event) {
onCacheEvent(event);
}
void onCacheEvent(CacheEntryEvent event) {
log.debugf("Adding new cluster event %s", event);
events.add(event);
}
protected boolean hasIncludeState() {
return false;
}
}
@Listener(clustered = true, includeCurrentState = true)
protected class ClusterListenerWithIncludeCurrentState extends ClusterListener {
protected boolean hasIncludeState() {
return true;
}
}
public static class LifespanFilter<K, V> implements KeyValueFilter<K, V> {
@ProtoFactory
LifespanFilter(long lifespan) {
this.lifespan = lifespan;
}
@ProtoField(number = 1, defaultValue = "-1")
final long lifespan;
@Override
public boolean accept(K key, V value, Metadata metadata) {
if (metadata == null) {
return false;
}
// Only accept entities with a lifespan longer than ours
return metadata.lifespan() > lifespan;
}
}
@ProtoName("NewLifespanLargerFilter")
protected static class NewLifespanLargerFilter<K, V> implements CacheEventFilter<K, V> {
@Override
public boolean accept(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) {
// If neither metadata is provided dont' raise the event (this will preclude all creations and removals)
if (oldMetadata == null || newMetadata == null) {
return true;
}
// Only accept entities with a lifespan that is now longer
return newMetadata.lifespan() > oldMetadata.lifespan();
}
}
public static class LifespanConverter implements CacheEventConverter<Object, String, Object> {
@ProtoField(number = 1, defaultValue = "false")
final boolean returnOriginalValueOrNull;
@ProtoField(number = 2, defaultValue = "-1")
final long lifespanThreshold;
@ProtoFactory
LifespanConverter(boolean returnOriginalValueOrNull, long lifespanThreshold) {
this.returnOriginalValueOrNull = returnOriginalValueOrNull;
this.lifespanThreshold = lifespanThreshold;
}
@Override
public Object convert(Object key, String oldValue, Metadata oldMetadata, String newValue, Metadata newMetadata, EventType eventType) {
if (newMetadata != null) {
long metaLifespan = newMetadata.lifespan();
if (metaLifespan > lifespanThreshold) {
return metaLifespan;
}
}
if (returnOriginalValueOrNull) {
return newValue;
}
return null;
}
}
public static class StringTruncator implements CacheEventConverter<Object, String, String> {
@ProtoField(number = 1, defaultValue = "0")
int beginning;
@ProtoField(number = 2, defaultValue = "0")
int length;
@ProtoFactory
StringTruncator(int beginning, int length) {
this.beginning = beginning;
this.length = length;
}
@Override
public String convert(Object key, String oldValue, Metadata oldMetadata, String newValue, Metadata newMetadata, EventType eventType) {
if (newValue != null && newValue.length() > beginning + length) {
return newValue.substring(beginning, beginning + length);
} else {
return newValue;
}
}
}
@ProtoName("StringAppender")
public static class StringAppender implements CacheEventConverter<Object, String, String> {
@Override
public String convert(Object key, String oldValue, Metadata oldMetadata, String newValue, Metadata newMetadata, EventType eventType) {
return oldValue + (oldMetadata != null ? oldMetadata.lifespan() : "null") + newValue + (newMetadata != null ? newMetadata.lifespan() : "null");
}
}
public static class FilterConverter implements CacheEventFilterConverter<Object, Object, Object> {
@ProtoField(number = 1, defaultValue = "false")
final boolean throwExceptionOnNonFilterAndConverterMethods;
@ProtoField(2)
final String convertedValue;
@ProtoFactory
FilterConverter(boolean throwExceptionOnNonFilterAndConverterMethods, String convertedValue) {
this.throwExceptionOnNonFilterAndConverterMethods = throwExceptionOnNonFilterAndConverterMethods;
this.convertedValue = convertedValue;
}
@Override
public Object filterAndConvert(Object key, Object oldValue, Metadata oldMetadata, Object newValue, Metadata newMetadata, EventType eventType) {
return convertedValue;
}
@Override
public Object convert(Object key, Object oldValue, Metadata oldMetadata, Object newValue, Metadata newMetadata, EventType eventType) {
if (throwExceptionOnNonFilterAndConverterMethods) {
throw new AssertionError("Method should not have been invoked!");
}
return filterAndConvert(key, oldValue, oldMetadata, oldValue, oldMetadata, eventType);
}
@Override
public boolean accept(Object key, Object oldValue, Metadata oldMetadata, Object newValue, Metadata newMetadata, EventType eventType) {
if (throwExceptionOnNonFilterAndConverterMethods) {
throw new AssertionError("Method should not have been invoked!");
}
return filterAndConvert(key, oldValue, oldMetadata, oldValue, oldMetadata, eventType) != null;
}
}
protected void verifySimpleInsertion(Cache<Object, String> cache, Object key, String value, Long lifespan,
ClusterListener listener, Object expectedValue) {
if (lifespan != null) {
cache.put(key, value, lifespan, TimeUnit.MILLISECONDS);
} else {
cache.put(key, value);
}
verifySimpleInsertionEvents(listener, key, expectedValue);
}
protected void verifySimpleModification(Cache<Object, String> cache, Object key, String value, Long lifespan,
ClusterListener listener, Object expectedValue) {
if (lifespan != null) {
cache.put(key, value, lifespan, TimeUnit.MILLISECONDS);
} else {
cache.put(key, value);
}
verifySimpleModificationEvents(listener, key, expectedValue);
}
protected void verifySimpleInsertionEvents(ClusterListener listener, Object key, Object expectedValue) {
assertEquals(1, listener.events.size());
CacheEntryEvent event = listener.events.get(0);
assertEquals(Event.Type.CACHE_ENTRY_CREATED, event.getType());
assertEquals(key, event.getKey());
assertEquals(expectedValue, event.getValue());
}
protected void verifySimpleModificationEvents(ClusterListener listener, Object key, Object expectedValue) {
assertEquals(listener.hasIncludeState() ? 2 : 1, listener.events.size());
CacheEntryEvent event = listener.events.get(listener.hasIncludeState() ? 1 :0);
assertEquals(Event.Type.CACHE_ENTRY_MODIFIED, event.getType());
assertEquals(key, event.getKey());
assertEquals(expectedValue, event.getValue());
}
protected void verifySimpleExpirationEvents(ClusterListener listener, int expectedNumEvents, Object key, Object expectedValue) {
eventually(() -> listener.events.size() >= expectedNumEvents);
CacheEntryEvent event = listener.events.get(expectedNumEvents - 1); //the index starts from 0
assertEquals(Event.Type.CACHE_ENTRY_EXPIRED, event.getType());
assertEquals(key, event.getKey());
assertEquals(expectedValue, event.getValue());
}
protected void waitUntilListenerInstalled(final Cache<?, ?> cache, final CheckPoint checkPoint) {
CacheNotifier cn = TestingUtil.extractComponent(cache, CacheNotifier.class);
final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(cn);
ClusterCacheNotifier mockNotifier = mock(ClusterCacheNotifier.class, withSettings().defaultAnswer(forwardedAnswer));
doAnswer(invocation -> {
// Wait for main thread to sync up
checkPoint.trigger("pre_add_listener_invoked_" + cache);
// Now wait until main thread lets us through
checkPoint.awaitStrict("pre_add_listener_release_" + cache, 10, TimeUnit.SECONDS);
try {
return forwardedAnswer.answer(invocation);
} finally {
// Wait for main thread to sync up
checkPoint.trigger("post_add_listener_invoked_" + cache);
// Now wait until main thread lets us through
checkPoint.awaitStrict("post_add_listener_release_" + cache, 10, TimeUnit.SECONDS);
}
}).when(mockNotifier).addFilteredListener(notNull(), nullable(CacheEventFilter.class), nullable(CacheEventConverter.class), any(Set.class));
TestingUtil.replaceComponent(cache, CacheNotifier.class, mockNotifier, true);
}
protected void waitUntilNotificationRaised(final Cache<?, ?> cache, final CheckPoint checkPoint) {
CacheNotifier cn = TestingUtil.extractComponent(cache, CacheNotifier.class);
final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(cn);
CacheNotifier mockNotifier = mock(CacheNotifier.class,
withSettings().extraInterfaces(ClusterCacheNotifier.class)
.defaultAnswer(forwardedAnswer));
Answer answer = invocation -> {
// Wait for main thread to sync up
checkPoint.trigger("pre_raise_notification_invoked");
// Now wait until main thread lets us through
checkPoint.awaitStrict("pre_raise_notification_release", 10, TimeUnit.SECONDS);
try {
return forwardedAnswer.answer(invocation);
} finally {
// Wait for main thread to sync up
checkPoint.trigger("post_raise_notification_invoked");
// Now wait until main thread lets us through
checkPoint.awaitStrict("post_raise_notification_release", 10, TimeUnit.SECONDS);
}
};
doAnswer(answer).when(mockNotifier).notifyCacheEntryCreated(any(), any(), any(Metadata.class), eq(false),
any(InvocationContext.class), any(FlagAffectedCommand.class));
doAnswer(answer).when(mockNotifier).notifyCacheEntryModified(any(), any(), any(Metadata.class), any(),
any(Metadata.class), anyBoolean(),
any(InvocationContext.class), any(FlagAffectedCommand.class));
doAnswer(answer).when(mockNotifier).notifyCacheEntryRemoved(any(), any(), any(Metadata.class), eq(false),
any(InvocationContext.class),
any(FlagAffectedCommand.class));
TestingUtil.replaceComponent(cache, CacheNotifier.class, mockNotifier, true);
}
protected void waitUntilViewChangeOccurs(final CacheContainer cacheContainer, final String uniqueId, final CheckPoint checkPoint) {
CacheManagerNotifier cmn = TestingUtil.extractGlobalComponent(cacheContainer, CacheManagerNotifier.class);
final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(cmn);
CacheManagerNotifier mockNotifier = mock(CacheManagerNotifier.class, withSettings().defaultAnswer(forwardedAnswer));
doAnswer(invocation -> {
// Wait for main thread to sync up
checkPoint.trigger("pre_view_listener_invoked_" + uniqueId);
// Now wait until main thread lets us through
checkPoint.awaitStrict("pre_view_listener_release_" + uniqueId, 10, TimeUnit.SECONDS);
try {
return forwardedAnswer.answer(invocation);
} finally {
checkPoint.trigger("post_view_listener_invoked_" + uniqueId);
}
}).when(mockNotifier).notifyViewChange(anyList(), anyList(), any(Address.class), anyInt());
TestingUtil.replaceComponent(cacheContainer, CacheManagerNotifier.class, mockNotifier, true);
}
@AutoProtoSchemaBuilder(
dependsOn = org.infinispan.test.TestDataSCI.class,
includeClasses = {
AbstractClusterListenerUtilTest.FilterConverter.class,
AbstractClusterListenerUtilTest.LifespanConverter.class,
AbstractClusterListenerUtilTest.LifespanFilter.class,
AbstractClusterListenerUtilTest.NewLifespanLargerFilter.class,
AbstractClusterListenerUtilTest.StringAppender.class,
AbstractClusterListenerUtilTest.StringTruncator.class,
},
schemaFileName = "core.listeners.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.test.core.notifications",
service = false
)
interface ListenerSerializationContext extends SerializationContextInitializer {
}
}
| 19,176
| 42.584091
| 152
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerReplTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.infinispan.Cache;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.distribution.BlockingInterceptor;
import org.infinispan.distribution.MagicKey;
import org.infinispan.interceptors.impl.EntryWrappingInterceptor;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.ControlledRpcManager;
import org.testng.annotations.Test;
/**
* Cluster listener test having a configuration of non tx and replication
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerReplTest")
public class ClusterListenerReplTest extends AbstractClusterListenerNonTxTest {
public ClusterListenerReplTest() {
super(false, CacheMode.REPL_SYNC);
}
public void testPrimaryOwnerGoesDownBeforeBackupRaisesEvent() throws InterruptedException, TimeoutException,
ExecutionException {
final Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
// Now we want to block the outgoing put to the backup owner
ControlledRpcManager controlledRpcManager = ControlledRpcManager.replaceRpcManager(cache1);
final MagicKey key = new MagicKey(cache1, cache2);
Future<String> future = fork(() -> cache0.put(key, FIRST_VALUE));
// Wait until the primary owner has sent the put command successfully to the backups
ControlledRpcManager.BlockedRequest<?> blockedPut = controlledRpcManager.expectCommand(PutKeyValueCommand.class);
// And discard the request
blockedPut.skipSend();
// Kill the cache now
TestingUtil.killCacheManagers(cache1.getCacheManager());
// This should return null normally, but when it was retried it returns its own value
String returnValue = future.get(10, TimeUnit.SECONDS);
assertTrue(returnValue == null || returnValue.equals(FIRST_VALUE));
// We should have received an event that was marked as retried
assertTrue(clusterListener.events.size() >= 1);
// Because a rebalance has 4 phases, the command may be retried 4 times
assertTrue(clusterListener.events.size() <= 4);
for (CacheEntryEvent<Object, String> event : clusterListener.events) {
checkEvent(event, key, true, true);
}
}
public void testPrimaryOwnerGoesDownAfterBackupRaisesEvent() throws InterruptedException, TimeoutException,
ExecutionException, BrokenBarrierException {
final Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
CyclicBarrier barrier = new CyclicBarrier(3);
BlockingInterceptor<?> blockingInterceptor0 = new BlockingInterceptor<>(barrier, PutKeyValueCommand.class,
true, false);
extractInterceptorChain(cache0).addInterceptorBefore(blockingInterceptor0, EntryWrappingInterceptor.class);
BlockingInterceptor<?> blockingInterceptor2 = new BlockingInterceptor<>(barrier, PutKeyValueCommand.class,
true, false);
extractInterceptorChain(cache2).addInterceptorBefore(blockingInterceptor2, EntryWrappingInterceptor.class);
// this is a replicated cache, all other nodes are backup owners
final MagicKey key = new MagicKey(cache1);
Future<String> future = fork(() -> cache0.put(key, FIRST_VALUE));
// Wait until the primary owner has sent the put command successfully to both backups
barrier.await(10, TimeUnit.SECONDS);
// Remove the interceptor so the next command can proceed properly
extractInterceptorChain(cache0).removeInterceptor(BlockingInterceptor.class);
extractInterceptorChain(cache2).removeInterceptor(BlockingInterceptor.class);
blockingInterceptor0.suspend(true);
blockingInterceptor2.suspend(true);
// Kill the cache now - note this will automatically unblock the fork thread
TestingUtil.killCacheManagers(cache1.getCacheManager());
// Unblock the command
barrier.await(10, TimeUnit.SECONDS);
// This should return null normally, but since it was retried it returns it's own value :(
// Maybe some day this can work properly
String returnValue = future.get(10, TimeUnit.SECONDS);
assertEquals(FIRST_VALUE, returnValue);
// We should have received an event that was marked as retried
assertTrue(clusterListener.events.size() >= 2);
// Because a rebalance has 4 phases, the command may be retried 4 times
assertTrue(clusterListener.events.size() <= 4);
// First create should not be retried since it was sent before node failure.
checkEvent(clusterListener.events.get(0), key, true, false);
// Events from retried commands are a MODIFY since CREATE was already done
for (int i = 1; i < clusterListener.events.size(); i++) {
CacheEntryEvent<Object, String> event = clusterListener.events.get(i);
checkEvent(event, key, false, true);
}
checkEvent(clusterListener.events.get(1), key, false, true);
}
}
| 6,120
| 45.725191
| 119
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerFilterWithDependenciesTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.testng.AssertJUnit.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.fwk.InCacheMode;
import org.testng.annotations.Test;
/**
* @author anistor@redhat.com
* @since 7.2
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerFilterWithDependenciesTest")
@InCacheMode({ CacheMode.DIST_SYNC })
public class ClusterListenerFilterWithDependenciesTest extends MultipleCacheManagersTest {
private final int NUM_NODES = 2;
private final int NUM_ENTRIES = 10;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = getDefaultClusteredCacheConfig(cacheMode, false);
createClusteredCaches(NUM_NODES, new ClusterListenerWithDependenciesSCIImpl(), cfgBuilder);
}
public void testEventFilterCurrentState() {
for (int i = 0; i < NUM_ENTRIES; ++i) {
Cache<Object, String> cache = cache(i % NUM_NODES);
Object key = new MagicKey(cache);
cache.put(key, "string " + i);
}
assertEquals(NUM_ENTRIES, cache(0).size());
EntryListener listener = new EntryListener();
NoOpCacheEventFilterConverterWithDependencies filterConverter = new NoOpCacheEventFilterConverterWithDependencies();
cache(0).addListener(listener, filterConverter, filterConverter);
assertEquals(NUM_ENTRIES, listener.createEvents.size());
cache(0).removeListener(listener);
}
public void testEventFilter() {
EntryListener listener = new EntryListener();
NoOpCacheEventFilterConverterWithDependencies filterConverter = new NoOpCacheEventFilterConverterWithDependencies();
cache(0).addListener(listener, filterConverter, filterConverter);
for (int i = 0; i < NUM_ENTRIES; ++i) {
Cache<Object, String> cache = cache(i % NUM_NODES);
Object key = new MagicKey(cache);
cache.put(key, "string " + i);
}
assertEquals(NUM_ENTRIES, cache(0).size());
assertEquals(NUM_ENTRIES, listener.createEvents.size());
cache(0).removeListener(listener);
}
@Listener(clustered = true, includeCurrentState = true)
public static class EntryListener {
public final List<CacheEntryCreatedEvent> createEvents = Collections.synchronizedList(new ArrayList<>());
@CacheEntryCreated
public void handleEvent(CacheEntryCreatedEvent event) {
if (!event.isPre()) {
createEvents.add(event);
}
}
}
@AutoProtoSchemaBuilder(
includeClasses = {
MagicKey.class,
NoOpCacheEventFilterConverterWithDependencies.class
},
schemaFileName = "test.core.ClusterListenerFilterWithDependenciesTest.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.test.core.ClusterListenerFilterWithDependenciesTest",
service = false
)
interface ClusterListenerWithDependenciesSCI extends SerializationContextInitializer {
}
}
| 3,725
| 35.891089
| 122
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerDistTxInitialStateTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import org.testng.annotations.Test;
/**
* Cluster listener test to make sure that when include current state is enabled that listeners still work properly
* in a distributed transactional cache
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerDistTxInitialStateTest")
public class ClusterListenerDistTxInitialStateTest extends ClusterListenerDistTxTest {
@Override
protected ClusterListener listener() {
return new ClusterListenerWithIncludeCurrentState();
}
}
| 622
| 31.789474
| 116
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/AbstractClusterListenerNonTxTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.infinispan.test.TestingUtil.extractCacheTopology;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.distribution.MagicKey;
import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent;
import org.infinispan.notifications.cachelistener.event.Event;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CheckPoint;
import org.infinispan.util.concurrent.CommandAckCollector;
import org.testng.annotations.Test;
/**
* Tests for cluster listeners that are specific to non tx
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional")
public abstract class AbstractClusterListenerNonTxTest extends AbstractClusterListenerTest {
protected AbstractClusterListenerNonTxTest(boolean tx, CacheMode cacheMode) {
super(tx, cacheMode);
}
@Test
public void testPrimaryOwnerGoesDownAfterSendingEvent() throws InterruptedException, ExecutionException,
TimeoutException {
final Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = listener();
cache0.addListener(clusterListener);
CheckPoint checkPoint = new CheckPoint();
waitUntilNotificationRaised(cache1, checkPoint);
checkPoint.triggerForever("pre_raise_notification_release");
final MagicKey key = new MagicKey(cache1, cache2);
Future<String> future = fork(() -> cache0.put(key, FIRST_VALUE));
checkPoint.awaitStrict("post_raise_notification_invoked", 10, TimeUnit.SECONDS);
awaitForBackups(cache0);
// Kill the cache now - note this will automatically unblock the fork thread
TestingUtil.killCacheManagers(cache1.getCacheManager());
future.get(10, TimeUnit.SECONDS);
TestingUtil.waitForNoRebalance(cache0, cache2);
// The command is retried during rebalance, but there are 5 topology updates (thus up to 5 retries)
// 1: top - 1 NO_REBALANCE
// 2: top READ_OLD_WRITE_ALL
// 3: top READ_ALL_WRITE_ALL
// 4: top READ_NEW_WRITE_ALL
// 5: top NO_REBALANCE
assertTrue("Expected 2 - 6 events, but received " + clusterListener.events,
clusterListener.events.size() >= 2 && clusterListener.events.size() <= 6);
// Since the first event was generated properly it is a create without retry
checkEvent(clusterListener.events.get(0), key, true, false);
Address cache0primary = extractCacheTopology(cache0).getDistribution(key).primary();
Address cache2primary = extractCacheTopology(cache2).getDistribution(key).primary();
// we expect that now both nodes have the same topology
assertEquals(cache0primary, cache2primary);
// Any extra events would be retries as modifications
clusterListener.events.stream().skip(1).forEach(e -> checkEvent(e, key, false, true));
}
protected void checkEvent(CacheEntryEvent<Object, String> event, MagicKey key, boolean isCreated, boolean isRetried) {
CacheEntryCreatedEvent<Object, String> createEvent;
if (isCreated) {
assertEquals(event.getType(), Event.Type.CACHE_ENTRY_CREATED);
createEvent = (CacheEntryCreatedEvent<Object, String>)event;
assertEquals(createEvent.isCommandRetried(), isRetried);
} else {
assertEquals(event.getType(), Event.Type.CACHE_ENTRY_MODIFIED);
CacheEntryModifiedEvent<Object, String> modEvent = (CacheEntryModifiedEvent<Object, String>) event;
assertTrue(modEvent.isCommandRetried());
}
assertEquals(event.getKey(), key);
assertEquals(event.getValue(), FIRST_VALUE);
}
protected void awaitForBackups(Cache<?, ?> cache) {
if (TestingUtil.isTriangleAlgorithm(cacheMode, tx)) {
CommandAckCollector collector = TestingUtil.extractComponent(cache, CommandAckCollector.class);
List<Long> pendingCommands = collector.getPendingCommands();
//only 1 put is waiting (it may receive the backup ack, but not the primary ack since it is blocked!)
assertEquals(1, pendingCommands.size());
//make sure that the backup received the update
eventually(() -> !collector.hasPendingBackupAcks(pendingCommands.get(0)));
}
}
}
| 4,993
| 43.990991
| 121
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerReplInitialStateTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import org.testng.annotations.Test;
/**
* Cluster listener test to make sure that when include current state is enabled that listeners still work properly
* in a replicated cache
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerReplInitialStateTest")
public class ClusterListenerReplInitialStateTest extends ClusterListenerReplTest {
@Override
protected ClusterListener listener() {
return new ClusterListenerWithIncludeCurrentState();
}
}
| 601
| 30.684211
| 115
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusteredListenerJoinsTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.testng.AssertJUnit.assertEquals;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.fwk.InCacheMode;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusteredListenerJoinsTest")
@InCacheMode({ CacheMode.DIST_SYNC })
public class ClusteredListenerJoinsTest extends MultipleCacheManagersTest {
@Listener(clustered = true)
private static final class NoOpListener {
@CacheEntryCreated
public void handleEvent(CacheEntryEvent<Object, Object> e) {
}
}
@Override
protected void createCacheManagers() {
ConfigurationBuilder c = buildConfiguration();
createCluster(c, 3);
waitForClusterToForm();
}
private ConfigurationBuilder buildConfiguration() {
ConfigurationBuilder c = getDefaultClusteredCacheConfig(cacheMode, false); //unreproducible with CacheMode.REPL_SYNC
return c;
}
public void testJoins() {
int cache0Size = cache(0).getListeners().size();
int cache1Size = cache(1).getListeners().size();
cache(0).addListener(new NoOpListener());
addClusterEnabledCacheManager(buildConfiguration());
cache(0).addListener(new NoOpListener());
waitForClusterToForm();
// Now we verify the listener was actually added - since this is a DIST cache we also have the local listener
// that sends remote and we added 2 of them
assertEquals(cache0Size + 2, cache(0).getListeners().size());
assertEquals(cache1Size + 2, cache(1).getListeners().size());
}
}
| 1,977
| 34.321429
| 122
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/AbstractClusterListenerDistAddListenerTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.statetransfer.StateProvider;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CheckPoint;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.concurrent.IsolationLevel;
import org.mockito.AdditionalAnswers;
import org.mockito.stubbing.Answer;
import org.testng.annotations.Test;
/**
* Base class to be used for cluster listener tests for both tx and nontx distributed caches
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional")
public abstract class AbstractClusterListenerDistAddListenerTest extends AbstractClusterListenerUtilTest {
protected AbstractClusterListenerDistAddListenerTest(boolean tx) {
super(tx, CacheMode.DIST_SYNC);
}
@Override
protected void createCacheManagers() throws Throwable {
builderUsed = new ConfigurationBuilder();
// Disable conflict resolution on merge as StateProvider mocks are used in this#waitUntilRequestingListeners
builderUsed.clustering().cacheMode(cacheMode).partitionHandling().mergePolicy(null);
if (tx) {
builderUsed.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
builderUsed.locking().isolationLevel(IsolationLevel.READ_COMMITTED);
}
builderUsed.expiration().disableReaper();
createClusteredCaches(3, CACHE_NAME, TestDataSCI.INSTANCE, builderUsed);
injectTimeServices();
}
/**
* This test is to verify then when a new node joins and a cluster listener is installed after the cluster listener
* request is finished that it finds it.
*
* Node 1, 2, 3 exists
* Node 2 adds cluster listener - knows to send to listener to Node 1
* Node 4 starts up
* Node 4 asks Node 1 for listeners (gets none)
* Node 1 receives Node 2 listener
*
* Test needs to verify in this case that Node 3 gets the listener from Node 2
*/
@Test
public void testMemberJoinsWhileClusterListenerInstalled() throws TimeoutException, InterruptedException,
ExecutionException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
final Cache<Object, String> cache1 = cache(1, CACHE_NAME);
CheckPoint checkPoint = new CheckPoint();
waitUntilListenerInstalled(cache0, checkPoint);
// We don't want this blocking
checkPoint.triggerForever("post_add_listener_release_" + cache0);
final ClusterListener clusterListener = new ClusterListener();
Future<Void> future = fork(() -> {
cache1.addListener(clusterListener);
return null;
});
// Now wait until the listener is about to be installed on cache1
checkPoint.awaitStrict("pre_add_listener_invoked_" + cache0, 10, TimeUnit.SECONDS);
addClusteredCacheManager();
// Now wait for cache3 to come up fully
waitForClusterToForm(CACHE_NAME);
Cache<Object, String> cache3 = cache(3, CACHE_NAME);
// Finally let the listener be added
checkPoint.triggerForever("pre_add_listener_release_" + cache0);
future.get(10, TimeUnit.SECONDS);
MagicKey key = new MagicKey(cache3);
verifySimpleInsertion(cache3, key, FIRST_VALUE, null, clusterListener, FIRST_VALUE);
}
/**
* Ths test is very similar to {@link AbstractClusterListenerDistAddListenerTest#testMemberJoinsWhileClusterListenerInstalled} except that
* the listener was retrieved in the initial request and thus would have received 2 callables to install the listener.
* We need to make sure this doesn't cause 2 listeners to be installed causing duplicate messages.
*/
@Test
public void testMemberJoinsWhileClusterListenerInstalledDuplicate() throws TimeoutException, InterruptedException,
ExecutionException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
final Cache<Object, String> cache1 = cache(1, CACHE_NAME);
CheckPoint checkPoint = new CheckPoint();
waitUntilListenerInstalled(cache0, checkPoint);
// We want the listener to be able to be added
checkPoint.triggerForever("pre_add_listener_release_" + cache0);
final ClusterListener clusterListener = new ClusterListener();
Future<Void> future = fork(() -> {
cache1.addListener(clusterListener);
return null;
});
// Now wait until the listener is about to be installed on cache1
checkPoint.awaitStrict("post_add_listener_invoked_" + cache0, 10, TimeUnit.SECONDS);
addClusteredCacheManager();
// Now wait for cache3 to come up fully
waitForClusterToForm(CACHE_NAME);
Cache<Object, String> cache3 = cache(3, CACHE_NAME);
// Finally let the listener be added
checkPoint.triggerForever("post_add_listener_release_" + cache0);
future.get(10, TimeUnit.SECONDS);
MagicKey key = new MagicKey(cache3);
verifySimpleInsertion(cache3, key, FIRST_VALUE, null, clusterListener, FIRST_VALUE);
}
/**
* This test is to make sure that if a new node comes up and requests the current cluster listeners that after
* that is retrieved before processing the response that the node who has the cluster listener dies that we
* don't keep the local cluster listener around for no reason
* <p>
* This may not be feasible since the cluster listener request is during topology change and
*/
@Test
public void testMemberJoinsAndRetrievesClusterListenersButMainListenerNodeDiesBeforeInstalled()
throws TimeoutException, InterruptedException, ExecutionException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
final Cache<Object, String> cache1 = cache(1, CACHE_NAME);
final ClusterListener clusterListener = new ClusterListener();
cache1.addListener(clusterListener);
assertEquals(manager(0).getAddress(), manager(0).getMembers().get(0));
CheckPoint checkPoint = new CheckPoint();
waitUntilRequestingListeners(cache0, checkPoint);
checkPoint.triggerForever("pre_cluster_listeners_release_" + cache0);
addClusteredCacheManager();
Future<Cache<Object, String>> future = fork(() -> cache(3, CACHE_NAME));
checkPoint.awaitStrict("post_cluster_listeners_invoked_" + cache0, 10, TimeUnit.SECONDS);
log.info("Killing node 1 ..");
// Notice we are killing the manager that doesn't have a cache with the cluster listener
TestingUtil.killCacheManagers(manager(1));
cacheManagers.remove(1);
log.info("Node 1 killed");
checkPoint.triggerForever("post_cluster_listeners_release_" + cache0);
// Now wait for cache3 to come up fully
TestingUtil.blockUntilViewsReceived(10000, false, cacheManagers);
TestingUtil.waitForNoRebalance(caches(CACHE_NAME));
Cache<Object, String> cache3 = future.get(10, TimeUnit.SECONDS);
for (Object listener : cache3.getAdvancedCache().getListeners()) {
assertFalse(listener instanceof RemoteClusterListener);
}
}
/**
* Tests to make sure that if a new node is joining and the node it requested
*/
@Test
public void testNodeJoiningAndStateNodeDiesWithExistingClusterListener() throws TimeoutException,
InterruptedException,
ExecutionException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
int initialCache0ListenerSize = cache0.getAdvancedCache().getListeners().size();
int initialCache1ListenerSize = cache1.getAdvancedCache().getListeners().size();
int initialCache2ListenerSize = cache2.getAdvancedCache().getListeners().size();
ClusterListener clusterListener = new ClusterListener();
cache2.addListener(clusterListener);
assertEquals(cache0.getAdvancedCache().getListeners().size(), initialCache0ListenerSize +
(cacheMode.isDistributed() ? 1 : 0));
assertEquals(cache1.getAdvancedCache().getListeners().size(), initialCache1ListenerSize +
(cacheMode.isDistributed() ? 1 : 0));
assertEquals(cache2.getAdvancedCache().getListeners().size(), initialCache2ListenerSize + 1);
assertEquals(manager(0).getAddress(), manager(0).getMembers().get(0));
CheckPoint checkPoint = new CheckPoint();
waitUntilRequestingListeners(cache0, checkPoint);
checkPoint.triggerForever("post_cluster_listeners_release_" + cache0);
addClusteredCacheManager();
Future<Cache<Object, String>> future = fork(() -> cache(3, CACHE_NAME));
checkPoint.awaitStrict("pre_cluster_listeners_invoked_" + cache0, 10, TimeUnit.SECONDS);
log.info("Killing node 0 ..");
// Notice we are killing the manager that doesn't have a cache with the cluster listener
TestingUtil.killCacheManagers(manager(0));
cacheManagers.remove(0);
log.info("Node 0 killed");
TestingUtil.blockUntilViewsReceived(10000, false, cacheManagers);
TestingUtil.waitForNoRebalance(caches(CACHE_NAME));
checkPoint.triggerForever("pre_cluster_listeners_invoked_" + cache0);
Cache<Object, String> cache3 = future.get(10, TimeUnit.SECONDS);
MagicKey key = new MagicKey(cache3);
verifySimpleInsertion(cache3, key, FIRST_VALUE, null, clusterListener, FIRST_VALUE);
}
/**
* The premise is the same as {@link AbstractClusterListenerDistAddListenerTest#testNodeJoiningAndStateNodeDiesWithExistingClusterListener}.
* This also has the twist of the fact that the node who dies is also has the cluster listener. This test makes sure
* that the subsequent node asked for cluster listeners hasn't yet got the view change and still has the cluster
* listener in it. Also the requesting node should have the view change before installing.
*/
@Test(enabled = false, description = "Test may not be doable, check TODO in test")
public void testNodeJoiningAndStateNodeDiesWhichHasClusterListener() throws TimeoutException,
InterruptedException,
ExecutionException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
int initialCache0ListenerSize = cache0.getAdvancedCache().getListeners().size();
int initialCache1ListenerSize = cache1.getAdvancedCache().getListeners().size();
int initialCache2ListenerSize = cache2.getAdvancedCache().getListeners().size();
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
assertEquals(cache0.getAdvancedCache().getListeners().size(), initialCache0ListenerSize + 1);
assertEquals(cache1.getAdvancedCache().getListeners().size(), initialCache1ListenerSize + 1);
assertEquals(cache2.getAdvancedCache().getListeners().size(), initialCache2ListenerSize + 1);
// Make sure cache0 will be the one will get the cluster listener request
assertEquals(manager(0).getAddress(), manager(0).getMembers().get(0));
CheckPoint checkPoint = new CheckPoint();
waitUntilRequestingListeners(cache0, checkPoint);
checkPoint.triggerForever("post_cluster_listeners_release_" + cache0);
waitUntilViewChangeOccurs(manager(1), "manager1", checkPoint);
// We let the first view change occur just fine on cache1 (this will be the addition of cache3).
// What we want to block is the second one which is the removal of cache0
checkPoint.trigger("pre_view_listener_release_" + "manager1");
addClusteredCacheManager();
waitUntilViewChangeOccurs(manager(3), "manager3", checkPoint);
// We don't want to block the view listener change on cache3
checkPoint.trigger("pre_view_listener_release_" + "manager3");
Future<Cache<Object, String>> future = fork(() -> cache(3, CACHE_NAME));
// Wait for view change to occur on cache1 for the addition of cache3
// Note we haven't triggered the view change for cache1 for the following removal yet
checkPoint.awaitStrict("post_view_listener_invoked_" + "manager1", 10, TimeUnit.SECONDS);
// Wait for the cluster listener request to come into cache0 which is from cache3
checkPoint.awaitStrict("pre_cluster_listeners_invoked_" + cache0, 10, TimeUnit.SECONDS);
// Now we kill cache0 while it is processing the request from cache3, which will in turn force it to ask cache1
log.info("Killing node 0 ..");
TestingUtil.killCacheManagers(manager(0));
cacheManagers.remove(0);
log.info("Node 0 killed");
// TODO: need a away to verify that the response was sent back to cache3 before releasing the next line. However
// with no reference to cache I don't think this is possible. If this can be fixed then test can be reenabled
Cache<Object, String> cache3 = future.get(10, TimeUnit.SECONDS);
// Now we can finally let the view change complete on cache1
checkPoint.triggerForever("pre_view_listener_release_" + "manager1");
// Now wait for cache3 to come up fully
TestingUtil.blockUntilViewsReceived(60000, false, cache1, cache2);
TestingUtil.waitForNoRebalance(cache1, cache2);
MagicKey key = new MagicKey(cache3);
cache3.put(key, FIRST_VALUE);
assertEquals(cache1.getAdvancedCache().getListeners().size(), initialCache1ListenerSize);
assertEquals(cache2.getAdvancedCache().getListeners().size(), initialCache2ListenerSize);
// Since we can't get a reliable start count, make sure no RemoteClusterListener is present which is added for
// a cluster listener
for (Object listener : cache3.getAdvancedCache().getListeners()) {
assertFalse(listener instanceof RemoteClusterListener);
}
}
protected void waitUntilRequestingListeners(final Cache<?, ?> cache, final CheckPoint checkPoint) {
StateProvider sp = TestingUtil.extractComponent(cache, StateProvider.class);
final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(sp);
StateProvider mockProvider = mock(StateProvider.class, withSettings().defaultAnswer(forwardedAnswer));
doAnswer(invocation -> {
// Wait for main thread to sync up
checkPoint.trigger("pre_cluster_listeners_invoked_" + cache);
// Now wait until main thread lets us through
checkPoint.awaitStrict("pre_cluster_listeners_release_" + cache, 10, TimeUnit.SECONDS);
try {
return forwardedAnswer.answer(invocation);
} finally {
// Wait for main thread to sync up
checkPoint.trigger("post_cluster_listeners_invoked_" + cache);
// Now wait until main thread lets us through
checkPoint.awaitStrict("post_cluster_listeners_release_" + cache, 10, TimeUnit.SECONDS);
}
}).when(mockProvider).getClusterListenersToInstall();
TestingUtil.replaceComponent(cache, StateProvider.class, mockProvider, true);
}
}
| 16,080
| 45.342939
| 143
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerDistTxAddListenerTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import org.testng.annotations.Test;
/**
* Cluster listener test having a configuration of non tx and dist when adding listeners at inopportune times
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerDistTxAddListenerTest")
public class ClusterListenerDistTxAddListenerTest extends AbstractClusterListenerDistAddListenerTest {
public ClusterListenerDistTxAddListenerTest() {
super(true);
}
}
| 547
| 31.235294
| 115
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerInvalTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* This tests is to make sure that a cluster listener may not be used with invalidation. The reason being is that
* we don't have a single owner to guarantee ordering.
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerInvalTest")
public class ClusterListenerInvalTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
// start a single cache instance
ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.INVALIDATION_SYNC);
return TestCacheManagerFactory.createClusteredCacheManager(c);
}
@Listener(clustered = true)
private static class ClusterListener {
@CacheEntryCreated
public void created(CacheEntryEvent event) {
}
}
@Test(expectedExceptions = UnsupportedOperationException.class)
public void testEnsureClusterListenerNotSupportedForInvalidation() {
cache.addListener(new ClusterListener());
}
}
| 1,612
| 37.404762
| 114
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerDistTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.infinispan.Cache;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.distribution.BlockingInterceptor;
import org.infinispan.distribution.MagicKey;
import org.infinispan.interceptors.distribution.TriangleDistributionInterceptor;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
/**
* Cluster listener test having a configuration of non tx and dist
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerDistTest")
public class ClusterListenerDistTest extends AbstractClusterListenerNonTxTest {
public ClusterListenerDistTest() {
super(false, CacheMode.DIST_SYNC);
}
@Test
public void testPrimaryOwnerGoesDownBeforeSendingEvent() throws InterruptedException, TimeoutException,
ExecutionException, BrokenBarrierException {
final Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
CyclicBarrier barrier = new CyclicBarrier(2);
BlockingInterceptor blockingInterceptor = new BlockingInterceptor<>(barrier, PutKeyValueCommand.class, true, false);
cache1.getAdvancedCache().getAsyncInterceptorChain().addInterceptorBefore(blockingInterceptor, TriangleDistributionInterceptor.class);
final MagicKey key = new MagicKey(cache1, cache2);
Future<String> future = fork(() -> cache0.put(key, FIRST_VALUE));
// Wait until the primary owner has sent the put command successfully to backup
barrier.await(10, TimeUnit.SECONDS);
awaitForBackups(cache0);
// Kill the cache now - note this will automatically unblock the fork thread
TestingUtil.killCacheManagers(cache1.getCacheManager());
// This should return null normally, but since it was retried it returns it's own value :(
// Maybe some day this can work properly
assertEquals(future.get(10, TimeUnit.SECONDS), FIRST_VALUE);
TestingUtil.waitForNoRebalance(cache0, cache2);
// The command is retried during rebalance, but there are 5 topology updates (thus up to 5 retries)
// 1: top - 1 NO_REBALANCE
// 2: top READ_OLD_WRITE_ALL
// 3: top READ_ALL_WRITE_ALL
// 4: top READ_NEW_WRITE_ALL
// 5: top NO_REBALANCE
assertTrue("Expected 1 - 5 events, but received " + clusterListener.events,
clusterListener.events.size() >= 1 && clusterListener.events.size() <= 5);
Address cache0primary = cache0.getAdvancedCache().getDistributionManager().getCacheTopology().getDistribution(key).primary();
Address cache2primary = cache2.getAdvancedCache().getDistributionManager().getCacheTopology().getDistribution(key).primary();
// we expect that now both nodes have the same topology
assertEquals(cache0primary, cache2primary);
clusterListener.events.forEach(e -> checkEvent(e, key, false, true));
}
}
| 3,713
| 44.292683
| 140
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerDistInitialStateTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import org.testng.annotations.Test;
/**
* Cluster listener test to make sure that when include current state is enabled that listeners still work properly
* in a distributed cache
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerDistInitialStateTest")
public class ClusterListenerDistInitialStateTest extends ClusterListenerDistTest {
@Override
protected ClusterListener listener() {
return new ClusterListenerWithIncludeCurrentState();
}
}
| 602
| 30.736842
| 115
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerReplTxInitialStateTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import org.testng.annotations.Test;
/**
* Cluster listener test to make sure that when include current state is enabled that listeners still work properly
* in a replicated transactional cache
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerReplTxInitialStateTest")
public class ClusterListenerReplTxInitialStateTest extends ClusterListenerReplTxTest {
@Override
protected ClusterListener listener() {
return new ClusterListenerWithIncludeCurrentState();
}
}
| 621
| 31.736842
| 116
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/AbstractClusterListenerTxTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Collection;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.distribution.MagicKey;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.Event;
import org.testng.annotations.Test;
/**
* This is a base class defining tests that are common across transactional tests when dealing with a cluster listener
*
* @author wburns
* @since 4.0
*/
@Test(groups = "functional")
public abstract class AbstractClusterListenerTxTest extends AbstractClusterListenerTest {
protected AbstractClusterListenerTxTest(CacheMode cacheMode) {
super(true, cacheMode);
}
// Checks the given events to see if an entry was marked as being created for the provided key and value
// Note this will have to iterate over all the events until one is found, since it is possible to get the events in
// non-deterministic order since they aren't from the same node
protected void verifyCreation(Collection<CacheEntryEvent> events, Object key, Object expectedValue) {
boolean found = false;
for (CacheEntryEvent event : events) {
if (Event.Type.CACHE_ENTRY_CREATED == event.getType() && key.equals(event.getKey()) &&
expectedValue.equals(event.getValue())) {
found = true;
break;
}
}
assertTrue(found, "No entry was created in provided events " + events + " matching key " + key + " and value " +
expectedValue);
}
@Test
public void testBatchedCommitOriginatorNotLocal() throws SystemException, NotSupportedException, HeuristicRollbackException,
HeuristicMixedException, RollbackException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
MagicKey key1 = new MagicKey(cache1, cache2);
MagicKey key2 = new MagicKey(cache2, cache1);
TransactionManager tm = cache2.getAdvancedCache().getTransactionManager();
tm.begin();
cache2.put(key1, FIRST_VALUE);
assertEquals(clusterListener.events.size(), 0);
cache2.put(key2, SECOND_VALUE);
assertEquals(clusterListener.events.size(), 0);
tm.commit();
assertEquals(clusterListener.events.size(), 2);
verifyCreation(clusterListener.events, key1, FIRST_VALUE);
verifyCreation(clusterListener.events, key2, SECOND_VALUE);
}
@Test
public void testBatchedCommitKeyNotLocalLocal() throws HeuristicRollbackException, RollbackException, HeuristicMixedException,
SystemException, NotSupportedException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
MagicKey key1 = new MagicKey(cache1, cache2);
MagicKey key2 = new MagicKey(cache2, cache1);
TransactionManager tm = cache2.getAdvancedCache().getTransactionManager();
tm.begin();
cache0.put(key1, FIRST_VALUE);
assertEquals(clusterListener.events.size(), 0);
cache0.put(key2, SECOND_VALUE);
assertEquals(clusterListener.events.size(), 0);
tm.commit();
assertEquals(clusterListener.events.size(), 2);
verifyCreation(clusterListener.events, key1, FIRST_VALUE);
verifyCreation(clusterListener.events, key2, SECOND_VALUE);
}
@Test
public void testBatchedCommitLocal() throws HeuristicRollbackException, RollbackException, HeuristicMixedException,
SystemException, NotSupportedException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
MagicKey key1 = new MagicKey(cache0);
MagicKey key2 = new MagicKey(cache1, cache0);
TransactionManager tm = cache2.getAdvancedCache().getTransactionManager();
tm.begin();
cache0.put(key1, FIRST_VALUE);
assertEquals(clusterListener.events.size(), 0);
cache0.put(key2, SECOND_VALUE);
assertEquals(clusterListener.events.size(), 0);
tm.commit();
assertEquals(clusterListener.events.size(), 2);
verifyCreation(clusterListener.events, key1, FIRST_VALUE);
verifyCreation(clusterListener.events, key2, SECOND_VALUE);
}
@Test
public void testRolledBackNotLocal() throws SystemException, NotSupportedException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
MagicKey key1 = new MagicKey(cache1, cache2);
MagicKey key2 = new MagicKey(cache2, cache1);
TransactionManager tm = cache2.getAdvancedCache().getTransactionManager();
tm.begin();
cache2.put(key1, FIRST_VALUE);
assertEquals(clusterListener.events.size(), 0);
cache2.put(key2, SECOND_VALUE);
assertEquals(clusterListener.events.size(), 0);
tm.rollback();
assertEquals(clusterListener.events.size(), 0);
}
@Test
public void testRolledBackOriginatorNotLocal() throws SystemException, NotSupportedException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
MagicKey key1 = new MagicKey(cache0);
MagicKey key2 = new MagicKey(cache1, cache0);
TransactionManager tm = cache2.getAdvancedCache().getTransactionManager();
tm.begin();
cache2.put(key1, FIRST_VALUE);
assertEquals(clusterListener.events.size(), 0);
cache2.put(key2, SECOND_VALUE);
assertEquals(clusterListener.events.size(), 0);
tm.rollback();
assertEquals(clusterListener.events.size(), 0);
}
@Test
public void testRolledBackLocal() throws SystemException, NotSupportedException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
MagicKey key1 = new MagicKey(cache0);
MagicKey key2 = new MagicKey(cache1, cache0);
TransactionManager tm = cache2.getAdvancedCache().getTransactionManager();
tm.begin();
cache0.put(key1, FIRST_VALUE);
assertEquals(clusterListener.events.size(), 0);
cache0.put(key2, SECOND_VALUE);
assertEquals(clusterListener.events.size(), 0);
tm.rollback();
assertEquals(clusterListener.events.size(), 0);
}
@Test
public void testMultipleKeysSameOwnerBatchNotified() throws SystemException, NotSupportedException, HeuristicRollbackException,
HeuristicMixedException, RollbackException {
Cache<Object, String> cache0 = cache(0, CACHE_NAME);
Cache<Object, String> cache1 = cache(1, CACHE_NAME);
Cache<Object, String> cache2 = cache(2, CACHE_NAME);
ClusterListener clusterListener = new ClusterListener();
cache0.addListener(clusterListener);
MagicKey key1 = new MagicKey(cache1);
MagicKey key2 = new MagicKey(cache1);
TransactionManager tm = cache2.getAdvancedCache().getTransactionManager();
tm.begin();
cache2.put(key1, FIRST_VALUE);
assertEquals(clusterListener.events.size(), 0);
cache2.put(key2, SECOND_VALUE);
assertEquals(clusterListener.events.size(), 0);
tm.commit();
assertEquals(clusterListener.events.size(), 2);
verifyCreation(clusterListener.events, key1, FIRST_VALUE);
verifyCreation(clusterListener.events, key2, SECOND_VALUE);
}
}
| 8,995
| 35.868852
| 130
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerDistAddListenerTest.java
|
package org.infinispan.notifications.cachelistener.cluster;
import org.testng.annotations.Test;
/**
* Cluster listener test having a configuration of non tx and dist when adding listeners at inopportune times
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "notifications.cachelistener.cluster.ClusterListenerDistAddListenerTest")
public class ClusterListenerDistAddListenerTest extends AbstractClusterListenerDistAddListenerTest {
public ClusterListenerDistAddListenerTest() {
super(false);
}
}
| 542
| 30.941176
| 113
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachemanagerlistener/CacheManagerNotifierImplTest.java
|
package org.infinispan.notifications.cachemanagerlistener;
import static org.mockito.Mockito.mock;
import java.util.Collections;
import java.util.List;
import org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent;
import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent;
import org.infinispan.notifications.cachemanagerlistener.event.Event;
import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "notifications.cachemanagerlistener.CacheManagerNotifierImplTest")
public class CacheManagerNotifierImplTest extends AbstractInfinispanTest {
CacheManagerNotifierImpl n;
CacheManagerListener cl;
@BeforeMethod
public void setUp() {
n = new CacheManagerNotifierImpl();
cl = new CacheManagerListener();
n.start();
n.addListener(cl);
}
public void testNotifyViewChanged() {
Address a = mock(Address.class);
List<Address> addresses = Collections.emptyList();
n.notifyViewChange(addresses, addresses, a, 100);
assert cl.invocationCount == 1;
assert ((ViewChangedEvent) cl.getEvent()).getLocalAddress() == a;
assert ((ViewChangedEvent) cl.getEvent()).getNewMembers() == addresses;
assert ((ViewChangedEvent) cl.getEvent()).getViewId() == 100;
assert cl.getEvent().getType() == Event.Type.VIEW_CHANGED;
}
public void testNotifyCacheStarted() {
n.notifyCacheStarted("cache");
assert cl.invocationCount == 1;
assert ((CacheStartedEvent) cl.getEvent()).getCacheName().equals("cache");
assert cl.getEvent().getType() == Event.Type.CACHE_STARTED;
}
public void testNotifyCacheStopped() {
n.notifyCacheStopped("cache");
assert cl.invocationCount == 1;
assert ((CacheStoppedEvent) cl.getEvent()).getCacheName().equals("cache");
assert cl.getEvent().getType() == Event.Type.CACHE_STOPPED;
}
}
| 2,124
| 35.016949
| 100
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachemanagerlistener/CacheManagerListener.java
|
package org.infinispan.notifications.cachemanagerlistener;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStarted;
import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStopped;
import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged;
import org.infinispan.notifications.cachemanagerlistener.event.Event;
@Listener
public class CacheManagerListener {
Event event;
int invocationCount;
public void reset() {
event = null;
invocationCount = 0;
}
public Event getEvent() {
return event;
}
public int getInvocationCount() {
return invocationCount;
}
// handler
@CacheStarted
@CacheStopped
@ViewChanged
public void handle(Event e) {
event = e;
invocationCount++;
}
}
| 861
| 22.944444
| 81
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/notifications/cachemanagerlistener/CacheManagerNotifierTest.java
|
package org.infinispan.notifications.cachemanagerlistener;
import static org.testng.AssertJUnit.assertNotNull;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.manager.CacheContainer;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged;
import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "notifications.cachemanagerlistener.CacheManagerNotifierTest")
public class CacheManagerNotifierTest extends AbstractInfinispanTest {
public void testViewChange() throws Exception {
EmbeddedCacheManager cmA = TestCacheManagerFactory.createClusteredCacheManager();
CacheContainer cmB = null;
try {
cmA.getCache();
GetCacheManagerCheckListener listener = new GetCacheManagerCheckListener();
cmA.addListener(listener);
cmB = TestCacheManagerFactory.createClusteredCacheManager();
cmB.getCache();
assertNotNull(listener.firstEvent.get(10, TimeUnit.SECONDS));
} finally {
TestingUtil.killCacheManagers(cmA, cmB);
}
}
public void testAddRemoveListenerWhileNotRunning() throws Exception {
GetCacheManagerCheckListener listener = new GetCacheManagerCheckListener();
ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder();
holder.getGlobalConfigurationBuilder().clusteredDefault().defaultCacheName("default");
holder.newConfigurationBuilder("default").clustering().cacheMode(CacheMode.DIST_SYNC);
EmbeddedCacheManager cmA = TestCacheManagerFactory.createClusteredCacheManager(false, holder);
EmbeddedCacheManager cmB = null;
try {
cmA.addListener(listener);
cmA.getCache();
cmB = TestCacheManagerFactory.createClusteredCacheManager();
cmB.getCache();
assertNotNull(listener.firstEvent.get(10, TimeUnit.SECONDS));
} finally {
TestingUtil.killCacheManagers(cmA, cmB);
}
// Should not throw an exception?
cmA.removeListener(listener);
}
@Listener
static public class GetCacheManagerCheckListener {
CompletableFuture<ViewChangedEvent> firstEvent = new CompletableFuture<>();
@ViewChanged
public void onViewChange(ViewChangedEvent e) {
firstEvent.complete(e);
}
}
}
| 2,793
| 35.763158
| 100
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/metrics/ClusteredCacheManagerMetricsTest.java
|
package org.infinispan.metrics;
import static org.assertj.core.api.Assertions.assertThat;
import static org.infinispan.test.fwk.TestCacheManagerFactory.createClusteredCacheManager;
import java.util.Collection;
import java.util.List;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.metrics.impl.MetricsCollector;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.fwk.TransportFlags;
import org.testng.annotations.Test;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Tag;
/**
* @author anistor@redhat.com
* @since 10.1
*/
@Test(groups = "functional", testName = "metrics.ClusteredCacheManagerMetricsTest")
public class ClusteredCacheManagerMetricsTest extends MultipleCacheManagersTest {
private static final String CACHE_NAME = "MyCache";
@Override
protected void createCacheManagers() throws Throwable {
GlobalConfigurationBuilder globalConfig1 = GlobalConfigurationBuilder.defaultClusteredBuilder();
globalConfig1.cacheContainer().statistics(true)
.metrics().prefix("ispn").gauges(true).histograms(true).namesAsTags(true);
ConfigurationBuilder config = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC);
config.statistics().enable();
EmbeddedCacheManager cacheManager1 = createClusteredCacheManager(globalConfig1, config, new TransportFlags());
cacheManager1.start();
GlobalConfigurationBuilder globalConfig2 = GlobalConfigurationBuilder.defaultClusteredBuilder();
globalConfig2.metrics().prefix("ispn").gauges(true).histograms(true).namesAsTags(true);
EmbeddedCacheManager cacheManager2 = createClusteredCacheManager(globalConfig2, config, new TransportFlags());
cacheManager2.start();
registerCacheManager(cacheManager1, cacheManager2);
defineConfigurationOnAllManagers(CACHE_NAME, config);
manager(0).getCache(CACHE_NAME);
manager(1).getCache(CACHE_NAME);
}
public void testMetricsAreRegistered() {
MetricsCollector mc0 = manager(0).getGlobalComponentRegistry().getComponent(MetricsCollector.class);
List<Meter> meters0 = mc0.registry().getMeters();
assertThat(meters0).isNotEmpty();
assertThat(meters0.get(0).getId().getName()).startsWith("vendor.ispn");
MetricsCollector mc1 = manager(1).getGlobalComponentRegistry().getComponent(MetricsCollector.class);
List<Meter> meters1 = mc1.registry().getMeters();
assertThat(meters1).isNotEmpty();
assertThat(meters1.get(0).getId().getName()).startsWith("vendor.ispn");
GlobalConfiguration gcfg0 = manager(0).getCacheManagerConfiguration();
Tag nodeNameTag = Tag.of(Constants.NODE_TAG_NAME, gcfg0.transport().nodeName());
Tag cacheManagerTag = Tag.of(Constants.CACHE_MANAGER_TAG_NAME, gcfg0.cacheManagerName());
Collection<Gauge> statsEvictions = mc0.registry().find("vendor.ispn_cache_container_stats_evictions").gauges();
assertThat(statsEvictions).hasSize(1);
Gauge statsEviction = statsEvictions.iterator().next();
statsEviction.getId().getTags().contains(nodeNameTag);
statsEviction.getId().getTags().contains(cacheManagerTag);
}
}
| 3,511
| 42.9
| 117
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/metrics/impl/VendorAdditionalMetricsTest.java
|
package org.infinispan.metrics.impl;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
/**
* @author Alexander Schwartz
*/
@Test(groups = "functional", testName = "metrics.VendorAdditionalMetricsTest")
public class VendorAdditionalMetricsTest {
@Test
public void testMetricNamesContainOnlyValidCharacters() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
new VendorAdditionalMetrics().bindTo(registry);
SoftAssert asserts = new SoftAssert();
registry.getMeters().forEach(meter -> {
asserts.assertTrue(meter.getId().getName().matches("[.\\w]+"), "metric name contains invalid characters: " + meter.getId().getName());
asserts.assertTrue(meter.getId().getName().matches("^[^_].*[^_]$"), "metric name should not begin or end with an underscore: " + meter.getId().getName());
});
asserts.assertAll();
registry.close();
}
}
| 1,018
| 36.740741
| 166
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/dataconversion/FooBarTranscoder.java
|
package org.infinispan.dataconversion;
import static java.util.Arrays.asList;
import static org.infinispan.commons.dataconversion.MediaType.fromString;
import java.util.HashSet;
import java.util.Set;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.Transcoder;
/**
* @since 9.2
*/
public class FooBarTranscoder implements Transcoder {
private final Set<MediaType> supportedTypes;
public FooBarTranscoder() {
supportedTypes = new HashSet<>(asList(fromString("application/x-java-object"), fromString("application/foo"), fromString("application/bar")));
}
@Override
public Object transcode(Object content, MediaType contentType, MediaType destinationType) {
switch (destinationType.toString()) {
case "application/foo":
return content.toString().replaceAll("bar", "foo");
case "application/bar":
return content.toString().replaceAll("foo", "bar");
default:
return content;
}
}
@Override
public Set<MediaType> getSupportedMediaTypes() {
return supportedTypes;
}
}
| 1,136
| 27.425
| 148
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/dataconversion/ProtostreamTranscoderTest.java
|
package org.infinispan.dataconversion;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN;
import static org.infinispan.protostream.ProtobufUtil.toWrappedByteArray;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
import java.io.IOException;
import java.util.Base64;
import org.infinispan.commons.dataconversion.Base16Codec;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.internal.Json;
import org.infinispan.commons.marshall.MarshallingException;
import org.infinispan.encoding.ProtostreamTranscoder;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.data.Address;
import org.infinispan.test.data.Person;
import org.infinispan.test.dataconversion.AbstractTranscoderTest;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "query.remote.impl.ProtostreamTranscoderTest")
public class ProtostreamTranscoderTest extends AbstractTranscoderTest {
protected String dataSrc;
private final SerializationContext ctx = createCtx();
static final MediaType UNWRAPPED_PROTOSTREAM = APPLICATION_PROTOSTREAM.withParameter("wrapped", "false");
static final MediaType TYPED_OBJECT = APPLICATION_OBJECT.withParameter("type", Person.class.getName());
@BeforeClass(alwaysRun = true)
public void setUp() {
dataSrc = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
SerializationContextRegistry registry = Mockito.mock(SerializationContextRegistry.class);
Mockito.when(registry.getUserCtx()).thenReturn(ctx);
transcoder = new ProtostreamTranscoder(registry, ProtostreamTranscoderTest.class.getClassLoader());
supportedMediaTypes = transcoder.getSupportedMediaTypes();
}
private SerializationContext createCtx() {
SerializationContext ctx = ProtobufUtil.newSerializationContext();
TestDataSCI.INSTANCE.registerSchema(ctx);
TestDataSCI.INSTANCE.registerMarshallers(ctx);
return ctx;
}
@Test
@Override
public void testTranscoderTranscode() throws Exception {
Object transcoded = transcoder.transcode(dataSrc, TEXT_PLAIN, APPLICATION_PROTOSTREAM);
assertTrue(transcoded instanceof byte[], "Must be byte[]");
Object transcodedBack = transcoder.transcode(transcoded, APPLICATION_PROTOSTREAM, TEXT_PLAIN);
// Must be String as byte[] as sent over the wire by hotrod
assertTrue(transcodedBack instanceof byte[], "Must be instance of byte[]");
assertEquals(dataSrc, new String((byte[]) transcodedBack, TEXT_PLAIN.getCharset().name()), "Must be equal strings");
}
@Test
public void testWrappedMessage() throws IOException {
Person input = new Person("value");
// Produces MessageWrapped and unwrapped payloads
byte[] wrapped = (byte[]) transcoder.transcode(input, APPLICATION_OBJECT, APPLICATION_PROTOSTREAM);
byte[] unwrapped = (byte[]) transcoder.transcode(input, APPLICATION_OBJECT, UNWRAPPED_PROTOSTREAM);
assertEquals(input, ProtobufUtil.fromWrappedByteArray(ctx, wrapped));
assertEquals(input, ProtobufUtil.fromByteArray(ctx, unwrapped, Person.class));
// Convert from MessageWrapped back to object
Object fromWrapped = transcoder.transcode(wrapped, APPLICATION_PROTOSTREAM, APPLICATION_OBJECT);
assertEquals(input, fromWrapped);
// Convert from unwrapped payload back to object, specifying the object type
Object fromUnWrappedWithType = transcoder.transcode(unwrapped, UNWRAPPED_PROTOSTREAM, TYPED_OBJECT);
assertEquals(input, fromUnWrappedWithType);
// Should throw exception if trying to convert from unwrapped without passing the type
try {
transcoder.transcode(unwrapped, UNWRAPPED_PROTOSTREAM, APPLICATION_OBJECT);
Assert.fail("should not convert from unwrapped without type");
} catch (MarshallingException ignored) {
}
}
@Test
public void testToFromObject() throws IOException {
Person objectContent = new Person("value");
final byte[] marshalled = toWrappedByteArray(ctx, objectContent);
byte[] marshalledHex = Base16Codec.encode(marshalled).getBytes(UTF_8);
// Converting from Object to protostream with different binary encodings
Object result = transcoder.transcode(objectContent, APPLICATION_OBJECT, APPLICATION_PROTOSTREAM);
assertArrayEquals(marshalled, (byte[]) result);
result = transcoder.transcode(objectContent, APPLICATION_OBJECT, APPLICATION_PROTOSTREAM.withEncoding("hex"));
assertEquals(Base16Codec.encode(marshalled), result);
result = transcoder.transcode(objectContent, APPLICATION_OBJECT, APPLICATION_PROTOSTREAM.withEncoding("hex").withClassType(String.class));
assertEquals(Base16Codec.encode(marshalled), result);
// convert from protostream with different encodings back to object
result = transcoder.transcode(marshalled, APPLICATION_PROTOSTREAM, APPLICATION_OBJECT);
assertEquals(objectContent, result);
result = transcoder.transcode(marshalledHex, APPLICATION_PROTOSTREAM.withEncoding("hex"), APPLICATION_OBJECT);
assertEquals(objectContent, result);
}
@Test
public void testToFromText() throws IOException {
final String string = "This is a text";
byte[] textContent = string.getBytes(UTF_8);
// Converting from text/plain to protostream with different binary encodings
Object protoWithNoEncoding = transcoder.transcode(textContent, TEXT_PLAIN, APPLICATION_PROTOSTREAM);
assertArrayEquals(toWrappedByteArray(ctx, string), (byte[]) protoWithNoEncoding);
Object protoHex = transcoder.transcode(textContent, TEXT_PLAIN, APPLICATION_PROTOSTREAM.withEncoding("hex"));
assertEquals(Base16Codec.encode(toWrappedByteArray(ctx, string)), protoHex);
Object protoBase64 = transcoder.transcode(textContent, TEXT_PLAIN, APPLICATION_PROTOSTREAM.withEncoding("base64"));
assertEquals(Base64.getEncoder().encode(toWrappedByteArray(ctx, string)), protoBase64);
// Converting back from protostream with different binary encodings
Object result = transcoder.transcode(protoWithNoEncoding, APPLICATION_PROTOSTREAM, TEXT_PLAIN);
assertArrayEquals(textContent, (byte[]) result);
}
@Test
public void testToFromJson() throws IOException {
String type = "org.infinispan.test.core.Address";
String street = "Elm Street";
String city = "NYC";
int zip = 123;
Address data = new Address(street, city, zip);
String jsonString = Json.object()
.set("_type", type)
.set("street", street)
.set("city", city)
.set("zip", zip)
.toString();
byte[] byteJson = jsonString.getBytes(UTF_8);
// Converting from json strings to protostream with different binary encodings
Object protoWithNoEncoding = transcoder.transcode(jsonString, APPLICATION_JSON, APPLICATION_PROTOSTREAM);
assertArrayEquals(toWrappedByteArray(ctx, data), (byte[]) protoWithNoEncoding);
Object protoHex = transcoder.transcode(jsonString, APPLICATION_JSON, APPLICATION_PROTOSTREAM.withEncoding("hex"));
assertEquals(protoHex, Base16Codec.encode((byte[]) protoWithNoEncoding));
Object protoBase64 = transcoder.transcode(jsonString, APPLICATION_JSON, APPLICATION_PROTOSTREAM.withEncoding("base64"));
assertEquals(protoBase64, Base64.getEncoder().encode((byte[]) protoWithNoEncoding));
// Converting from json byte[] to protostream with different binary encodings
protoWithNoEncoding = transcoder.transcode(byteJson, APPLICATION_JSON, APPLICATION_PROTOSTREAM);
assertArrayEquals(toWrappedByteArray(ctx, data), (byte[]) protoWithNoEncoding);
protoHex = transcoder.transcode(byteJson, APPLICATION_JSON, APPLICATION_PROTOSTREAM.withEncoding("hex"));
assertEquals(protoHex, Base16Codec.encode((byte[]) protoWithNoEncoding));
protoBase64 = transcoder.transcode(byteJson, APPLICATION_JSON, APPLICATION_PROTOSTREAM.withEncoding("base64"));
assertEquals(protoBase64, Base64.getEncoder().encode((byte[]) protoWithNoEncoding));
// Converting from protostream to json with different output binary encoding
Object result = transcoder.transcode(protoWithNoEncoding, APPLICATION_PROTOSTREAM, APPLICATION_JSON);
assertTrue(result instanceof byte[]);
assertJsonCorrect(result);
result = transcoder.transcode(protoHex, APPLICATION_PROTOSTREAM.withEncoding("hex"), APPLICATION_JSON);
assertTrue(result instanceof byte[]);
assertJsonCorrect(result);
result = transcoder.transcode(protoBase64, APPLICATION_PROTOSTREAM.withEncoding("base64"), APPLICATION_JSON);
assertTrue(result instanceof byte[]);
assertJsonCorrect(result);
result = transcoder.transcode(protoHex, APPLICATION_PROTOSTREAM.withEncoding("hex"), APPLICATION_JSON.withClassType(String.class));
assertTrue(result instanceof String);
assertJsonCorrect(result);
}
private void assertJsonCorrect(Object json) {
String strJson = json instanceof byte[] ? new String((byte[]) json) : json.toString();
Json jsonResult = Json.read(strJson);
assertEquals("org.infinispan.test.core.Address", jsonResult.at("_type").asString());
}
}
| 10,040
| 47.742718
| 144
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/dataconversion/ProtostreamJsonTranscoderTest.java
|
package org.infinispan.dataconversion;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.nio.charset.StandardCharsets;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.encoding.ProtostreamTranscoder;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.protostream.FileDescriptorSource;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.test.dataconversion.AbstractTranscoderTest;
import org.mockito.Mockito;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "query.remote.impl.ProtostreamJsonTranscoderTest")
public class ProtostreamJsonTranscoderTest extends AbstractTranscoderTest {
private static final String PROTO_DEFINITIONS =
"syntax = \"proto2\";\n" +
"\n" +
" message Person {\n" +
" optional string _type = 1;\n" +
" optional string name = 2;\n" +
"\n" +
" message Address {\n" +
" optional string _type = 1;\n" +
" optional string street = 2;\n" +
" optional string city = 3;\n" +
" optional string zip = 4;\n" +
" }\n" +
"\n" +
" optional Address address = 3;\n" +
"}";
protected String dataSrc;
@BeforeClass(alwaysRun = true)
public void setUp() {
dataSrc = "{\"_type\":\"Person\", \"name\":\"joe\", \"address\":{\"_type\":\"Address\", \"street\":\"\", \"city\":\"London\", \"zip\":\"0\"}}";
SerializationContext serCtx = ProtobufUtil.newSerializationContext();
serCtx.registerProtoFiles(FileDescriptorSource.fromString("person_definition.proto", PROTO_DEFINITIONS));
SerializationContextRegistry registry = Mockito.mock(SerializationContextRegistry.class);
Mockito.when(registry.getUserCtx()).thenReturn(serCtx);
transcoder = new ProtostreamTranscoder(registry, ProtostreamTranscoder.class.getClassLoader());
supportedMediaTypes = transcoder.getSupportedMediaTypes();
}
@Test
@Override
public void testTranscoderTranscode() {
Object transcoded = transcoder.transcode(dataSrc.getBytes(StandardCharsets.UTF_8), MediaType.APPLICATION_JSON, MediaType.APPLICATION_PROTOSTREAM);
assertTrue(transcoded instanceof byte[], "Must be byte[]");
Object transcodedBack = transcoder.transcode(transcoded, MediaType.APPLICATION_PROTOSTREAM, MediaType.APPLICATION_JSON);
assertEquals(
dataSrc.replace(" ", ""),
(new String((byte[]) transcodedBack)).replace(" ", "").replace("\n", ""),
"Must be the same JSON string"
);
}
}
| 2,896
| 42.238806
| 152
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/dataconversion/ObjectXMLTranscoder.java
|
package org.infinispan.dataconversion;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.Transcoder;
/**
* @since 9.2
*/
class ObjectXMLTranscoder implements Transcoder {
private Set<MediaType> supported;
private TestXMLParser parser = new TestXMLParser();
ObjectXMLTranscoder() {
supported = new HashSet<>();
supported.add(APPLICATION_XML);
supported.add(APPLICATION_OBJECT);
}
@Override
public Object transcode(Object content, MediaType contentType, MediaType destinationType) {
if (destinationType.match(APPLICATION_OBJECT)) {
try {
return parser.parse((String) content);
} catch (Exception e) {
e.printStackTrace();
}
}
if (destinationType.match(APPLICATION_XML)) {
try {
return parser.serialize((Map<String, String>) content);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
@Override
public Set<MediaType> getSupportedMediaTypes() {
return supported;
}
}
| 1,356
| 25.096154
| 94
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/dataconversion/DataConversionTest.java
|
package org.infinispan.dataconversion;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML;
import static org.infinispan.notifications.Listener.Observation.POST;
import static org.infinispan.test.TestingUtil.withCacheManager;
import static org.infinispan.test.fwk.TestCacheManagerFactory.createCacheManager;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commons.dataconversion.IdentityEncoder;
import org.infinispan.commons.dataconversion.IdentityWrapper;
import org.infinispan.commons.dataconversion.JavaSerializationEncoder;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.UTF8Encoder;
import org.infinispan.commons.marshall.JavaSerializationMarshaller;
import org.infinispan.commons.marshall.WrappedByteArray;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.container.DataContainer;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.context.InvocationContext;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.interceptors.impl.EntryWrappingInterceptor;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.marshall.core.EncoderRegistry;
import org.infinispan.marshall.core.GlobalMarshaller;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.CacheManagerCallable;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.data.Person;
import org.testng.annotations.Test;
/**
* Test various data conversion scenarios.
*
* @since 9.1
*/
@Test(groups = "functional", testName = "core.DataConversionTest")
@SuppressWarnings("unchecked")
public class DataConversionTest extends AbstractInfinispanTest {
@Test
public void testReadUnencoded() {
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.memory().storage(StorageType.OFF_HEAP);
withCacheManager(new CacheManagerCallable(
createCacheManager(TestDataSCI.INSTANCE, cfg)) {
private final EncoderRegistry registry = TestingUtil.extractGlobalComponent(cm, EncoderRegistry.class);
public Object asStored(Object object) {
return registry.convert(object, APPLICATION_OBJECT, APPLICATION_PROTOSTREAM);
}
@Override
public void call() {
cm.getClassAllowList().addClasses(Person.class);
Cache<String, Person> cache = cm.getCache();
Person value = new Person();
cache.put("1", value);
// Read using default valueEncoder
assertEquals(cache.get("1"), value);
// Read unencoded
Cache<?, ?> unencodedCache = cache.getAdvancedCache().withStorageMediaType();
assertEquals(unencodedCache.get(asStored("1")), asStored(value));
}
});
}
@Test
public void testUTF8Encoders() {
ConfigurationBuilder cfg = new ConfigurationBuilder();
withCacheManager(new CacheManagerCallable(
createCacheManager(TestDataSCI.INSTANCE, cfg)) {
String charset = "UTF-8";
private byte[] asUTF8Bytes(String value) throws UnsupportedEncodingException {
return value.getBytes(charset);
}
@Override
public void call() throws IOException {
Cache<byte[], byte[]> cache = cm.getCache();
String keyUnencoded = "1";
String valueUnencoded = "value";
cache.put(asUTF8Bytes(keyUnencoded), asUTF8Bytes(valueUnencoded));
// Read using different valueEncoder
Cache utf8Cache = cache.getAdvancedCache().withEncoding(UTF8Encoder.class);
assertEquals(utf8Cache.get(keyUnencoded), valueUnencoded);
// Write with one valueEncoder and read with another
String key2Unencoded = "2";
String value2Unencoded = "anotherValue";
utf8Cache.put(key2Unencoded, value2Unencoded);
assertEquals(cache.get(asUTF8Bytes(key2Unencoded)), asUTF8Bytes(value2Unencoded));
}
});
}
@Test
public void testExtractIndexable() {
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.customInterceptors().addInterceptor().after(EntryWrappingInterceptor.class).interceptor(new TestInterceptor(1));
withCacheManager(new CacheManagerCallable(
createCacheManager(TestDataSCI.INSTANCE, cfg)) {
@Override
public void call() {
ConfigurationBuilder offHeapConfig = new ConfigurationBuilder();
offHeapConfig.memory().storage(StorageType.OFF_HEAP);
offHeapConfig.customInterceptors().addInterceptor().after(EntryWrappingInterceptor.class).interceptor(new TestInterceptor(1));
ConfigurationBuilder compatConfig = new ConfigurationBuilder();
compatConfig.customInterceptors().addInterceptor().after(EntryWrappingInterceptor.class).interceptor(new TestInterceptor(1));
cm.defineConfiguration("offheap", offHeapConfig.build());
cm.defineConfiguration("compat", compatConfig.build());
Cache<Object, Object> cache = cm.getCache();
Cache<Object, Object> offheapCache = cm.getCache("offheap");
Cache<Object, Object> compatCache = cm.getCache("compat");
cache.put(1, 1);
offheapCache.put(1, 1);
compatCache.put(1, 1);
assertEquals(1, cache.get(1));
assertEquals(1, offheapCache.get(1));
assertEquals(1, compatCache.get(1));
}
});
}
@Test
public void testConversionWithListeners() {
ConfigurationBuilder cfg = new ConfigurationBuilder();
withCacheManager(new CacheManagerCallable(
createCacheManager(TestDataSCI.INSTANCE, cfg)) {
@Override
public void call() {
Cache<String, Person> cache = cm.getCache();
cm.getClassAllowList().addClasses(Person.class);
// Obtain cache with custom valueEncoder
Cache storeMarshalled = cache.getAdvancedCache().withEncoding(JavaSerializationEncoder.class);
// Add a listener
SimpleListener simpleListener = new SimpleListener();
storeMarshalled.addListener(simpleListener);
Person value = new Person();
storeMarshalled.put("1", value);
// Assert values returned are passed through the valueEncoder
assertEquals(simpleListener.events.size(), 1);
assertEquals(simpleListener.events.get(0).getKey(), "1");
assertEquals(simpleListener.events.get(0).getValue(), value);
}
});
}
@Test
@SuppressWarnings("unchecked")
public void testTranscoding() {
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
cfg.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
withCacheManager(new CacheManagerCallable(
createCacheManager(TestDataSCI.INSTANCE, cfg)) {
@Override
public void call() {
Cache<String, Map<String, String>> cache = cm.getCache();
EncoderRegistry encoderRegistry = TestingUtil.extractGlobalComponent(cm, EncoderRegistry.class);
encoderRegistry.registerTranscoder(new ObjectXMLTranscoder());
// Store a map in the cache
Map<String, String> valueMap = new HashMap<>();
valueMap.put("BTC", "Bitcoin");
valueMap.put("ETH", "Ethereum");
valueMap.put("LTC", "Litecoin");
cache.put("CoinMap", valueMap);
assertEquals(valueMap, cache.get("CoinMap"));
// Obtain the value with a different MediaType
AdvancedCache<String, String> xmlCache = cache.getAdvancedCache().withMediaType(APPLICATION_OBJECT, APPLICATION_XML);
assertEquals(xmlCache.get("CoinMap"), "<root><BTC>Bitcoin</BTC><ETH>Ethereum</ETH><LTC>Litecoin</LTC></root>");
// Reading with same configured MediaType should not change content
assertEquals(xmlCache.withMediaType(APPLICATION_OBJECT, APPLICATION_OBJECT).get("CoinMap"), valueMap);
// Writing using XML
xmlCache.put("AltCoinMap", "<root><CAT>Catcoin</CAT><DOGE>Dogecoin</DOGE></root>");
// Read using object from undecorated cache
Map<String, String> map = cache.get("AltCoinMap");
assertEquals(map.get("CAT"), "Catcoin");
assertEquals(map.get("DOGE"), "Dogecoin");
}
});
}
@Test
@SuppressWarnings("unchecked")
public void testTranscodingWithCustomConfig() {
withCacheManager(new CacheManagerCallable(createCacheManager(TestDataSCI.INSTANCE)) {
@Override
public void call() {
EncoderRegistry encoderRegistry = TestingUtil.extractGlobalComponent(cm, EncoderRegistry.class);
encoderRegistry.registerTranscoder(new FooBarTranscoder());
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.encoding().key().mediaType("application/foo");
cfg.encoding().value().mediaType("application/bar");
cm.defineConfiguration("foobar", cfg.build());
Cache<String, String> cache = cm.getCache("foobar");
cache.put("foo-key", "bar-value");
assertEquals(cache.get("foo-key"), "bar-value");
MediaType appFoo = MediaType.fromString("application/foo");
MediaType appBar = MediaType.fromString("application/bar");
Cache<String, String> fooCache = cache.getAdvancedCache().withMediaType(appFoo, appFoo);
assertEquals(fooCache.get("foo-key"), "foo-value");
Cache<String, String> barCache = cache.getAdvancedCache().withMediaType(appBar, appBar);
assertEquals(barCache.get("bar-key"), "bar-value");
Cache<String, String> barFooCache = cache.getAdvancedCache().withMediaType(appBar, appFoo);
assertEquals(barFooCache.get("bar-key"), "foo-value");
}
});
}
@Test
@SuppressWarnings("unchecked")
public void testTextTranscoder() {
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.encoding().key().mediaType("text/plain; charset=ISO-8859-1");
cfg.encoding().value().mediaType("text/plain; charset=UTF-8");
withCacheManager(new CacheManagerCallable(
createCacheManager(TestDataSCI.INSTANCE, cfg)) {
@Override
public void call() {
AdvancedCache<Object, Object> cache = cm.getCache().getAdvancedCache().withStorageMediaType();
byte[] key = "key1".getBytes(ISO_8859_1);
byte[] value = new byte[]{97, 118, 105, -61, -93, 111}; // 'avião' in UTF-8
cache.put(key, value);
assertEquals(cache.get(key), value);
// Value as UTF-16
Cache<byte[], byte[]> utf16ValueCache = cache.getAdvancedCache().withMediaType(MediaType.fromString("text/plain; charset=ISO-8859-1"), MediaType.fromString("text/plain; charset=UTF-16"));
assertEquals(utf16ValueCache.get(key), new byte[]{-2, -1, 0, 97, 0, 118, 0, 105, 0, -29, 0, 111});
}
});
}
public void testWithCustomEncoder() {
withCacheManager(new CacheManagerCallable(
createCacheManager(TestDataSCI.INSTANCE, new ConfigurationBuilder())) {
@Override
public void call() {
EncoderRegistry encoderRegistry = TestingUtil.extractGlobalComponent(cm, EncoderRegistry.class);
encoderRegistry.registerEncoder(new GzipEncoder());
AdvancedCache<String, String> cache = cm.<String, String>getCache().getAdvancedCache();
AdvancedCache<String, String> compressingCache = (AdvancedCache<String, String>) cache.withEncoding(IdentityEncoder.class, GzipEncoder.class);
compressingCache.put("297931749", "0412c789a37f5086f743255cfa693dd502b6a2ecb2ceee68380ff58ad15e7b56");
assertEquals(compressingCache.get("297931749"), "0412c789a37f5086f743255cfa693dd502b6a2ecb2ceee68380ff58ad15e7b56");
Object value = compressingCache.withEncoding(IdentityEncoder.class).get("297931749");
assert value instanceof byte[];
}
});
}
@Test
public void testSerialization() {
withCacheManager(new CacheManagerCallable(createCacheManager(TestDataSCI.INSTANCE, new ConfigurationBuilder())) {
GlobalMarshaller marshaller = TestingUtil.extractGlobalMarshaller(cm);
private void testWith(DataConversion dataConversion, ComponentRegistry registry) throws Exception {
byte[] marshalled = marshaller.objectToByteBuffer(dataConversion);
Object back = marshaller.objectFromByteBuffer(marshalled);
registry.wireDependencies(back);
assertEquals(back, dataConversion);
}
@Override
public void call() throws Exception {
ComponentRegistry registry = cm.getCache().getAdvancedCache().getComponentRegistry();
testWith(DataConversion.DEFAULT_KEY, registry);
testWith(DataConversion.DEFAULT_VALUE, registry);
testWith(DataConversion.IDENTITY_KEY, registry);
testWith(DataConversion.IDENTITY_VALUE, registry);
ConfigurationBuilder builder = new ConfigurationBuilder();
cm.defineConfiguration("compat", builder.build());
AdvancedCache<?, ?> compat = cm.getCache("compat").getAdvancedCache();
ComponentRegistry compatRegistry = compat.getComponentRegistry();
testWith(compat.getKeyDataConversion(), compatRegistry);
testWith(compat.getValueDataConversion(), compatRegistry);
AdvancedCache<?, ?> wrapped = compat.withEncoding(IdentityEncoder.class).withWrapping(IdentityWrapper.class);
ComponentRegistry wrappedRegistry = wrapped.getComponentRegistry();
testWith(wrapped.getKeyDataConversion(), wrappedRegistry);
testWith(wrapped.getValueDataConversion(), wrappedRegistry);
}
});
}
@Test
public void testJavaSerialization() throws Exception {
GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();
gcb.serialization().marshaller(new JavaSerializationMarshaller());
try (DefaultCacheManager manager = new DefaultCacheManager(gcb.build())) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.encoding().mediaType(MediaType.APPLICATION_SERIALIZED_OBJECT_TYPE);
Cache<String, String> cache = manager.createCache("cache", builder.build());
cache.put("key", "value");
JavaSerializationMarshaller marshaller = new JavaSerializationMarshaller();
DataContainer<?, ?> dataContainer = cache.getAdvancedCache().getDataContainer();
InternalCacheEntry<?, ?> cacheEntry = dataContainer.peek(new WrappedByteArray(marshaller.objectToByteBuffer("key")));
assertEquals(new WrappedByteArray(marshaller.objectToByteBuffer("value")), cacheEntry.getValue());
}
}
@SuppressWarnings("unused")
static class TestInterceptor extends BaseCustomAsyncInterceptor {
private final int i;
@Inject ComponentRef<AdvancedCache<?, ?>> cache;
TestInterceptor(int i) {
this.i = i;
}
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command)
throws Throwable {
DataConversion valueDataConversion = cache.wired().getValueDataConversion();
assertNotNull(valueDataConversion);
Object value = command.getValue();
assertEquals(i, valueDataConversion.fromStorage(value));
return invokeNext(ctx, command);
}
}
@Listener(observation = POST)
@SuppressWarnings("unused")
private static class SimpleListener {
private List<CacheEntryEvent> events = new ArrayList<>();
@CacheEntryCreated
public void cacheEntryCreated(CacheEntryEvent ev) {
events.add(ev);
}
}
}
| 17,339
| 40.985472
| 199
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/dataconversion/TranscoderRegistrationTest.java
|
package org.infinispan.dataconversion;
import static org.testng.Assert.assertEquals;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.infinispan.commons.dataconversion.DefaultTranscoder;
import org.infinispan.commons.dataconversion.EncodingException;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.Transcoder;
import org.infinispan.commons.marshall.JavaSerializationMarshaller;
import org.infinispan.marshall.core.EncoderRegistry;
import org.infinispan.marshall.core.EncoderRegistryImpl;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @since 9.2
*/
@Test(groups = "functional", testName = "core.TranscoderRegistrationTest")
public class TranscoderRegistrationTest {
public void testTranscoderLookup() {
EncoderRegistry encoderRegistry = new EncoderRegistryImpl();
TestTranscoder t1 = new TestTranscoder(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OBJECT);
TestTranscoder t2 = new TestTranscoder(MediaType.APPLICATION_XML, MediaType.APPLICATION_OBJECT);
DefaultTranscoder t3 = new DefaultTranscoder(new JavaSerializationMarshaller());
encoderRegistry.registerTranscoder(t3);
encoderRegistry.registerTranscoder(t2);
encoderRegistry.registerTranscoder(t1);
assertEquals(encoderRegistry.getTranscoder(MediaType.TEXT_PLAIN, MediaType.APPLICATION_OBJECT), t3);
assertEquals(encoderRegistry.getTranscoder(MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN), t3);
assertEquals(encoderRegistry.getTranscoder(MediaType.TEXT_PLAIN, MediaType.APPLICATION_OBJECT), t3);
assertEquals(encoderRegistry.getTranscoder(MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_OCTET_STREAM), t3);
assertEquals(encoderRegistry.getTranscoder(MediaType.APPLICATION_OBJECT, MediaType.APPLICATION_OBJECT), t3);
assertEquals(encoderRegistry.getTranscoder(MediaType.TEXT_PLAIN, MediaType.APPLICATION_OCTET_STREAM), t3);
assertNotFound(encoderRegistry, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML);
assertNotFound(encoderRegistry, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON);
assertEquals(encoderRegistry.getTranscoder(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OBJECT), t1);
assertEquals(encoderRegistry.getTranscoder(MediaType.APPLICATION_OBJECT, MediaType.APPLICATION_JSON), t1);
assertEquals(encoderRegistry.getTranscoder(MediaType.APPLICATION_XML, MediaType.APPLICATION_OBJECT), t2);
assertEquals(encoderRegistry.getTranscoder(MediaType.APPLICATION_OBJECT, MediaType.APPLICATION_XML), t2);
assertEquals(encoderRegistry.getTranscoder(MediaType.APPLICATION_WWW_FORM_URLENCODED, MediaType.APPLICATION_WWW_FORM_URLENCODED), t3);
}
private void assertNotFound(EncoderRegistry registry, MediaType one, MediaType other) {
try {
registry.getTranscoder(one, other);
Assert.fail("Should not have found transcoder");
} catch (EncodingException ignored) {
}
}
private static final class TestTranscoder implements Transcoder {
Set<MediaType> supportedSet = new HashSet<>();
TestTranscoder(MediaType... supported) {
supportedSet.addAll(Arrays.asList(supported));
}
@Override
public Object transcode(Object content, MediaType contentType, MediaType destinationType) {
return content;
}
@Override
public Set<MediaType> getSupportedMediaTypes() {
return supportedSet;
}
@Override
public String toString() {
return "TestTranscoder{" +
"supportedSet=" + supportedSet +
'}';
}
}
}
| 3,708
| 40.674157
| 140
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/dataconversion/GzipEncoder.java
|
package org.infinispan.dataconversion;
import static org.infinispan.dataconversion.Gzip.compress;
import static org.infinispan.dataconversion.Gzip.decompress;
import org.infinispan.commons.dataconversion.Encoder;
import org.infinispan.commons.dataconversion.MediaType;
public class GzipEncoder implements Encoder {
@Override
public Object toStorage(Object content) {
assert content instanceof String;
return compress(content.toString());
}
@Override
public Object fromStorage(Object content) {
assert content instanceof byte[];
return decompress((byte[]) content);
}
@Override
public MediaType getStorageFormat() {
return MediaType.fromString("application/gzip");
}
@Override
public boolean isStorageFormatFilterable() {
return false;
}
@Override
public short id() {
return 10000;
}
}
| 880
| 22.184211
| 60
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/dataconversion/TestXMLParser.java
|
package org.infinispan.dataconversion;
import static javax.xml.stream.XMLStreamConstants.CHARACTERS;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.xml.sax.SAXException;
class TestXMLParser {
public Map<String, String> parse(String input) throws ParserConfigurationException, SAXException, XMLStreamException {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(input));
Map<String, String> pairs = new HashMap<>();
String currentElement = null, currentValue = null;
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case START_ELEMENT:
currentElement = reader.getLocalName();
break;
case CHARACTERS:
currentValue = reader.getText();
break;
case XMLStreamConstants.END_ELEMENT:
if (currentElement != null) {
pairs.put(currentElement, currentValue);
}
currentElement = null;
currentValue = null;
break;
}
}
return pairs;
}
String serialize(Map<String, String> pairs) throws XMLStreamException {
if (pairs.isEmpty()) return "";
XMLOutputFactory factory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLStreamWriter streamWriter = factory.createXMLStreamWriter(writer);
streamWriter.writeStartElement("root");
for (Map.Entry<String, String> entry : pairs.entrySet()) {
streamWriter.writeStartElement(entry.getKey());
streamWriter.writeCharacters(entry.getValue());
streamWriter.writeEndElement();
}
streamWriter.writeEndElement();
return writer.toString();
}
}
| 2,292
| 32.720588
| 121
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/dataconversion/Gzip.java
|
package org.infinispan.dataconversion;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public final class Gzip {
public static byte[] compress(String str) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gis = new GZIPOutputStream(baos)) {
gis.write(str.getBytes(UTF_8));
gis.close();
return baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException("Unable to compress", e);
}
}
public static String decompress(byte[] compressed) {
try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int len;
while ((len = gis.read(buffer)) > 0) {
baos.write(buffer, 0, len);
}
return new String(baos.toByteArray(), UTF_8);
} catch (IOException e) {
throw new RuntimeException("Unable to decompress", e);
}
}
}
| 1,234
| 31.5
| 91
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/dataconversion/impl/JavaSerializationTranscoderTest.java
|
package org.infinispan.dataconversion.impl;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Collections;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.encoding.impl.JavaSerializationTranscoder;
import org.infinispan.test.data.Address;
import org.infinispan.test.data.Person;
import org.infinispan.test.dataconversion.AbstractTranscoderTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "rest.JavaSerializationTranscoderTest")
public class JavaSerializationTranscoderTest extends AbstractTranscoderTest {
protected Person dataSrc;
@BeforeClass(alwaysRun = true)
public void setUp() {
dataSrc = new Person("Joe");
Address address = new Address();
address.setCity("London");
dataSrc.setAddress(address);
transcoder = new JavaSerializationTranscoder(new ClassAllowList(Collections.singletonList(".*")));
supportedMediaTypes = transcoder.getSupportedMediaTypes();
}
@Override
public void testTranscoderTranscode() {
MediaType personMediaType = MediaType.fromString("application/x-java-object;type=org.infinispan.test.data.Person");
Object result = transcoder.transcode(dataSrc, personMediaType, MediaType.APPLICATION_SERIALIZED_OBJECT);
assertTrue(result instanceof byte[], "Must be byte[]");
Object transcodedBack = transcoder.transcode(result, MediaType.APPLICATION_SERIALIZED_OBJECT, personMediaType);
assertEquals(transcodedBack, dataSrc, "Must be an equal objects");
}
}
| 1,692
| 38.372093
| 121
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/factories/TestDelayFactory.java
|
package org.infinispan.factories;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* Internal class, only used for testing.
*
* It has to reside in the production source tree because the component metadata persister doesn't parse
* test classes.
*
* @author Dan Berindei
* @since 5.2
*/
@Scope(Scopes.GLOBAL)
@DefaultFactoryFor(classes = TestDelayFactory.Component.class)
public class TestDelayFactory extends AbstractComponentFactory implements AutoInstantiableFactory {
private boolean injectionDone = false;
private Control control;
@Inject
public void inject(Control control) {
this.control = control;
control.await();
injectionDone = true;
}
// Implement the old construct method for testing
public <T> T construct(Class<T> componentType) {
if (!injectionDone) {
throw new IllegalStateException("GlobalConfiguration reference is null");
}
return componentType.cast(new Component());
}
@Scope(Scopes.GLOBAL)
public static class Component {
}
@Scope(Scopes.GLOBAL)
public static class Control {
private final CountDownLatch latch = new CountDownLatch(1);
public void await() {
try {
latch.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void unblock() {
latch.countDown();
}
}
}
| 1,679
| 26.096774
| 104
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/factories/DataContainerFactoryTest.java
|
package org.infinispan.factories;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.testng.AssertJUnit.assertEquals;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.container.impl.BoundedSegmentedDataContainer;
import org.infinispan.container.impl.DefaultDataContainer;
import org.infinispan.container.impl.DefaultSegmentedDataContainer;
import org.infinispan.container.impl.L1SegmentedDataContainer;
import org.infinispan.container.offheap.BoundedOffHeapDataContainer;
import org.infinispan.container.offheap.OffHeapConcurrentMap;
import org.infinispan.container.offheap.OffHeapDataContainer;
import org.infinispan.container.offheap.SegmentedBoundedOffHeapDataContainer;
import org.infinispan.eviction.EvictionStrategy;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(testName = "factories.DataContainerFactoryTest", groups = "functional")
public class DataContainerFactoryTest extends AbstractInfinispanTest {
private static final String COMPONENT_NAME = "";
private DataContainerFactory dataContainerFactory;
@BeforeMethod
public void before() {
dataContainerFactory = new DataContainerFactory();
dataContainerFactory.globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder().build();
}
@Test
public void testDefaultConfigurationDataContainer() {
dataContainerFactory.configuration = new ConfigurationBuilder().build();
assertEquals(DefaultDataContainer.class, dataContainerFactory.construct(COMPONENT_NAME).getClass());
}
@Test
public void testOffHeap() {
dataContainerFactory.configuration = new ConfigurationBuilder()
.memory().storageType(StorageType.OFF_HEAP).build();
assertEquals(OffHeapDataContainer.class, dataContainerFactory.construct(COMPONENT_NAME).getClass());
}
@Test
public void testSegmentedOffHeap() {
dataContainerFactory.configuration = new ConfigurationBuilder().clustering().cacheMode(CacheMode.DIST_ASYNC)
.memory().storageType(StorageType.OFF_HEAP).build();
Object component = dataContainerFactory.construct(COMPONENT_NAME);
assertEquals(DefaultSegmentedDataContainer.class, component.getClass());
}
@Test
public void testSegmentedOffHeapAndL1() {
dataContainerFactory = spy(new DataContainerFactory());
doReturn(mock(OffHeapConcurrentMap.class))
.when(dataContainerFactory)
.createAndStartOffHeapConcurrentMap();
dataContainerFactory.globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder().build();
dataContainerFactory.configuration = new ConfigurationBuilder().clustering()
.cacheMode(CacheMode.DIST_ASYNC)
.l1().enable()
.memory().storageType(StorageType.OFF_HEAP).build();
Object component = dataContainerFactory.construct(COMPONENT_NAME);
assertEquals(L1SegmentedDataContainer.class, component.getClass());
}
@Test
public void testDefaultSegmented() {
dataContainerFactory.configuration = new ConfigurationBuilder().clustering()
.cacheMode(CacheMode.DIST_ASYNC).build();
Object component = dataContainerFactory.construct(COMPONENT_NAME);
assertEquals(DefaultSegmentedDataContainer.class, component.getClass());
}
@Test
public void testSegmentedL1() {
dataContainerFactory.configuration = new ConfigurationBuilder().clustering()
.cacheMode(CacheMode.DIST_ASYNC)
.l1().enable().build();
Object component = dataContainerFactory.construct(COMPONENT_NAME);
assertEquals(L1SegmentedDataContainer.class, component.getClass());
}
@Test
public void testEvictionRemoveNotSegmented() {
dataContainerFactory.configuration = new ConfigurationBuilder().clustering()
.memory().evictionStrategy(EvictionStrategy.REMOVE).size(1000).build();
assertEquals(DefaultDataContainer.class, this.dataContainerFactory.construct(COMPONENT_NAME).getClass());
}
@Test
public void testEvictionRemoveSegmented() {
dataContainerFactory.configuration = new ConfigurationBuilder().clustering()
.memory().evictionStrategy(EvictionStrategy.REMOVE).size(1000)
.clustering().cacheMode(CacheMode.DIST_ASYNC).build();
Object component = dataContainerFactory.construct(COMPONENT_NAME);
assertEquals(BoundedSegmentedDataContainer.class, component.getClass());
}
@Test
public void testEvictionRemoveNotSegmentedOffHeap() {
dataContainerFactory.configuration = new ConfigurationBuilder().clustering()
.memory().storageType(StorageType.OFF_HEAP).evictionStrategy(EvictionStrategy.REMOVE).size(1000)
.build();
assertEquals(BoundedOffHeapDataContainer.class, this.dataContainerFactory.construct(COMPONENT_NAME).getClass());
}
@Test
public void testEvictionRemoveSegmentedOffHeap() {
dataContainerFactory.configuration = new ConfigurationBuilder().clustering()
.memory().storageType(StorageType.OFF_HEAP).evictionStrategy(EvictionStrategy.REMOVE).size(1000)
.clustering().cacheMode(CacheMode.DIST_ASYNC).build();
Object component = dataContainerFactory.construct(COMPONENT_NAME);
assertEquals(SegmentedBoundedOffHeapDataContainer.class, component.getClass());
}
}
| 5,701
| 41.87218
| 118
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/factories/ComponentRegistryTest.java
|
package org.infinispan.factories;
import static org.mockito.Mockito.mock;
import static org.testng.Assert.assertNotNull;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.infinispan.AdvancedCache;
import org.infinispan.configuration.ConfigurationManager;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.manager.TestModuleRepository;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Test the concurrent lookup of components for ISPN-2796.
*
* @author Dan Berindei
* @since 5.2
*/
@Test(groups = "unit", testName = "factories.ComponentRegistryTest")
public class ComponentRegistryTest extends AbstractInfinispanTest {
private GlobalComponentRegistry gcr;
private ComponentRegistry cr1;
private ComponentRegistry cr2;
private TestDelayFactory.Control control;
@BeforeMethod
public void setUp() throws InterruptedException, ExecutionException {
GlobalConfiguration gc = new GlobalConfigurationBuilder().build();
Configuration c = new ConfigurationBuilder().build();
Set<String> cachesSet = new HashSet<>();
EmbeddedCacheManager cm = mock(EmbeddedCacheManager.class);
AdvancedCache cache = mock(AdvancedCache.class);
gcr = new GlobalComponentRegistry(gc, cm, cachesSet, TestModuleRepository.defaultModuleRepository(),
mock(ConfigurationManager.class));
cr1 = new ComponentRegistry("cache", c, cache, gcr, ComponentRegistryTest.class.getClassLoader());
cr2 = new ComponentRegistry("cache", c, cache, gcr, ComponentRegistryTest.class.getClassLoader());
control = new TestDelayFactory.Control();
gcr.registerComponent(control, TestDelayFactory.Control.class);
}
public void testSingleThreadLookup() {
control.unblock();
TestDelayFactory.Component c1 = cr1.getOrCreateComponent(TestDelayFactory.Component.class);
assertNotNull(c1);
TestDelayFactory.Component c2 = cr1.getOrCreateComponent(TestDelayFactory.Component.class);
assertNotNull(c2);
}
public void testConcurrentLookupSameComponentRegistry() throws Exception {
testConcurrentLookup(cr1, cr2);
}
public void testConcurrentLookupDifferentComponentRegistries() throws Exception {
testConcurrentLookup(cr1, cr2);
}
private void testConcurrentLookup(ComponentRegistry cr1, ComponentRegistry cr2) throws Exception {
Future<TestDelayFactory.Component> future1 = fork(
() -> cr1.getOrCreateComponent(TestDelayFactory.Component.class));
Future<TestDelayFactory.Component> future2 = fork(
() -> cr2.getOrCreateComponent(TestDelayFactory.Component.class));
Thread.sleep(500);
assertFalse(future1.isDone());
assertFalse(future2.isDone());
control.unblock();
assertNotNull(future1.get());
assertNotNull(future2.get());
}
public void testGetLocalComponent() {
GlobalComponentRegistry localGcr = cr1.getLocalComponent(GlobalComponentRegistry.class);
assertNull(localGcr);
}
}
| 3,565
| 37.344086
| 106
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/factories/threads/ThreadNameInfoTest.java
|
package org.infinispan.factories.threads;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.Test;
/**
* @author Galder Zamarreño
*/
@Test(groups = "unit", testName = "factories.threads.ThreadNameInfoTest")
public class ThreadNameInfoTest {
public void testThreadNamePatterns() {
ThreadNameInfo name = new ThreadNameInfo(100, 1, 2, "nodeX", "eviction");
String threadName = name.format(Thread.currentThread(), "infinispan-%n-%c-p%f-t%t");
assertEquals("infinispan-nodeX-eviction-p2-t1", threadName);
threadName = name.format(Thread.currentThread(), "%%-%g%p%");
assertEquals("%-100system:main", threadName);
}
}
| 686
| 28.869565
| 90
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/factories/impl/FactoryAutoInstantiationTest.java
|
package org.infinispan.factories.impl;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.testng.AssertJUnit.assertNotNull;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.infinispan.factories.AutoInstantiableFactory;
import org.infinispan.factories.ComponentFactory;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.manager.ModuleRepository;
import org.infinispan.manager.TestModuleRepository;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "factories.impl.FactoryAutoInstantiationTest")
public class FactoryAutoInstantiationTest extends AbstractInfinispanTest {
private ModuleRepository moduleRepository;
private BasicComponentRegistryImpl globalRegistry;
private BasicComponentRegistryImpl cacheRegistry;
@BeforeMethod(alwaysRun = true)
public void setup() {
moduleRepository = TestModuleRepository.defaultModuleRepository();
globalRegistry = new BasicComponentRegistryImpl(moduleRepository, true, null);
cacheRegistry = new BasicComponentRegistryImpl(moduleRepository, false, globalRegistry);
}
@AfterMethod(alwaysRun = true)
public void tearDown() {
cacheRegistry.stop();
globalRegistry.stop();
}
public void testConcurrentAutoInstantiation() throws Exception {
globalRegistry.registerComponent(AFactoryDependency.class, new AFactoryDependency(), true);
int numThreads = 2;
CyclicBarrier barrier = new CyclicBarrier(numThreads + 1);
ExecutorService threadPool = Executors.newFixedThreadPool(numThreads, getTestThreadFactory("Worker"));
ExecutorCompletionService<Object> completionService = new ExecutorCompletionService<>(threadPool);
for (int i = 0; i < numThreads; i++) {
completionService.submit(() -> {
barrier.await(10, SECONDS);
ComponentRef<AComponent> aRef = cacheRegistry.getComponent(AComponent.class);
return aRef.wired();
});
}
Thread.sleep(1);
barrier.await(10, SECONDS);
threadPool.shutdown();
for (int i = 0; i < numThreads; i++) {
Future<Object> future = completionService.poll(111, SECONDS);
assertNotNull(future);
assertNotNull(future.get());
}
}
@Scope(Scopes.GLOBAL)
public static class AComponent {
}
@Scope(Scopes.GLOBAL)
public static class AFactoryDependency{
}
@Scope(Scopes.GLOBAL)
@DefaultFactoryFor(classes = AComponent.class)
public static class AComponentFactory implements ComponentFactory, AutoInstantiableFactory {
@Inject
void inject(AFactoryDependency aDependency) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public Object construct(String componentName) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new AComponent();
}
}
}
| 3,507
| 34.795918
| 108
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/factories/impl/BasicComponentRegistryImplTest.java
|
package org.infinispan.factories.impl;
import static org.infinispan.commons.test.Exceptions.expectException;
import static org.testng.AssertJUnit.assertNotNull;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.factories.ComponentFactory;
import org.infinispan.factories.annotations.ComponentName;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.manager.ModuleRepository;
import org.infinispan.manager.TestModuleRepository;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "factories.impl.BasicComponentRegistryImplTest")
public class BasicComponentRegistryImplTest {
private ModuleRepository moduleRepository;
private BasicComponentRegistryImpl globalRegistry;
private BasicComponentRegistryImpl cacheRegistry;
@BeforeMethod(alwaysRun = true)
public void setup() {
moduleRepository = TestModuleRepository.defaultModuleRepository();
globalRegistry = new BasicComponentRegistryImpl(moduleRepository, true, null);
cacheRegistry = new BasicComponentRegistryImpl(moduleRepository, false, globalRegistry);
}
@AfterMethod(alwaysRun = true)
public void tearDown() {
cacheRegistry.stop();
globalRegistry.stop();
}
public void testRegisterNoFactory() {
globalRegistry.registerComponent(A.class.getName(), new A(), false);
// The AA alias doesn't exist at this point
expectException(RuntimeException.class,
() -> globalRegistry.wireDependencies(new B(), true));
expectException(RuntimeException.class,
() -> globalRegistry.registerComponent(B.class.getName(), new B(), false));
globalRegistry.registerAlias("AA", A.class.getName(), A.class);
B b1 = new B();
globalRegistry.wireDependencies(b1, true);
assertNotNull(b1.a);
// B is already in the failed state, can't register it again
expectException(RuntimeException.class,
() -> globalRegistry.registerComponent(B.class.getName(), new B(), false));
// Replace the failed component with a running one
globalRegistry.replaceComponent(B.class.getName(), b1, true);
C c1 = new C();
globalRegistry.wireDependencies(c1, true);
assertNotNull(c1.a);
assertNotNull(c1.b);
C c2 = new C();
globalRegistry.registerComponent(C.class.getName(), c2, false);
assertNotNull(c2.a);
assertNotNull(c2.b);
}
public void testRegisterWrongScope() {
// There's no check that the class scope matches the interface (or superclass) scope yet
expectException(RuntimeException.class,
() -> globalRegistry.registerComponent(D.class.getName(), new D3(), false));
cacheRegistry.registerComponent(D.class.getName(), new D3(), false);
expectException(RuntimeException.class,
() -> cacheRegistry.registerComponent(H.class.getName(), new H(), false));
globalRegistry.registerComponent(H.class.getName(), new H(), false);
}
@DataProvider(name = "cycleClasses")
public Object[][] cycleClasses() {
return new Object[][]{{D.class}, {E.class}, {F.class}};
}
@Test(dataProvider = "cycleClasses")
public void testDependencyCycle(Class<?> entryPoint) {
cacheRegistry.registerComponent(DEFFactory.class.getName(), new DEFFactory(new D1()), false);
expectException(RuntimeException.class,
() -> cacheRegistry.getComponent(entryPoint));
}
public void testDependencyCycleNoStart() {
cacheRegistry.registerComponent(DEFFactory.class.getName(), new DEFFactory(new D1()), false);
G g = new G();
expectException(RuntimeException.class,
() -> cacheRegistry.registerComponent(G.class.getName(), g, false));
}
@Test(dataProvider = "cycleClasses")
public void testDependencyCycleLazy(Class<?> entryPoint) {
cacheRegistry.registerComponent(DEFFactory.class.getName(), new DEFFactory(new D2()), false);
ComponentRef<?> component = cacheRegistry.getComponent(entryPoint);
assertNotNull(component);
Object instance = component.wired();
assertNotNull(instance);
}
public void testDependencyCycleLazyNoStart() {
registerGlobals();
cacheRegistry.registerComponent(DEFFactory.class.getName(), new DEFFactory(new D2()), false);
G g = new G();
cacheRegistry.registerComponent(G.class.getName(), g, false);
assertNotNull(g);
assertNotNull(g.c);
assertNotNull(g.c.a);
assertNotNull(g.c.b);
assertNotNull(g.f.e);
assertNotNull(g.f.e.d);
assertNotNull(g.f);
}
public void testFactoryRegistersComponent() {
globalRegistry.registerComponent(HFactory.class.getName(), new HFactory(globalRegistry), false);
ComponentRef<H> href = globalRegistry.getComponent(H.class.getName(), H.class);
assertNotNull(href);
H h = href.wired();
assertNotNull(h);
// I is now in the failed state
ComponentRef<I> iref = globalRegistry.getComponent(I.class);
expectException(IllegalLifecycleStateException.class, iref::wired);
}
private void registerGlobals() {
globalRegistry.registerComponent(A.class.getName(), new A(), false);
globalRegistry.registerAlias("AA", A.class.getName(), A.class);
globalRegistry.registerComponent(B.class.getName(), new B(), false);
globalRegistry.registerComponent(C.class.getName(), new C(), false);
}
@Scope(Scopes.GLOBAL)
static class A {
}
@Scope(Scopes.GLOBAL)
static class B {
@ComponentName("AA")
@Inject A a;
}
@Scope(Scopes.GLOBAL)
static class C {
A a;
B b;
@Inject
void inject(@ComponentName("AA") A a, B b) {
this.a = a;
this.b = b;
}
}
@Scope(Scopes.NAMED_CACHE)
interface D {
}
@Scope(Scopes.NAMED_CACHE)
static class D1 implements D {
@Inject F f;
}
@Scope(Scopes.NAMED_CACHE)
static class D2 implements D {
@Inject ComponentRef<F> f;
}
@Scope(Scopes.NAMED_CACHE)
static class D3 implements D {
}
@Scope(Scopes.NAMED_CACHE)
static class E {
@ComponentName("DD")
@Inject D d;
}
@Scope(Scopes.NAMED_CACHE)
static class F {
@Inject E e;
}
@Scope(Scopes.NAMED_CACHE)
static class G {
@Inject C c;
@Inject F f;
}
@Scope(Scopes.GLOBAL)
static class H {
}
@Scope(Scopes.GLOBAL)
static class I {
@Inject H h;
}
@DefaultFactoryFor(classes = {D.class, E.class, F.class}, names = "DD")
@Scope(Scopes.NAMED_CACHE)
static class DEFFactory implements ComponentFactory {
private final D d;
DEFFactory(D d) {
this.d = d;
}
@Override
public Object construct(String componentName) {
if (D.class.getName().equals(componentName)) {
return d;
}
if ("DD".equals(componentName)) {
return ComponentAlias.of(D.class);
}
if (E.class.getName().equals(componentName)) {
return new E();
}
if (F.class.getName().equals(componentName)) {
return new F();
}
throw new UnsupportedOperationException();
}
}
@DefaultFactoryFor(classes = H.class)
@Scope(Scopes.GLOBAL)
public static class HFactory implements ComponentFactory {
final BasicComponentRegistry registry;
HFactory(BasicComponentRegistry registry) {
this.registry = registry;
}
@Override
public Object construct(String componentName) {
if (H.class.getName().equals(componentName)) {
// Registering I would block waiting on H
expectException(RuntimeException.class, () -> registry.registerComponent(I.class.getName(), new I(), false));
H h = new H();
// Our thread has already started registering H
expectException(RuntimeException.class, () -> registry.registerComponent(H.class.getName(), h, false));
// Registering an unrelated component is allowed
registry.registerComponent("HH", h, false);
return h;
}
throw new UnsupportedOperationException();
}
}
}
| 8,601
| 30.859259
| 121
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/factories/impl/TestComponentAccessors.java
|
package org.infinispan.factories.impl;
import java.util.IdentityHashMap;
import java.util.Map;
import org.infinispan.manager.TestModuleRepository;
import org.infinispan.test.RunningComponentRef;
/**
* Helper for TestingUtil.inject() and TestingUtil.invokeLifecycle()
*/
public final class TestComponentAccessors {
public static void wire(Object target, Object... components) {
TestWireContext wireContext = new TestWireContext(components);
String accessorName = target.getClass().getName();
while (accessorName != null) {
ComponentAccessor<Object> componentAccessor =
TestModuleRepository.defaultModuleRepository().getComponentAccessor(accessorName);
componentAccessor.wire(target, wireContext, false);
accessorName = componentAccessor.getSuperAccessorName();
}
Map<Object, Object> unmatchedComponents = new IdentityHashMap<>();
for (Object component : components) {
if (!wireContext.matchedComponents.containsKey(component)) {
unmatchedComponents.put(component, component);
}
}
if (!unmatchedComponents.isEmpty()) {
throw new IllegalArgumentException("No fields match components " + unmatchedComponents.values());
}
}
public static void start(Object target) throws Exception {
String accessorName = target.getClass().getName();
while (accessorName != null) {
ComponentAccessor<Object> componentAccessor =
TestModuleRepository.defaultModuleRepository().getComponentAccessor(accessorName);
componentAccessor.start(target);
accessorName = componentAccessor.getSuperAccessorName();
}
}
public static void stop(Object target) throws Exception {
String accessorName = target.getClass().getName();
while (accessorName != null) {
ComponentAccessor<Object> componentAccessor =
TestModuleRepository.defaultModuleRepository().getComponentAccessor(accessorName);
componentAccessor.stop(target);
accessorName = componentAccessor.getSuperAccessorName();
}
}
public static final class NamedComponent {
private final String name;
private final Object component;
public NamedComponent(String name, Object component) {
this.name = name;
this.component = component;
}
@Override
public String toString() {
return "NamedComponent{" +
"name='" + name + '\'' +
", component=" + component +
'}';
}
}
static class TestWireContext extends WireContext {
private final Object[] components;
private final Map<Object, Object> matchedComponents;
public TestWireContext(Object[] components) {
super(null);
this.components = components;
matchedComponents = new IdentityHashMap<>(components.length);
}
private <T> T findComponent(String componentName, Class<T> componentType) {
for (Object component : components) {
Object currentMatch = null;
Object componentInstance = null;
if (component instanceof NamedComponent) {
NamedComponent nc = (NamedComponent) component;
if (componentName.equals(nc.name)) {
currentMatch = nc;
componentInstance = nc.component;
}
} else {
if (componentType.isInstance(component)) {
currentMatch = component;
componentInstance = component;
}
}
if (currentMatch != null) {
Object previousMatch = matchedComponents.put(currentMatch, currentMatch);
if (previousMatch != null) {
throw new IllegalArgumentException("Ambiguous injection, dependency " + componentName +
" is matched by both " + previousMatch + " and " + component);
}
return (T) componentInstance;
}
}
return null;
}
@Override
public <T> T get(String componentName, Class<T> componentClass, boolean start) {
return findComponent(componentName, componentClass);
}
@Override
public <T, U extends T> ComponentRef<T> getLazy(String componentName, Class<U> componentClass, boolean start) {
return new RunningComponentRef<T>(componentName, componentClass, findComponent(componentName, componentClass));
}
}
}
| 4,575
| 36.508197
| 120
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/factories/impl/MockBasicComponentRegistry.java
|
package org.infinispan.factories.impl;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.infinispan.test.RunningComponentRef;
import org.mockito.Mockito;
public class MockBasicComponentRegistry implements BasicComponentRegistry {
private ConcurrentMap<String, RunningComponentRef> components = new ConcurrentHashMap<>();
public void registerMock(String componentName, Class<?> componentType) {
registerComponent(componentName, Mockito.mock(componentType, Mockito.RETURNS_DEEP_STUBS), false);
}
public void registerMocks(Class<?>... componentTypes) {
for (Class<?> componentType : componentTypes) {
registerComponent(componentType, Mockito.mock(componentType, Mockito.RETURNS_DEEP_STUBS), false);
}
}
@Override
public <T, U extends T> ComponentRef<T> getComponent(String name, Class<U> componentType) {
return (ComponentRef<T>) components.get(name);
}
@Override
public <T> ComponentRef<T> registerComponent(String componentName, T instance, boolean manageLifecycle) {
RunningComponentRef<T> componentRef = new RunningComponentRef<T>(componentName, instance.getClass(), instance);
components.put(componentName, componentRef);
return componentRef;
}
@Override
public void registerAlias(String aliasName, String targetComponentName, Class<?> targetComponentType) {
throw new UnsupportedOperationException();
}
@Override
public void wireDependencies(Object target, boolean startDependencies) {
// Do nothing
}
public void registerSubComponent(String ownerComponentName, String subComponentName, Object instance) {
registerComponent(subComponentName, instance, false);
}
@Override
public void addDynamicDependency(String ownerComponentName, String dependencyComponentName) {
// Do nothing
}
@Override
public void replaceComponent(String componentName, Object newInstance, boolean manageLifecycle) {
throw new UnsupportedOperationException();
}
@Override
public void rewire() {
throw new UnsupportedOperationException();
}
@Override
public Collection<ComponentRef<?>> getRegisteredComponents() {
throw new UnsupportedOperationException();
}
@Override
public MBeanMetadata getMBeanMetadata(String className) {
return null;
}
@Override
public boolean hasComponentAccessor(String componentClassName) {
return false;
}
@Override
public void stop() {
components.clear();
}
@Override
public <T> ComponentRef<T> lazyGetComponent(Class<T> componentType) {
return (ComponentRef<T>) components.get(componentType.getName());
}
}
| 2,755
| 29.966292
| 117
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/GetEntryTxTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertNotNull;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.testng.annotations.Test;
/**
* Tests for getCacheEntry under Tx
*
* @author gustavonalle
* @since 8.0
*/
@Test(groups = "functional", testName = "tx.GetEntryTxTest")
public class GetEntryTxTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
builder.clustering().hash().numOwners(1);
createCluster(TestDataSCI.INSTANCE, builder, 2);
waitForClusterToForm();
}
public void testGetEntry() throws Exception {
Cache<MagicKey, String> cache = cache(0);
MagicKey localKey = new MagicKey(cache(0));
MagicKey remoteKey = new MagicKey(cache(1));
cache.put(localKey, localKey.toString());
cache.put(remoteKey, remoteKey.toString());
assertNotNull(cache.getAdvancedCache().getCacheEntry(localKey));
assertNotNull(cache.getAdvancedCache().getCacheEntry(remoteKey));
}
}
| 1,371
| 30.181818
| 95
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/RemoteLockCleanupTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
/**
* Test fpr ISPN-777.
*
* @author Mircea.Markus@jboss.com
* @since 4.2
*/
@Test(groups = "functional", testName = "tx.RemoteLockCleanupTest")
public class RemoteLockCleanupTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder config = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
config.transaction().lockingMode(LockingMode.PESSIMISTIC);
super.createClusteredCaches(2, TestDataSCI.INSTANCE, config);
}
public void testLockCleanup() throws Exception {
final DelayInterceptor interceptor = new DelayInterceptor();
extractInterceptorChain(advancedCache(0)).addInterceptor(interceptor, 1);
final Object k = getKeyForCache(0);
fork(() -> {
try {
tm(1).begin();
advancedCache(1).lock(k);
tm(1).suspend();
} catch (Exception e) {
log.error(e);
}
});
eventually(() -> interceptor.receivedReplRequest);
TestingUtil.killCacheManagers(manager(1));
TestingUtil.blockUntilViewsReceived(60000, false, cache(0));
TestingUtil.waitForNoRebalance(cache(0));
eventually(() -> interceptor.lockAcquired);
assertEventuallyNotLocked(cache(0), "k");
}
static public class DelayInterceptor extends DDAsyncInterceptor {
volatile boolean receivedReplRequest = false;
volatile boolean lockAcquired = false;
@Override
public Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) throws Throwable {
if (!ctx.isOriginLocal()) {
receivedReplRequest = true;
// TODO: we can replace this with the BlockingInterceptor instead or something equivalent to remove 5s wait
Thread.sleep(5000);
try {
return super.visitLockControlCommand(ctx, command);
} finally {
lockAcquired = true;
}
} else {
return super.visitLockControlCommand(ctx, command);
}
}
@Override
public Object visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) throws Throwable {
return super.visitRollbackCommand(ctx, command);
}
}
}
| 2,956
| 31.855556
| 119
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/OnePhaseXATest.java
|
package org.infinispan.tx;
import java.util.ArrayList;
import java.util.List;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "tx.OnePhaseXATest", description = "See ISPN-156 for details.")
public class OnePhaseXATest extends AbstractInfinispanTest {
private List<Cache> caches;
private List<EmbeddedCacheManager> cacheContainers;
public static final int CACHES_NUM = 2;
public void testMultipleCaches() throws Exception {
//add something to cache
int i = 0;
for (Cache c : caches) {
TransactionManager tm = TestingUtil.getTransactionManager(c);
tm.begin();
c.put("key" + i, "value");
tm.commit();
i++;
}
//check if caches contain these same keys
i = 0;
for (Cache c : caches) {
assert "value".equals(c.get("key0")) : "Failed getting value for key0 on cache " + i;
assert "value".equals(c.get("key1")) : "Failed getting value for key1 on cache " + i;
i++;
}
}
@BeforeClass
public void setUp() throws Exception {
caches = new ArrayList<>();
cacheContainers = new ArrayList<>();
for (int i = 0; i < CACHES_NUM; i++) caches.add(getCache());
}
@AfterClass
public void tearDown() {
if (caches != null) TestingUtil.killCacheManagers(cacheContainers);
}
private Cache getCache() {
GlobalConfigurationBuilder gc = GlobalConfigurationBuilder.defaultClusteredBuilder();
ConfigurationBuilder c = new ConfigurationBuilder();
c.clustering().cacheMode(CacheMode.REPL_SYNC)
.remoteTimeout(30000)
.transaction().invocationBatching().enable()
.locking().lockAcquisitionTimeout(60000).useLockStriping(false);
EmbeddedCacheManager container = TestCacheManagerFactory.createClusteredCacheManager(gc, c);
cacheContainers.add(container);
container.defineConfiguration("TestCache", c.build());
return container.getCache("TestCache");
}
}
| 2,564
| 34.136986
| 103
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/LockAfterNodesLeftTest.java
|
package org.infinispan.tx;
import static org.testng.Assert.assertEquals;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.impl.TransactionTable;
import org.testng.annotations.Test;
/**
* Test for ISPN-2469.
*
* @author Carsten Lohmann
*/
@Test(groups = "functional", testName = "tx.LockAfterNodesLeftTest")
public class LockAfterNodesLeftTest extends MultipleCacheManagersTest {
private final int INITIAL_CLUSTER_SIZE = 6;
private final int NUM_NODES_TO_STOP_FOR_TEST = 3;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cacheConfig = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true);
cacheConfig.transaction().lockingMode(LockingMode.PESSIMISTIC);
createClusteredCaches(INITIAL_CLUSTER_SIZE, cacheConfig);
waitForClusterToForm();
}
public void test() throws Exception {
log.debug("Adding test key");
cache(0).put("k", "v");
// ensure that there are no transactions left
for (int i = 0; i < INITIAL_CLUSTER_SIZE; i++) {
final TransactionTable transactionTable = TestingUtil.getTransactionTable(cache(i));
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
return transactionTable.getLocalTransactions().isEmpty();
}
});
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
return transactionTable.getRemoteTransactions().isEmpty();
}
});
}
TestingUtil.sleepThread(2000);
log.debug("Shutting down some nodes ..");
for (int i = 0; i < NUM_NODES_TO_STOP_FOR_TEST; i++) {
cacheManagers.get(INITIAL_CLUSTER_SIZE - 1 - i).stop();
}
log.debug("Shutdown completed");
final int remainingNodesCount = INITIAL_CLUSTER_SIZE - NUM_NODES_TO_STOP_FOR_TEST;
TestingUtil.sleepThread(2000);
// now do a parallel put on the cache
final String key = "key";
final AtomicInteger errorCount = new AtomicInteger();
final AtomicInteger rolledBack = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
Thread[] threads = new Thread[remainingNodesCount];
for (int i = 0; i < remainingNodesCount; i++) {
final int nodeIndex = i;
threads[i] = new Thread("LockAfterNodesLeftTest.Putter-" + i) {
public void run() {
try {
latch.await();
log.debug("about to begin transaction...");
tm(nodeIndex).begin();
try {
log.debug("Getting lock on cache key");
cache(nodeIndex).getAdvancedCache().lock(key);
log.debug("Got lock");
cache(nodeIndex).put(key, "value");
log.debug("Done with put");
TestingUtil.sleepRandom(200);
tm(nodeIndex).commit();
} catch (Throwable e) {
if (e instanceof RollbackException) {
rolledBack.incrementAndGet();
} else if (tm(nodeIndex).getTransaction() != null) {
// the TX is most likely rolled back already, but we attempt a rollback just in case it isn't
try {
tm(nodeIndex).rollback();
rolledBack.incrementAndGet();
} catch (SystemException e1) {
log.error("Failed to rollback", e1);
}
}
throw e;
}
} catch (Throwable e) {
errorCount.incrementAndGet();
log.error(e);
}
}
};
threads[i].start();
}
latch.countDown();
for (Thread t : threads) {
t.join();
}
log.trace("Got errors: " + errorCount.get());
assertEquals(0, errorCount.get());
}
}
| 4,563
| 34.107692
| 117
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/OptimisticPartialCommitTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.concurrent.StateSequencerUtil.advanceOnGlobalComponentMethod;
import static org.infinispan.test.concurrent.StateSequencerUtil.advanceOnInterceptor;
import static org.infinispan.test.concurrent.StateSequencerUtil.matchCommand;
import static org.infinispan.test.concurrent.StateSequencerUtil.matchMethodCall;
import static org.testng.AssertJUnit.assertEquals;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.infinispan.commands.tx.VersionedCommitCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.statetransfer.StateTransferInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.concurrent.InvocationMatcher;
import org.infinispan.test.concurrent.StateSequencer;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.topology.ClusterTopologyManager;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.impl.LocalTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ControlledConsistentHashFactory;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
/**
* Test that the modifications of a transaction that were not committed on a node because it didn't own all the keys
* are still applied after the node becomes an owner for all of them.
*
* @author Dan Berindei
*/
@CleanupAfterMethod
@Test(groups = "functional", testName = "tx.OptimisticPartialCommitTest")
public class OptimisticPartialCommitTest extends MultipleCacheManagersTest {
private ControlledConsistentHashFactory controlledCHFactory;
@Override
protected void createCacheManagers() throws Throwable {
controlledCHFactory = new ControlledConsistentHashFactory.Default(new int[][]{{1, 2}, {2, 3}});
ConfigurationBuilder configuration = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
configuration.clustering().cacheMode(CacheMode.DIST_SYNC);
configuration.clustering().hash().numSegments(2).numOwners(2).consistentHashFactory(controlledCHFactory);
configuration.transaction().lockingMode(LockingMode.OPTIMISTIC)
.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
createCluster(TestDataSCI.INSTANCE, configuration, 4);
waitForClusterToForm();
}
public void testNonOwnerBecomesOwnerDuringCommit() throws Exception {
final Object k1 = new MagicKey("k1", cache(1), cache(2));
final Object k2 = new MagicKey("k2", cache(2), cache(3));
cache(0).put(k1, "v1_0");
cache(0).put(k2, "v2_0");
// commit on cache 0 -> send commit to 1, 2, 3 -> block commit on 2 -> wait for the commit on 1 to finish
// -> kill 3 -> rebalance -> 1 applies state from 2 -> 2 resends commit to 1 -> 1 commits again (including k2)
// Without the fix, the second commit is ignored and k2 is not updated
StateSequencer ss = new StateSequencer();
ss.logicalThread("main", "after_commit_on_1", "before_kill_3",
"after_state_applied_on_1", "before_commit_on_2", "after_commit_on_2");
advanceOnInterceptor(ss, cache(1), StateTransferInterceptor.class,
matchCommand(VersionedCommitCommand.class).matchCount(0).build())
.after("after_commit_on_1");
advanceOnInterceptor(ss, cache(2), StateTransferInterceptor.class,
matchCommand(VersionedCommitCommand.class).matchCount(0).build())
.before("before_commit_on_2").after("after_commit_on_2");
InvocationMatcher stateAppliedOn0Matcher = matchMethodCall("handleRebalancePhaseConfirm")
.withParam(1, address(1)).build();
advanceOnGlobalComponentMethod(ss, manager(0), ClusterTopologyManager.class, stateAppliedOn0Matcher)
.after("after_state_applied_on_1");
Future<Object> txFuture = fork(() -> {
tm(0).begin();
try {
cache(0).put(k1, "v1_1");
cache(0).put(k2, "v2_1");
} finally {
tm(0).commit();
}
return null;
});
ss.advance("before_kill_3");
controlledCHFactory.setOwnerIndexes(new int[][]{{1, 2}, {2, 1}});
manager(3).stop();
cacheManagers.remove(3);
txFuture.get(30, TimeUnit.SECONDS);
assertEquals("v1_1", cache(1).get(k1));
assertEquals("v2_1", cache(1).get(k2));
assertEquals("v1_1", cache(2).get(k1));
assertEquals("v2_1", cache(2).get(k2));
}
public void testOriginatorBecomesOwnerDuringCommit() throws Exception {
final Object k1 = new MagicKey("k1", cache(1), cache(2));
final Object k2 = new MagicKey("k2", cache(2), cache(3));
cache(1).put(k1, "v1_0");
cache(1).put(k2, "v2_0");
// commit on cache 1 -> send commit to 2 and 3 -> kill 3
// -> rebalance -> 1 receives state from 2 -> 2 doesn't resend commit to 1 -> 1 finishes commit
// Cache 1 wrapped k2 before the prepare, so it will update it during commit even without repeating the commit
StateSequencer ss = new StateSequencer();
ss.logicalThread("main", "before_kill_3",
"after_state_applied_on_1", "before_commit_on_2", "after_commit_on_2", "after_commit_on_1");
// avoids blockhound exception in the next method
TransactionTable transactionTable = transactionTable(1);
advanceOnInterceptor(ss, cache(1), StateTransferInterceptor.class,
command -> {
if (!(command instanceof VersionedCommitCommand))
return false;
GlobalTransaction gtx = ((VersionedCommitCommand) command).getGlobalTransaction();
LocalTransaction tx = transactionTable.getLocalTransaction(gtx);
return tx.getStateTransferFlag() == null;
}).after("after_commit_on_1");
advanceOnInterceptor(ss, cache(2), StateTransferInterceptor.class,
matchCommand(VersionedCommitCommand.class).matchCount(0).build())
.before("before_commit_on_2").after("after_commit_on_2");
InvocationMatcher stateAppliedOn0Matcher = matchMethodCall("handleRebalancePhaseConfirm")
.withParam(1, address(1)).build();
advanceOnGlobalComponentMethod(ss, manager(0), ClusterTopologyManager.class, stateAppliedOn0Matcher)
.after("after_state_applied_on_1");
Future<Object> txFuture = fork(() -> {
tm(0).begin();
try {
cache(1).put(k1, "v1_1");
cache(1).put(k2, "v2_1");
} finally {
tm(0).commit();
}
return null;
});
ss.advance("before_kill_3");
controlledCHFactory.setOwnerIndexes(new int[][]{{1, 2}, {2, 1}});
manager(3).stop();
cacheManagers.remove(3);
txFuture.get(30, TimeUnit.SECONDS);
assertEquals("v1_1", cache(1).get(k1));
assertEquals("v2_1", cache(1).get(k2));
assertEquals("v1_1", cache(2).get(k1));
assertEquals("v2_1", cache(2).get(k2));
}
}
| 7,265
| 43.036364
| 116
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/BatchingAndEnlistmentTest.java
|
package org.infinispan.tx;
import static org.testng.Assert.assertEquals;
import jakarta.transaction.TransactionManager;
import org.infinispan.batch.BatchContainer;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.tm.BatchModeTransactionManager;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.testng.annotations.Test;
/**
* @author Mircea Markus <mircea.markus@jboss.com> (C) 2011 Red Hat Inc.
* @since 5.1
*/
@Test (groups = "functional", testName = "tx.BatchingAndEnlistmentTest")
public class BatchingAndEnlistmentTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.invocationBatching().enable();
cb.transaction().transactionManagerLookup(null);
return TestCacheManagerFactory.createCacheManager(cb);
}
public void testExpectedEnlistmentMode() {
TransactionManager tm = cache.getAdvancedCache().getTransactionManager();
assert tm instanceof BatchModeTransactionManager;
TransactionTable tt = TestingUtil.getTransactionTable(cache);
assertEquals(tt.getClass(), TransactionTable.class);
BatchContainer bc = TestingUtil.extractComponent(cache, BatchContainer.class);
cache.startBatch();
cache.put("k", "v");
assert getBatchTx(bc).getEnlistedSynchronization().size() == 1;
assert getBatchTx(bc).getEnlistedResources().size() == 0;
cache.endBatch(true);
assert getBatchTx(bc) == null;
}
private EmbeddedTransaction getBatchTx(BatchContainer bc) {
return (EmbeddedTransaction) bc.getBatchTransaction();
}
}
| 1,988
| 37.25
| 84
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/PessimisticDeadlockTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import jakarta.transaction.RollbackException;
import jakarta.transaction.TransactionManager;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.remoting.inboundhandler.AbstractDelegatingHandler;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler;
import org.infinispan.remoting.inboundhandler.Reply;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.impl.RemoteTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.util.ControlledConsistentHashFactory;
import org.testng.annotations.Test;
/**
* Test for ISPN-8533
*
* @author Pedro Ruivo
* @since 9.3
*/
@Test(groups = "functional", testName = "tx.PessimisticDeadlockTest")
public class PessimisticDeadlockTest extends MultipleCacheManagersTest {
public void testDeadlock(Method method) throws Exception {
assertEquals(4, managers().length);
final String key = method.getName();
assertOwnership(key);
dropLockCommandInPrimary();
//both transactions will send the LockControlCommand to cache1 and cache2.
//cache1 will discard the command (it will be killed)
//cache2 will acquire the backup lock.
Future<Boolean> tx1 = runTransaction(key, "tx1");
Future<Boolean> tx2 = runTransaction(key, "tx2");
//make sure the backup is acquired in cache2
awaitBackupLocks(key);
killMember(1);
assertEquals(3, managers().length);
//check if the cache2 is actually the primary owner.
//both transactions should re-send the LockControlCommand
assertOwnership(key);
//both txs must complete successfully but we don't know which one was last
//the test fails here if we have a deadlock!
assertTrue(tx1.get(30, TimeUnit.SECONDS));
assertTrue(tx2.get(30, TimeUnit.SECONDS));
//just make sure everything is ok
String result = this.<String, String>cache(0).get(key);
for (Cache<String, String> cache : this.<String, String>caches()) {
assertEquals(result, cache.get(key));
}
assertNoTransactions();
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
builder.transaction().lockingMode(LockingMode.PESSIMISTIC);
builder.clustering().hash().consistentHashFactory(new ControlledConsistentHashFactory.Default(1, 2))
.numSegments(1)
.numOwners(2);
createClusteredCaches(4, builder);
}
private Future<Boolean> runTransaction(String key, String value) {
return fork(() -> {
AdvancedCache<String, String> cache = this.<String, String>cache(0).getAdvancedCache();
TransactionManager tm = cache.getTransactionManager();
tm.begin();
cache.put(key, value);
try {
tm.commit();
return true;
} catch (RollbackException e) {
return false;
}
});
}
private void dropLockCommandInPrimary() {
TestingUtil.wrapInboundInvocationHandler(cache(1), DropLockCommandHandler::new);
}
private void awaitBackupLocks(String key) {
eventually(() -> {
TransactionTable table = TestingUtil.getTransactionTable(cache(2));
Collection<RemoteTransaction> remoteTransactions = table.getRemoteTransactions();
if (remoteTransactions.size() != 2) {
return false;
}
for (RemoteTransaction rtx : remoteTransactions) {
if (!rtx.getBackupLockedKeys().contains(key)) {
return false;
}
}
return true;
});
}
private void assertOwnership(String key) {
for (Cache<?, ?> cache : caches()) {
Collection<Address> writeOwners = cache.getAdvancedCache().getDistributionManager().getCacheTopology()
.getDistribution(key).writeOwners();
assertEquals(Arrays.asList(address(1), address(2)), writeOwners);
}
}
private class DropLockCommandHandler extends AbstractDelegatingHandler {
DropLockCommandHandler(PerCacheInboundInvocationHandler delegate) {
super(delegate);
}
@Override
public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) {
if (!(command instanceof LockControlCommand)) {
delegate.handle(command, reply, order);
}
}
}
}
| 5,219
| 35
| 111
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TransactionsSpanningCachesTest.java
|
package org.infinispan.tx;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", sequential = true, testName = "tx.TransactionsSpanningCachesTestTest")
public class TransactionsSpanningCachesTest extends MultipleCacheManagersTest {
protected StorageType storage1;
protected StorageType storage2;
public Object[] factory() {
return new Object[] {
new TransactionsSpanningCachesTest().withStorage(StorageType.OBJECT, StorageType.OBJECT),
new TransactionsSpanningCachesTest().withStorage(StorageType.OFF_HEAP, StorageType.OFF_HEAP),
new TransactionsSpanningCachesTest().withStorage(StorageType.OBJECT, StorageType.OFF_HEAP)
};
}
@Override
protected void createCacheManagers() throws Exception {
ConfigurationBuilder defaultCacheConfig = TestCacheManagerFactory.getDefaultCacheConfiguration(true);
amendConfig(defaultCacheConfig);
ConfigurationBuilder cb1 = defaultCacheConfig;
ConfigurationBuilder cb2 = defaultCacheConfig;
cb1.memory().storageType(storage1);
cb2.memory().storageType(storage2);
EmbeddedCacheManager cm1 = TestCacheManagerFactory.createCacheManager(cb1);
EmbeddedCacheManager cm2 = TestCacheManagerFactory.createCacheManager(cb2);
cm1.defineConfiguration("c1", cm1.getCache().getCacheConfiguration());
cm2.defineConfiguration("c2", cm2.getCache().getCacheConfiguration());
registerCacheManager(cm1, cm2);
}
protected void amendConfig(ConfigurationBuilder defaultCacheConfig) {
//ignore
}
public TransactionsSpanningCachesTest withStorage(StorageType storage1, StorageType storage2) {
this.storage1 = storage1;
this.storage2 = storage2;
return this;
}
@Override
protected String parameters() {
return "[storage1=" + storage1 + ", storage2=" + storage2 + "]";
}
public void testCommitSpanningCaches() throws Exception {
Cache c1 = cacheManagers.get(0).getCache("c1");
Cache c2 = cacheManagers.get(1).getCache("c2");
assert c1.isEmpty();
assert c2.isEmpty();
c1.put("c1key", "c1value");
c2.put("c2key", "c2value");
assert !c1.isEmpty();
assert c1.size() == 1;
assert c1.get("c1key").equals("c1value");
assert !c2.isEmpty();
assert c2.size() == 1;
assert c2.get("c2key").equals("c2value");
TransactionManager tm = TestingUtil.getTransactionManager(c1);
tm.begin();
c1.put("c1key", "c1value_new");
c2.put("c2key", "c2value_new");
assert c1.get("c1key").equals("c1value_new");
assert c2.get("c2key").equals("c2value_new");
Transaction tx = tm.suspend();
assert c1.get("c1key").equals("c1value");
assert c2.get("c2key").equals("c2value");
tm.resume(tx);
tm.commit();
assert c1.get("c1key").equals("c1value_new");
assert c2.get("c2key").equals("c2value_new");
}
public void testRollbackSpanningCaches() throws Exception {
Cache c1 = cacheManagers.get(0).getCache("c1");
Cache c2 = cacheManagers.get(1).getCache("c2");
assert c1.isEmpty();
assert c2.isEmpty();
c1.put("c1key", "c1value");
c2.put("c2key", "c2value");
assert !c1.isEmpty();
assert c1.size() == 1;
assert c1.get("c1key").equals("c1value");
assert !c2.isEmpty();
assert c2.size() == 1;
assert c2.get("c2key").equals("c2value");
TransactionManager tm = TestingUtil.getTransactionManager(c1);
tm.begin();
c1.put("c1key", "c1value_new");
c2.put("c2key", "c2value_new");
assert c1.get("c1key").equals("c1value_new");
assert c2.get("c2key").equals("c2value_new");
Transaction tx = tm.suspend();
assert c1.get("c1key").equals("c1value");
assert c2.get("c2key").equals("c2value");
tm.resume(tx);
tm.rollback();
assert c1.get("c1key").equals("c1value");
assert c2.get("c2key").equals("c2value");
}
}
| 4,439
| 31.408759
| 107
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TxCompletionForRolledBackXaTxTest.java
|
package org.infinispan.tx;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
@Test (groups = "functional", testName = "tx.TxCompletionForRolledBackXaTxTest")
public class TxCompletionForRolledBackXaTxTest extends TxCompletionForRolledBackTxTest {
@Override
protected void amend(ConfigurationBuilder dcc) {
dcc.transaction().useSynchronization(false);
}
}
| 423
| 29.285714
| 88
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/NoLockLostOnLongTxTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.replaceComponent;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import jakarta.transaction.TransactionManager;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.remote.CheckTransactionRpcCommand;
import org.infinispan.commons.time.TimeService;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.rpc.RpcOptions;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollector;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.impl.RemoteTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ControlledTimeService;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Tests if long running transactions from members which are alive, are not rolled-back by mistake.
*
* @author Pedro Ruivo
* @since 10.0
*/
@Test(groups = "functional", testName = "tx.NoLockLostOnLongTxTest")
public class NoLockLostOnLongTxTest extends MultipleCacheManagersTest {
private static final long COMPLETED_TX_TIMEOUT = 10000;
private ControlledTimeService timeService;
private static Method extractCleanupMethod() throws NoSuchMethodException {
Method m = TransactionTable.class.getDeclaredMethod("cleanupTimedOutTransactions", (Class<?>[]) null);
m.setAccessible(true);
return m;
}
@DataProvider(name = "long-tx-test")
public static Object[][] longTxDataProvider() {
return new Object[][]{
{TestLockMode.PESSIMISTIC},
{TestLockMode.OPTIMISTIC}
};
}
@Test(dataProvider = "long-tx-test")
public void testLongTx(LongTxTestParameter testParameter) throws Exception {
String cacheName = testParameter.cacheName();
defineConfigurationOnAllManagers(cacheName, testParameter.config());
AdvancedCache<MagicKey, String> cache = this.<MagicKey, String>cache(0, cacheName).getAdvancedCache();
AdvancedCache<MagicKey, String> owner = this.<MagicKey, String>cache(1, cacheName).getAdvancedCache();
TransactionTable ownerTxTable = owner.getComponentRegistry().getTransactionTable();
TransactionTable cacheTxTable = cache.getComponentRegistry().getTransactionTable();
Method cleanupMethod = extractCleanupMethod();
final MagicKey key = new MagicKey("key", owner);
EmbeddedTransactionManager tm = (EmbeddedTransactionManager) cache.getTransactionManager();
tm.begin();
cache.put(key, "a");
testParameter.beforeAdvanceTime(tm);
//get the local gtx. should be the same as remote
GlobalTransaction gtx = cacheTxTable.getGlobalTransaction(tm.getTransaction());
assertTrue("RemoteTransaction must exists after key is locked!", ownerTxTable.containRemoteTx(gtx));
//completedTxTimeout is 10'000 ms. we advance 11'000
timeService.advance(COMPLETED_TX_TIMEOUT + 1000);
//check if the remote-tx is eligible for timeout
RemoteTransaction rtx = ownerTxTable.getRemoteTransaction(gtx);
assertNotNull("RemoteTransaction must exists after key is locked!", rtx);
assertTrue("RemoteTransaction is not eligible for timeout.", rtx.getCreationTime() - getCreationTimeCutoff() < 0);
//instead of waiting for the reaper, invoke the method directly
cleanupMethod.invoke(ownerTxTable);
//it should keep the tx
assertTrue("RemoteTransaction should be live after cleanup.", ownerTxTable.containRemoteTx(gtx));
testParameter.afterAdvanceTime(tm);
assertEquals("Wrong value in originator", "a", cache.get(key));
assertEquals("Wrong value in owner", "a", owner.get(key));
}
public void testCheckTransactionRpcCommand() throws Exception {
//default cache is transactional
Cache<String, String> cache0 = cache(0);
Cache<String, String> cache1 = cache(1);
CommandsFactory factory = cache0.getAdvancedCache().getComponentRegistry().getCommandsFactory();
RpcManager rpcManager = cache0.getAdvancedCache().getRpcManager();
RpcOptions rpcOptions = rpcManager.getSyncRpcOptions();
ResponseCollector<Collection<GlobalTransaction>> collector = CheckTransactionRpcCommand.responseCollector();
Address remoteAddress = cache1.getAdvancedCache().getRpcManager().getAddress();
TransactionTable transactionTable = cache1.getAdvancedCache().getComponentRegistry().getTransactionTable();
CheckTransactionRpcCommand rpcCommand = factory.buildCheckTransactionRpcCommand(Collections.emptyList());
Collection<GlobalTransaction> result = rpcManager.invokeCommand(remoteAddress, rpcCommand, collector, rpcOptions)
.toCompletableFuture()
.join();
assertTrue("Expected an empty collection but got: " + result, result.isEmpty());
TransactionManager tm = cache1.getAdvancedCache().getTransactionManager();
tm.begin();
cache1.put("k", "v");
rpcCommand = factory.buildCheckTransactionRpcCommand(transactionTable.getLocalGlobalTransaction());
result = rpcManager.invokeCommand(remoteAddress, rpcCommand, collector, rpcOptions)
.toCompletableFuture()
.join();
assertTrue("Expected an empty collection but got: " + result, result.isEmpty());
tm.commit();
GlobalTransaction nonExistingGtx = new GlobalTransaction(remoteAddress, false);
nonExistingGtx.setId(-1);
Collection<GlobalTransaction> list = Collections.singletonList(nonExistingGtx);
rpcCommand = factory.buildCheckTransactionRpcCommand(list);
result = rpcManager.invokeCommand(remoteAddress, rpcCommand, collector, rpcOptions)
.toCompletableFuture()
.join();
assertEquals("Wrong list returned.", list, result);
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
createClusteredCaches(2, TestDataSCI.INSTANCE, builder);
timeService = new ControlledTimeService();
for (EmbeddedCacheManager cm : cacheManagers) {
replaceComponent(cm, TimeService.class, timeService, true);
}
}
private long getCreationTimeCutoff() {
//copied from TransactionTable
long beginning = timeService.time();
return beginning - TimeUnit.MILLISECONDS.toNanos(COMPLETED_TX_TIMEOUT);
}
private enum TestLockMode implements LongTxTestParameter {
PESSIMISTIC {
@Override
public String cacheName() {
return "p_cache";
}
@Override
public ConfigurationBuilder config() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
builder.transaction()
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.lockingMode(LockingMode.PESSIMISTIC)
.completedTxTimeout(COMPLETED_TX_TIMEOUT);
return builder;
}
@Override
public void beforeAdvanceTime(EmbeddedTransactionManager tm) {
//no-op
}
@Override
public void afterAdvanceTime(EmbeddedTransactionManager tm) throws Exception {
tm.commit();
}
},
OPTIMISTIC {
@Override
public String cacheName() {
return "o_cache";
}
@Override
public ConfigurationBuilder config() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
builder.transaction()
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.lockingMode(LockingMode.OPTIMISTIC)
.completedTxTimeout(COMPLETED_TX_TIMEOUT);
return builder;
}
@Override
public void beforeAdvanceTime(EmbeddedTransactionManager tm) {
tm.getTransaction().runPrepare();
}
@Override
public void afterAdvanceTime(EmbeddedTransactionManager tm) throws Exception {
tm.getTransaction().runCommit(false);
EmbeddedTransactionManager.dissociateTransaction();
}
}
}
private interface LongTxTestParameter {
String cacheName();
ConfigurationBuilder config();
void beforeAdvanceTime(EmbeddedTransactionManager tm);
void afterAdvanceTime(EmbeddedTransactionManager tm) throws Exception;
}
}
| 9,410
| 38.2125
| 120
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/MarkAsRollbackTest.java
|
package org.infinispan.tx;
import static org.infinispan.commons.test.Exceptions.expectException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.TransactionManager;
import org.infinispan.commons.CacheException;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "tx.MarkAsRollbackTest")
public class MarkAsRollbackTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(getDefaultStandaloneCacheConfig(true));
cache = cm.getCache();
return cm;
}
public void testMarkAsRollbackAfterMods() throws Exception {
TransactionManager tm = TestingUtil.getTransactionManager(cache);
assert tm != null;
tm.begin();
cache.put("k", "v");
assert cache.get("k").equals("v");
tm.setRollbackOnly();
expectException(RollbackException.class, () -> tm.commit());
assert tm.getTransaction() == null : "There should be no transaction in scope anymore!";
assert cache.get("k") == null : "Expected a null but was " + cache.get("k");
}
public void testMarkAsRollbackBeforeMods() throws Exception {
TransactionManager tm = TestingUtil.getTransactionManager(cache);
assert tm != null;
tm.begin();
tm.setRollbackOnly();
expectException(CacheException.class, IllegalStateException.class, () -> cache.put("k", "v"));
expectException(RollbackException.class, () -> tm.commit());
assert tm.getTransaction() == null : "There should be no transaction in scope anymore!";
assert cache.get("k") == null : "Expected a null but was " + cache.get("k");
}
}
| 1,950
| 37.254902
| 114
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/InfinispanNodeFailureTest.java
|
package org.infinispan.tx;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.distribution.MagicKey;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.transport.DelayedViewJGroupsTransport;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.infinispan.test.TestingUtil.waitForNoRebalance;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
/**
* This test reproduces following scenario in Infinispan:
* <pre>
* NODE-A NODE-B NODE-C
*
* 1:start-tx
* 1:replace key X
* 1:lock X (A is owner)
* 1:put key Z
* 1:lock Z (B is owner)
* kill node C
* 1:get response from lock Z
* 1:release ALL locks (!)
* new view is received
* 1:retry lock Z
* 1:lock Z (B is owner)
* 2:start-tx
* 2:replace key X
* 2:lock X (A is owner)
* 2:commit-tx
* 1:commit-tx
*
* The problematic part is marked with exclamation, PessimisticLockingInterceptor releases ALL locks and retries just
* one last command, which puts
* current transaction in invalid state, when client thinks first operation protects second operation with a lock, but
* this is not the case.
* </pre>
*
* @since 9.0
*/
@Test(groups = "functional", testName = "tx.InfinispanNodeFailureTest")
public class InfinispanNodeFailureTest extends MultipleCacheManagersTest {
private static final Integer INITIAL_VALUE = 0;
private static final Integer REPLACING_VALUE = 1;
private static final String TEST_CACHE = "test_cache";
private CompletableFuture<Void> viewLatch;
public void killedNodeDoesNotBreakReplaceCommand() throws Exception {
defineConfigurationOnAllManagers(TEST_CACHE, new ConfigurationBuilder().read(manager(0).getDefaultCacheConfiguration(), Combine.DEFAULT));
waitForClusterToForm(TEST_CACHE);
waitForNoRebalance(caches(TEST_CACHE));
final Object replaceKey = new MagicKey("X", cache(0, TEST_CACHE));
final Object putKey = new MagicKey("Z", cache(1, TEST_CACHE));
cache(0, TEST_CACHE).put(replaceKey, INITIAL_VALUE);
// prepare third node to notify us when put command is in progress so we can kill the node
final CountDownLatch beforeKill = new CountDownLatch(1);
final CountDownLatch afterKill = new CountDownLatch(1);
advancedCache(1, TEST_CACHE).getAsyncInterceptorChain().addInterceptor(new BaseCustomAsyncInterceptor() {
@Override
public Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) throws Throwable {
return invokeNextAndFinally(ctx, command, (rCtx, rCommand, rv, t) -> {
LockControlCommand cmd = (LockControlCommand) rCommand;
if (putKey.equals(cmd.getSingleKey())) {
// notify main thread it can start killing third node
beforeKill.countDown();
// wait for completion and proceed
afterKill.await(10, TimeUnit.SECONDS);
}
});
}
}, 1);
// execute replace command in separate thread so we can do something else meanwhile
Future<Boolean> firstResult = fork(() -> {
try {
tm(0, TEST_CACHE).begin();
// this should replace and lock REPLACE_KEY so other transactions can't pass this barrier
boolean result = cache(0, TEST_CACHE).replace(replaceKey, INITIAL_VALUE, REPLACING_VALUE);
// issue put command so it is retried while node-c is being killed
cache(0, TEST_CACHE).put(putKey, "some-value");
// apply new view
viewLatch.complete(null);
tm(0, TEST_CACHE).commit();
return result;
} catch (Throwable t) {
return null;
}
});
// wait third node to complete replace command and kill it
assertTrue(beforeKill.await(10, TimeUnit.SECONDS));
// kill node-c, do not wait rehash, it is important to continue with put-retry before new view is received
killMember(2, TEST_CACHE, false);
afterKill.countDown();
tm(1, TEST_CACHE).begin();
// this replace should never succeed because first node has already replaced and locked value
// but during put command replace lock is lost, so we can successfully replace the same value again, which is a bug
boolean secondResult = cache(1, TEST_CACHE).replace(replaceKey, INITIAL_VALUE, REPLACING_VALUE);
tm(1, TEST_CACHE).commit();
// check that first node did not fail
assertEquals(Boolean.TRUE, firstResult.get());
assertEquals(REPLACING_VALUE, cache(0, TEST_CACHE).get(replaceKey));
assertEquals(REPLACING_VALUE, cache(1, TEST_CACHE).get(replaceKey));
// check that second node state is inconsistent, second result should be FALSE in read committed pessimistic cache
// uncomment when this bug is fixed
assertEquals(false, secondResult);
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder configuration = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true);
configuration.locking()
.useLockStriping(false)
.isolationLevel(IsolationLevel.READ_COMMITTED)
.lockAcquisitionTimeout(20000);
configuration.transaction()
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.lockingMode(LockingMode.PESSIMISTIC)
.useSynchronization(false)
.recovery()
.disable();
configuration.clustering()
.hash()
.numSegments(60)
.stateTransfer()
.fetchInMemoryState(false);
viewLatch = new CompletableFuture<>();
GlobalConfigurationBuilder global = new GlobalConfigurationBuilder();
global.transport().transport(new DelayedViewJGroupsTransport(viewLatch));
global.serialization().addContextInitializer(TestDataSCI.INSTANCE);
addClusterEnabledCacheManager(global, configuration);
createCluster(TestDataSCI.INSTANCE, configuration, 2);
}
}
| 7,093
| 41.479042
| 144
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TransactionsSpanningReplicatedCachesTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Arrays;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.remoting.rpc.RpcManagerImpl;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
@Test(groups = {"functional", "smoke"}, testName = "tx.TransactionsSpanningReplicatedCachesTest")
public class TransactionsSpanningReplicatedCachesTest extends MultipleCacheManagersTest {
public TransactionsSpanningReplicatedCachesTest() {
cleanup = CleanupPhase.AFTER_METHOD;
}
@Override
protected void createCacheManagers() throws Exception {
ConfigurationBuilder c = getConfiguration();
addClusterEnabledCacheManager(c);
addClusterEnabledCacheManager(c);
defineConfigurationOnAllManagers("c1", c);
defineConfigurationOnAllManagers("c2", c);
defineConfigurationOnAllManagers("cache1", c);
defineConfigurationOnAllManagers("cache2", c);
//internally calls m.getCache(c1) which starts he cache
waitForClusterToForm("c1", "c2", "cache1", "cache2", getDefaultCacheName());
}
protected ConfigurationBuilder getConfiguration() {
ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true);
c.statistics().enable();
return c;
}
public void testReadOnlyTransaction() throws Exception {
Cache<String, String> c1 = cache(0);
Cache<String, String> c2 = cache(1);
RpcManagerImpl ri = (RpcManagerImpl) c1.getAdvancedCache().getRpcManager();
c1.put("k", "v");
assertEquals("v", c1.get("k"));
assertEquals("v", c2.get("k"));
long oldRC = ri.getReplicationCount();
c1.getAdvancedCache().getTransactionManager().begin();
assertEquals("v", c1.get("k"));
c1.getAdvancedCache().getTransactionManager().commit();
assertEquals(ri.getReplicationCount(), oldRC);
}
public void testCommitSpanningCaches() throws Exception {
Cache<String, String> c1 = cache(0, "c1");
Cache<String, String> c1Replica = cache(1, "c1");
Cache<String, String> c2 = cache(0, "c2");
Cache<String, String> c2Replica = cache(1, "c2");
assertTrue(c1.isEmpty());
assertTrue(c2.isEmpty());
assertTrue(c1Replica.isEmpty());
assertTrue(c2Replica.isEmpty());
c1.put("c1key", "c1value");
c2.put("c2key", "c2value");
assertInitialValues(c1, c1Replica, c2, c2Replica);
TransactionManager tm = TestingUtil.getTransactionManager(c1);
tm.begin();
c1.put("c1key", "c1value_new");
c2.put("c2key", "c2value_new");
assertEquals(c1.get("c1key"), "c1value_new");
assertEquals(c1Replica.get("c1key"), "c1value");
assertEquals(c2.get("c2key"), "c2value_new");
assertEquals(c2Replica.get("c2key"), "c2value");
Transaction tx = tm.suspend();
assertInitialValues(c1, c1Replica, c2, c2Replica);
tm.resume(tx);
log.trace("before commit...");
tm.commit();
assertEquals(c1.get("c1key"), "c1value_new");
assertEquals(c1Replica.get("c1key"), "c1value_new");
assertEquals(c2.get("c2key"), "c2value_new");
assertEquals(c2Replica.get("c2key"), "c2value_new");
}
public void testRollbackSpanningCaches() throws Exception {
Cache<String, String> c1 = cache(0, "c1");
Cache<String, String> c1Replica = cache(1, "c1");
Cache<String, String> c2 = cache(0, "c2");
Cache<String, String> c2Replica = cache(1, "c2");
assertTrue(c1.isEmpty());
assertTrue(c2.isEmpty());
assertTrue(c1Replica.isEmpty());
assertTrue(c2Replica.isEmpty());
c1.put("c1key", "c1value");
c2.put("c2key", "c2value");
assertInitialValues(c1, c1Replica, c2, c2Replica);
TransactionManager tm = TestingUtil.getTransactionManager(c1);
tm.begin();
c1.put("c1key", "c1value_new");
c2.put("c2key", "c2value_new");
assertEquals(c1.get("c1key"), "c1value_new");
assertEquals(c1Replica.get("c1key"), "c1value");
assertEquals(c2.get("c2key"), "c2value_new");
assertEquals(c2Replica.get("c2key"), "c2value");
Transaction tx = tm.suspend();
assertEquals(c1.get("c1key"), "c1value");
assertEquals(c1Replica.get("c1key"), "c1value");
assertEquals(c2.get("c2key"), "c2value");
assertEquals(c2Replica.get("c2key"), "c2value");
tm.resume(tx);
tm.rollback();
assertEquals(c1.get("c1key"), "c1value");
assertEquals(c1Replica.get("c1key"), "c1value");
assertEquals(c2.get("c2key"), "c2value");
assertEquals("c2value", c2Replica.get("c2key"));
}
private void assertInitialValues(Cache<String, String> c1, Cache<String, String> c1Replica, Cache<String, String> c2, Cache<String, String> c2Replica) {
for (Cache<String, String> c : Arrays.asList(c1, c1Replica)) {
assertEquals(c.size(), 1);
assertEquals(c.get("c1key"), "c1value");
}
for (Cache<String, String> c : Arrays.asList(c2, c2Replica)) {
assertEquals(c.size(), 1);
assertEquals(c.get("c2key"), "c2value");
}
}
public void testRollbackSpanningCaches2() throws Exception {
Cache<String, String> c1 = cache(0, "c1");
assertTrue(c1.getCacheConfiguration().clustering().cacheMode().isClustered());
Cache<String, String> c1Replica = cache(1, "c1");
assertTrue(c1.isEmpty());
assertTrue(c1Replica.isEmpty());
c1.put("c1key", "c1value");
assertEquals(c1.get("c1key"), "c1value");
assertEquals(c1Replica.get("c1key"), "c1value");
}
public void testSimpleCommit() throws Exception {
Cache<String, String> c1 = cache(0, "c1");
Cache<String, String> c1Replica = cache(1, "c1");
assertTrue(c1.isEmpty());
assertTrue(c1Replica.isEmpty());
TransactionManager tm = TestingUtil.getTransactionManager(c1);
tm.begin();
c1.put("c1key", "c1value");
tm.commit();
assertEquals(c1.get("c1key"), "c1value");
assertEquals(c1Replica.get("c1key"), "c1value");
}
public void testPutIfAbsent() throws Exception {
Cache<String, String> c1 = cache(0, "c1");
Cache<String, String> c1Replica = cache(1, "c1");
assertTrue(c1.isEmpty());
assertTrue(c1Replica.isEmpty());
TransactionManager tm = TestingUtil.getTransactionManager(c1);
tm.begin();
c1.put("c1key", "c1value");
tm.commit();
assertEquals(c1.get("c1key"), "c1value");
assertEquals(c1Replica.get("c1key"), "c1value");
tm.begin();
c1.putIfAbsent("c1key", "SHOULD_NOT_GET_INSERTED");
tm.commit();
assertEquals(c1.get("c1key"), "c1value");
assertEquals(c1Replica.get("c1key"), "c1value");
}
public void testTwoNamedCachesSameNode() throws Exception {
runTest(cache(0, "cache1"), cache(0, "cache2"));
}
public void testDefaultCacheAndNamedCacheSameNode() throws Exception {
runTest(cache(0), cache(0, "cache1"));
}
public void testTwoNamedCachesDifferentNodes() throws Exception {
runTest(cache(0, "cache1"), cache(1, "cache2"));
}
public void testDefaultCacheAndNamedCacheDifferentNodes() throws Exception {
runTest(cache(0), cache(1, "cache1"));
}
private void runTest(Cache<String, String> cache1, Cache<String, String> cache2) throws Exception {
assertFalse(cache1.containsKey("a"));
assertFalse(cache2.containsKey("b"));
TransactionManager tm = TestingUtil.getTransactionManager(cache1);
tm.begin();
cache1.put("a", "value1");
cache2.put("b", "value2");
tm.commit();
assertEquals("value1", cache1.get("a"));
assertEquals("value2", cache2.get("b"));
tm.begin();
cache1.remove("a");
cache2.remove("b");
tm.commit();
assertFalse(cache1.containsKey("a"));
assertFalse(cache2.containsKey("b"));
}
}
| 8,300
| 31.425781
| 155
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TerminatedCacheWhileInTxTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.k;
import static org.infinispan.test.TestingUtil.v;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import java.lang.reflect.Method;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
/**
* Test that verifies that Cache.stop() waits for on-going transactions to
* finish before making the cache unavailable.
*
* Also verifies that new transactions started while the cache is stopping
* are not accepted.
*
* @author Galder Zamarreño
* @author Dan Berindei
* @since 4.2
*/
@Test(groups = "functional", testName = "tx.TerminatedCacheWhileInTxTest")
public class TerminatedCacheWhileInTxTest extends SingleCacheManagerTest {
protected StorageType storage;
@Factory
public Object[] factory() {
return new Object[] {
new TerminatedCacheWhileInTxTest().withStorage(StorageType.BINARY),
new TerminatedCacheWhileInTxTest().withStorage(StorageType.OBJECT),
new TerminatedCacheWhileInTxTest().withStorage(StorageType.OFF_HEAP)
};
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder c = TestCacheManagerFactory.getDefaultCacheConfiguration(true);
c.transaction().cacheStopTimeout(10000);
c.memory().storageType(storage);
return TestCacheManagerFactory.createCacheManager(c);
}
public TerminatedCacheWhileInTxTest withStorage(StorageType storage) {
this.storage = storage;
return this;
}
@Override
protected String parameters() {
return "[storage=" + storage + "]";
}
/**
* The aim of this test is to make sure that invocations not belonging to
* on-going transactions or non-transactional invocations are not allowed
* once the cache is in stopping mode.
*/
public void testNotAllowCallsWhileStopping(final Method m) throws Throwable {
cacheManager.defineConfiguration("cache-" + m.getName(), cacheManager.getDefaultCacheConfiguration());
final Cache<String, String> cache1 = cacheManager.getCache("cache-" + m.getName());
final CyclicBarrier barrier = new CyclicBarrier(2);
final CountDownLatch latch = new CountDownLatch(1);
final TransactionManager tm = TestingUtil.getTransactionManager(cache1);
Future<Void> waitAfterModFuture = fork(() -> {
log.debug("Wait for all executions paths to be ready to perform calls.");
tm.begin();
cache1.put(k(m, 1), v(m, 1));
log.debug("Cache modified, wait for cache to be stopped.");
barrier.await();
// Delay the commit, but it must still happen while cache.stop() is waiting for transactions
assertFalse(latch.await(5, TimeUnit.SECONDS));
tm.commit();
return null;
});
// wait for the transaction to have started
barrier.await();
Future<Void> callStoppingCacheFuture = fork(() -> {
log.debug("Wait very briefly and then make call.");
Thread.sleep(2000);
cache1.put(k(m, 2), v(m, 2));
return null;
});
cache1.stop(); // now stop the cache
latch.countDown(); // now that cache has been stopped, let the thread continue
waitAfterModFuture.get();
try {
callStoppingCacheFuture.get();
fail("Should have thrown an IllegalLifecycleStateException");
} catch (ExecutionException e) {
assertTrue(e.toString(), e.getCause() instanceof IllegalLifecycleStateException);
}
}
}
| 4,324
| 35.652542
| 108
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/OptimisticReadOnlyTxTest.java
|
package org.infinispan.tx;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
/**
* @author Pedro Ruivo
* @since 6.0
*/
@Test(groups = "functional", testName = "tx.OptimisticReadOnlyTxTest")
@CleanupAfterMethod
public class OptimisticReadOnlyTxTest extends ReadOnlyTxTest {
@Override
public void testROWhenHasOnlyLocksAndReleasedProperly() throws Exception {
//no-op. not valid for optimistic transactions
}
@Override
public void testNotROWhenHasWrites() throws Exception {
//no-op. not valid for optimistic transactions
}
@Override
protected void configure(ConfigurationBuilder builder) {
super.configure(builder);
builder.transaction().lockingMode(LockingMode.OPTIMISTIC);
}
@Override
protected int numberCommitCommand() {
//with optimistic locking, the transactions are committed in 2 phases. So 1 CommitCommand is expected
return 1;
}
}
| 1,069
| 27.157895
| 107
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/ContextAffectsTransactionRepeatableReadTest.java
|
package org.infinispan.tx;
import jakarta.transaction.RollbackException;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
/**
* This test is to ensure that values in the context are properly counted for various cache operations
*
* @author wburns
* @since 6.0
*/
@Test (groups = "functional", testName = "tx.ContextAffectsTransactionRepeatableReadTest")
public class ContextAffectsTransactionRepeatableReadTest extends ContextAffectsTransactionReadCommittedTest {
@Factory
public Object[] factory() {
return new Object[] {
new ContextAffectsTransactionRepeatableReadTest().withStorage(StorageType.BINARY),
new ContextAffectsTransactionRepeatableReadTest().withStorage(StorageType.OBJECT),
new ContextAffectsTransactionRepeatableReadTest().withStorage(StorageType.OFF_HEAP)
};
}
@Override
protected void configure(ConfigurationBuilder builder) {
builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
}
@Override
protected void safeCommit(boolean throwWriteSkew) throws Exception {
if (throwWriteSkew) {
Exceptions.expectException(RollbackException.class, tm()::commit);
} else {
tm().commit();
}
}
}
| 1,484
| 33.534884
| 109
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/ExceptionDuringGetTest.java
|
package org.infinispan.tx;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.interceptors.locking.PessimisticLockingInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
/**
* @author Mircea Markus <mircea.markus@jboss.com> (C) 2011 Red Hat Inc.
* @since 5.1
*/
@Test (groups = "functional", testName = "tx.ExceptionDuringGetTest")
public class ExceptionDuringGetTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
dcc.transaction().lockingMode(LockingMode.PESSIMISTIC);
createCluster(dcc, 2);
waitForClusterToForm();
cache(0).put("k", "v");
assert cache(1).get("k").equals("v");
}
@Test(expectedExceptions = CacheException.class, expectedExceptionsMessageRegExp = "Induced!")
public void testExceptionDuringGet() {
advancedCache(0).getAsyncInterceptorChain().addInterceptorAfter(new ExceptionInterceptor(), PessimisticLockingInterceptor.class);
cache(0).get("k");
assert false;
}
static class ExceptionInterceptor extends BaseAsyncInterceptor {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
throw new RuntimeException("Induced!");
}
}
}
| 1,743
| 37.755556
| 135
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/ReadOnlyTxCleanupTest.java
|
package org.infinispan.tx;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.impl.TransactionTable;
import org.testng.annotations.Test;
@Test(testName = "tx.ReadOnlyTxCleanupTest", groups = "functional")
@CleanupAfterMethod
public class ReadOnlyTxCleanupTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder c = TestCacheManagerFactory.getDefaultCacheConfiguration(true);
return TestCacheManagerFactory.createCacheManager(c);
}
public void testReadOnlyTx() throws SystemException, RollbackException, HeuristicRollbackException, HeuristicMixedException, NotSupportedException {
Cache<String, String> c1 = cacheManager.getCache();
cacheManager.defineConfiguration("two", cacheManager.getDefaultCacheConfiguration());
Cache<String, String> c2 = cacheManager.getCache("two");
c1.put("c1", "c1");
c2.put("c2", "c2");
TransactionManager tm1 = tm();
tm1.begin();
c1.get("c1");
c2.get("c2");
tm1.commit();
TransactionTable tt1 = TestingUtil.extractComponent(c1, TransactionTable.class);
TransactionTable tt2 = TestingUtil.extractComponent(c2, TransactionTable.class);
assert tt1.getLocalTxCount() == 0;
assert tt2.getLocalTxCount() == 0;
}
}
| 1,961
| 37.470588
| 151
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/NoRpcOnReadonlyTransactionsTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.testng.AssertJUnit.assertEquals;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.org
* @since 5.2
*/
@Test(groups = "functional", testName = "tx.NoRpcOnReadonlyTransactionsTest")
@CleanupAfterMethod
public class NoRpcOnReadonlyTransactionsTest extends MultipleCacheManagersTest {
private TxCheckInterceptor i0;
private TxCheckInterceptor i2;
private TxCheckInterceptor i1;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder config = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
config.clustering().hash().numOwners(1);
createCluster(TestDataSCI.INSTANCE, config, 3);
waitForClusterToForm();
i0 = new TxCheckInterceptor();
i1 = new TxCheckInterceptor();
i2 = new TxCheckInterceptor();
extractInterceptorChain(advancedCache(0)).addInterceptor(i0, 1);
extractInterceptorChain(advancedCache(1)).addInterceptor(i1, 1);
extractInterceptorChain(advancedCache(2)).addInterceptor(i2, 1);
}
public void testReadOnlyTxNoNetworkCallAtCommit() throws Exception {
Object k0 = getKeyForCache(0);
log.tracef("On address %s adding key %s", address(0), k0);
cache(0).put(k0, "v");
assertEquals(0, i0.remotePrepares);
assertEquals(0, i0.remoteCommits);
assertEquals(0, i1.remotePrepares);
assertEquals(0, i1.remoteCommits);
assertEquals(0, i2.remotePrepares);
assertEquals(0, i2.remoteCommits);
log.trace("Here is where the r-o tx happens.");
tm(1).begin();
assertEquals("v", cache(1).get(k0));
tm(1).commit();
assertEquals(0, i0.remotePrepares);
assertEquals(0, i0.remoteCommits);
assertEquals(0, i1.remotePrepares);
assertEquals(0, i1.remoteCommits);
assertEquals(0, i2.remotePrepares);
assertEquals(0, i2.remoteCommits);
tm(1).begin();
cache(1).put(getKeyForCache(2), "v");
assertEquals("v", cache(1).get(k0));
tm(1).commit();
assertEquals(0, i0.remotePrepares);
assertEquals(0, i0.remoteCommits);
assertEquals(0, i1.remotePrepares);
assertEquals(0, i1.remoteCommits);
assertEquals(1, i2.remotePrepares);
assertEquals(1, i2.remoteCommits);
}
public void testReadOnlyTxNoNetworkCallMultipleCaches() throws Exception {
defineConfigurationOnAllManagers("a", new ConfigurationBuilder().read(manager(0).getDefaultCacheConfiguration(), Combine.DEFAULT));
cache(0, "a");
cache(1, "a");
cache(2, "a");
waitForClusterToForm("a");
cache(0, "a").put("k", "v");
assertEquals(0, i0.remotePrepares);
assertEquals(0, i0.remoteCommits);
assertEquals(0, i1.remotePrepares);
assertEquals(0, i1.remoteCommits);
assertEquals(0, i2.remotePrepares);
assertEquals(0, i2.remoteCommits);
assertEquals("v", cache(0, "a").get("k"));
assertEquals("v", cache(1, "a").get("k"));
assertEquals("v", cache(2, "a").get("k"));
Object k0 = getKeyForCache(0);
cache(0).put(k0, "v0");
Object k1 = getKeyForCache(1);
cache(1).put(k1, "v0");
Object k2 = getKeyForCache(2);
cache(2).put(k2, "v0");
tm(1).begin();
assertEquals("v", cache(1, "a").put("k", "v2"));
assertEquals("v0", cache(1).get(k0));
assertEquals("v0", cache(1).get(k1));
assertEquals("v0", cache(1).get(k2));
tm(1).commit();
assertEquals(0, i0.remotePrepares);
assertEquals(0, i0.remoteCommits);
assertEquals(0, i1.remotePrepares);
assertEquals(0, i1.remoteCommits);
assertEquals(0, i2.remotePrepares);
assertEquals(0, i2.remoteCommits);
assertEquals("v2", cache(0, "a").get("k"));
assertEquals("v2", cache(1, "a").get("k"));
assertEquals("v2", cache(2, "a").get("k"));
}
static class TxCheckInterceptor extends DDAsyncInterceptor {
private volatile int remotePrepares;
private volatile int remoteCommits;
@Override
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable {
if (!ctx.isOriginLocal()) remotePrepares++;
return super.visitPrepareCommand(ctx, command);
}
@Override
public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable {
if (!ctx.isOriginLocal()) remoteCommits++;
return super.visitCommitCommand(ctx, command);
}
void reset() {
remotePrepares = remoteCommits = 0;
}
}
}
| 5,210
| 34.44898
| 137
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/FailureWith1PCTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.testng.Assert.assertNull;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
/**
* Test for https://issues.jboss.org/browse/ISPN-1093.
* @author Mircea Markus
*/
@Test (groups = "functional", testName = "tx.FailureWith1PCTest")
public class FailureWith1PCTest extends MultipleCacheManagersTest {
boolean fail = true;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
c.clustering().hash().numOwners(3);
createCluster(c, 3);
waitForClusterToForm();
}
public void testInducedFailureOn1pc() throws Exception {
extractInterceptorChain(cache(1)).addInterceptor(new FailInterceptor(), 1);
tm(0).begin();
cache(0).put("k", "v");
try {
tm(0).commit();
assert false : "Exception expected";
} catch (Exception e) {
log.debug("Ignoring expected exception during 1-phase prepare", e);
}
fail = false;
assertExpectedState(0);
assertExpectedState(1);
assertExpectedState(2);
}
private void assertExpectedState(int index) {
assertNull(cache(index).get("k"));
assert !lockManager(index).isLocked("k");
assert TestingUtil.getTransactionTable(cache(index)).getLocalTxCount() == 0;
assert TestingUtil.getTransactionTable(cache(index)).getRemoteTxCount() == 0;
}
class FailInterceptor extends DDAsyncInterceptor {
@Override
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable {
if (fail)
throw new RuntimeException("Induced exception");
else
return invokeNext(ctx, command);
}
}
}
| 2,224
| 30.338028
| 107
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/LockCleanupStateTransferTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand;
import org.infinispan.commands.tx.VersionedCommitCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.DataContainer;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.mocks.ControlledCommandFactory;
import org.testng.annotations.Test;
/**
* test:
* - N1 starts a tx with 10 keys that map to the second node and prepares it
* - N3 is started and (hopefully) some of the keys touched by the transaction should be migrated over to N3
* - the transaction is finalized. The test makes sure that:
* - no data is lost during ST
* - the transaction is cleaned up correctly from all nodes
*
* @author Mircea Markus
* @since 5.2
*/
@Test (groups = "functional", testName = "tx.LockCleanupStateTransferTest")
@CleanupAfterMethod
public class LockCleanupStateTransferTest extends MultipleCacheManagersTest {
private static final int KEY_SET_SIZE = 10;
private ConfigurationBuilder dcc;
@Override
protected void createCacheManagers() throws Throwable {
dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
dcc.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup());
dcc.clustering().hash().numOwners(1);
dcc.clustering().stateTransfer().fetchInMemoryState(true);
createCluster(TestDataSCI.INSTANCE, dcc, 2);
waitForClusterToForm();
}
public void testBelatedCommit() throws Throwable {
testLockReleasedCorrectly(VersionedCommitCommand.class);
}
public void testBelatedTxCompletionNotificationCommand() throws Throwable {
testLockReleasedCorrectly(TxCompletionNotificationCommand.class);
}
private void testLockReleasedCorrectly(Class<? extends ReplicableCommand> toBlock ) throws Throwable {
final ControlledCommandFactory ccf = ControlledCommandFactory.registerControlledCommandFactory(advancedCache(1), toBlock);
ccf.gate.close();
final Set<Object> keys = new HashSet<>(KEY_SET_SIZE);
//fork it into another test as this is going to block in commit
Future<Object> future = fork(() -> {
tm(0).begin();
for (int i = 0; i < KEY_SET_SIZE; i++) {
Object k = getKeyForCache(1);
keys.add(k);
cache(0).put(k, k);
}
tm(0).commit();
return null;
});
//now wait for all the commits to block
eventuallyEquals(1, ccf.blockTypeCommandsReceived::get);
if (toBlock == TxCompletionNotificationCommand.class) {
//at this stage everything should be committed locally
DataContainer dc = advancedCache(1).getDataContainer();
for (Object k : keys) {
assertEquals(k, dc.get(k).getValue());
}
}
log.trace("Before state transfer");
//now add a one new member
addClusterEnabledCacheManager(TestDataSCI.INSTANCE, dcc);
waitForClusterToForm();
log.trace("After state transfer");
final Set<Object> migratedKeys = new HashSet<>(KEY_SET_SIZE);
for (Object key : keys) {
if (keyMapsToNode(key)) {
migratedKeys.add(key);
}
}
log.tracef("Number of migrated keys is %s", migratedKeys.size());
if (migratedKeys.size() == 0) return;
eventuallyEquals(1, () -> TestingUtil.getTransactionTable(cache(2)).getRemoteTxCount());
log.trace("Releasing the gate");
ccf.gate.open();
// wait for the forked thread to finish its transaction
future.get(10, TimeUnit.SECONDS);
for (int i = 0; i < 3; i++) {
TransactionTable tt = TestingUtil.getTransactionTable(cache(i));
assertEquals("For cache " + i, 0, tt.getLocalTxCount());
}
// the tx completion is async, so we need to wait a little more
eventually(() -> {
boolean success = true;
for (int i = 0; i < 3; i++) {
TransactionTable tt = TestingUtil.getTransactionTable(cache(i));
int remoteTxCount = tt.getRemoteTxCount();
log.tracef("For cache %s, remoteTxCount==%d", cache(i), remoteTxCount);
success &= remoteTxCount == 0;
}
return success;
});
for (Object key : keys) {
assertNotLocked(key);
assertEquals(key, cache(0).get(key));
}
for (Object k : migratedKeys) {
assertFalse(advancedCache(0).getDataContainer().containsKey(k));
assertFalse(advancedCache(1).getDataContainer().containsKey(k));
assertTrue(advancedCache(2).getDataContainer().containsKey(k));
}
}
private boolean keyMapsToNode(Object key) {
Address owner = owner(key);
return owner.equals(address(2));
}
private Address owner(Object key) {
return advancedCache(0).getDistributionManager().getCacheTopology().getDistribution(key).primary();
}
}
| 5,695
| 34.823899
| 128
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/ExplicitLockingMultipleKeyTest.java
|
package org.infinispan.tx;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test (groups = "functional", testName = "tx.ExplicitLockingMultipleKeyTest")
public class ExplicitLockingMultipleKeyTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
final ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
c.transaction().lockingMode(LockingMode.PESSIMISTIC);
createCluster(TestDataSCI.INSTANCE, c, 2);
waitForClusterToForm();
}
public void testAcquireRemoteLocks1() throws Exception {
runTest(0, 1);
}
public void testAcquireRemoteLocks2() throws Exception {
runTest(0, 0);
}
public void testAcquireRemoteLocks3() throws Exception {
runTest(1, 1);
}
public void testAcquireRemoteLocks4() throws Exception {
runTest(1, 0);
}
private void runTest(int lockOwner, int txOriginator) throws Exception {
Object k0_1 = getKeyForCache(lockOwner);
Object k0_2 = getKeyForCache(lockOwner);
tm(txOriginator).begin();
advancedCache(txOriginator).lock(k0_1, k0_2);
assertKeyLockedCorrectly(k0_1);
assertKeyLockedCorrectly(k0_2);
tm(txOriginator).commit();
assertNotLocked(k0_1);
assertNotLocked(k0_2);
}
}
| 1,618
| 29.54717
| 95
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/EntryWrappingInterceptorDoesNotBlockTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.fwk.TestCacheManagerFactory.createClusteredCacheManager;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Stream;
import jakarta.transaction.Transaction;
import org.infinispan.Cache;
import org.infinispan.commands.remote.BaseClusteredReadCommand;
import org.infinispan.commands.remote.ClusteredGetCommand;
import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand;
import org.infinispan.commands.statetransfer.StateResponseCommand;
import org.infinispan.commands.statetransfer.StateTransferGetTransactionsCommand;
import org.infinispan.commands.statetransfer.StateTransferStartCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.distribution.MagicKey;
import org.infinispan.functional.FunctionalMap;
import org.infinispan.functional.Traversable;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.interceptors.InvocationStage;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.TopologyChanged;
import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.fwk.TransportFlags;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.ControlledConsistentHashFactory;
import org.infinispan.util.ControlledRpcManager;
import org.infinispan.util.concurrent.TimeoutException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* We make node 2 a backup owner for segment 0, but we block state transfer so that it doesn't have any entries.
* We verify that when the prepare command is invoked remotely on node 2, a remote get is sent to nodes 0 and 1,
* and that the remote thread is not blocked while waiting for the remote get responses.
*/
@Test(groups = "functional", testName = "tx.EntryWrappingInterceptorDoesNotBlockTest")
@CleanupAfterMethod
public class EntryWrappingInterceptorDoesNotBlockTest extends MultipleCacheManagersTest {
private ConfigurationBuilder cb;
private ControlledConsistentHashFactory.Default chFactory;
private static class Operation {
final String name;
final BiFunction<MagicKey, Integer, Object> f;
private Operation(String name, BiFunction<MagicKey, Integer, Object> f) {
this.name = name;
this.f = f;
}
@Override
public String toString() {
return name;
}
}
@DataProvider(name = "operations")
public Object[][] operations() {
return Stream.of(
new Operation("readWriteKey", this::readWriteKey),
new Operation("readWriteKeyValue", this::readWriteKeyValue),
new Operation("readWriteMany", this::readWriteMany),
new Operation("readWriteManyEntries", this::readWriteManyEntries)
).map(f -> new Object[] { f }).toArray(Object[][]::new);
}
@Override
protected void createCacheManagers() throws Throwable {
chFactory = new ControlledConsistentHashFactory.Default(new int[][]{{0, 1}, {0, 2}});
cb = new ConfigurationBuilder();
cb.clustering().cacheMode(CacheMode.DIST_SYNC).hash().consistentHashFactory(chFactory).numSegments(2);
cb.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
createCluster(TestDataSCI.INSTANCE, cb, 3);
}
@Test(dataProvider = "operations")
public void testMovingStable(Operation operation) throws Exception {
test(1, operation.f, new MagicKey("moving", cache(0), cache(1)), new MagicKey("stable", cache(0), cache(2)));
}
@Test(dataProvider = "operations")
public void testStableMoving(Operation operation) throws Exception {
test(1, operation.f, new MagicKey("stable", cache(0), cache(2)), new MagicKey("moving", cache(0), cache(1)));
}
@Test(dataProvider = "operations")
public void testMovingMoving(Operation operation) throws Exception {
test(2, operation.f, new MagicKey("moving1", cache(0), cache(1)), new MagicKey("moving2", cache(0), cache(1)));
}
protected void test(int expectRemoteGets, BiFunction<MagicKey, Integer, Object> operation, MagicKey... keys) throws Exception {
ControlledRpcManager crm0 = ControlledRpcManager.replaceRpcManager(cache(0));
ControlledRpcManager crm2 = ControlledRpcManager.replaceRpcManager(cache(2));
CountDownLatch topologyChangeLatch = new CountDownLatch(2);
cache(0).addListener(new TopologyChangeListener(topologyChangeLatch));
cache(2).addListener(new TopologyChangeListener(topologyChangeLatch));
PrepareExpectingInterceptor prepareExpectingInterceptor = new PrepareExpectingInterceptor();
TestingUtil.extractInterceptorChain(cache(2)).addInterceptor(prepareExpectingInterceptor, 0);
tm(0).begin();
for (int i = 0; i < keys.length; ++i) {
Object returnValue = operation.apply(keys[i], i);
assertEquals("r" + i, returnValue);
}
// node 2 should become backup for both segment 0 (new) and segment 1 (already there)
chFactory.setOwnerIndexes(new int[][]{{0, 2}, {0, 2}});
EmbeddedCacheManager cm = createClusteredCacheManager(false, GlobalConfigurationBuilder.defaultClusteredBuilder(),
cb, new TransportFlags());
registerCacheManager(cm);
Future<?> newNode = fork(() -> cache(3));
// block sending segment 0 to node 2
crm2.expectCommand(StateTransferGetTransactionsCommand.class).send().receiveAll();
crm2.expectCommand(StateTransferStartCommand.class).send().receiveAllAsync();
ControlledRpcManager.BlockedRequest blockedStateResponse0 = crm0.expectCommand(StateResponseCommand.class);
assertTrue(topologyChangeLatch.await(10, TimeUnit.SECONDS));
Transaction transaction = tm(0).suspend();
Future<Void> commitFuture = fork(transaction::commit);
ControlledRpcManager.SentRequest sentPrepare = crm0.expectCommand(PrepareCommand.class).send();
// The PrepareCommand attempts to load moving keys, and we allow the request to be sent
// but block receiving the responses. Here we'll intercept only the first remote get because the second one
// is not fired until the first is received (implementation inefficiency).
ControlledRpcManager.SentRequest firstRemoteGet = crm2.expectCommand(BaseClusteredReadCommand.class).send();
// The topmost interceptor gets the InvocationStage from the PrepareCommand and verifies
// that it is not completed yet (as we are waiting for the remote gets). Receiving the invocation stage
// means that the stack is really non-blocking.
// If the remote get responses hadn't been blocked this verification would fail with assertion.
prepareExpectingInterceptor.await();
// Receiving the responses for one remote get triggers the next remote get, so complete them in parallel
firstRemoteGet.expectAllResponses().receiveAsync();
for (int i = 1; i < expectRemoteGets; ++i) {
crm2.expectCommand(BaseClusteredReadCommand.class).send().receiveAll();
}
sentPrepare.expectAllResponses().receiveAsync();
crm0.expectCommand(CommitCommand.class).send().receiveAll();
crm0.expectCommand(TxCompletionNotificationCommand.class).send();
commitFuture.get(10, TimeUnit.SECONDS);
crm2.excludeCommands(ClusteredGetCommand.class);
for (int i = 0; i < keys.length; i++) {
MagicKey key = keys[i];
assertEquals("v" + i, cache(2).get(key));
}
blockedStateResponse0.send().receiveAll();
newNode.get(10, TimeUnit.SECONDS);
}
private Object readWriteKey(MagicKey key, int index) {
FunctionalMap.ReadWriteMap<Object, Object> rwMap = ReadWriteMapImpl.create(FunctionalMapImpl.create(cache(0).getAdvancedCache()));
CompletableFuture cf = rwMap.eval(key, view -> {
assertFalse(view.find().isPresent());
view.set("v" + index);
return "r" + index;
});
return cf.join();
}
private Object readWriteMany(MagicKey key, int index) {
// make sure the other key is stable
MagicKey otherKey = new MagicKey("other", cache(0), cache(2));
FunctionalMap.ReadWriteMap<Object, Object> rwMap = ReadWriteMapImpl.create(FunctionalMapImpl.create(cache(0).getAdvancedCache()));
HashSet<MagicKey> keys = new HashSet<>(Arrays.asList(key, otherKey));
Traversable<Object> traversable = rwMap.evalMany(keys, view -> {
assertFalse(view.find().isPresent());
view.set("v" + index);
return "r" + index;
});
return traversable.findAny().orElseThrow(IllegalStateException::new);
}
private Object readWriteKeyValue(MagicKey key, int index) {
FunctionalMap.ReadWriteMap<Object, Object> rwMap = ReadWriteMapImpl.create(FunctionalMapImpl.create(cache(0).getAdvancedCache()));
CompletableFuture cfa = rwMap.eval(key, "v" + index, (value, view) -> {
assertFalse(view.find().isPresent());
view.set(value);
return "r" + index;
});
return cfa.join();
}
private Object readWriteManyEntries(MagicKey key, int index) {
// make sure the other key is stable
MagicKey otherKey = new MagicKey("other", cache(0), cache(2));
FunctionalMap.ReadWriteMap<Object, Object> rwMap = ReadWriteMapImpl.create(FunctionalMapImpl.create(cache(0).getAdvancedCache()));
HashMap<MagicKey, Object> map = new HashMap<>();
map.put(key, "v" + index);
map.put(otherKey, "something");
Traversable<Object> traversable = rwMap.evalMany(map, (value, view) -> {
assertFalse(view.find().isPresent());
view.set(value);
return "r" + index;
});
return traversable.findAny().orElseThrow(IllegalStateException::new);
}
private static <T extends RpcManager> T replace(Cache<Object, Object> cache, Function<RpcManager, T> ctor) {
T crm = ctor.apply(TestingUtil.extractComponent(cache, RpcManager.class));
TestingUtil.replaceComponent(cache, RpcManager.class, crm, true);
return crm;
}
@Listener(observation = Listener.Observation.POST)
private class TopologyChangeListener {
private final CountDownLatch latch;
TopologyChangeListener(CountDownLatch latch) {
this.latch = latch;
}
@TopologyChanged
public void onTopologyChange(TopologyChangedEvent event) {
latch.countDown();
}
}
class PrepareExpectingInterceptor extends DDAsyncInterceptor {
private final CountDownLatch latch = new CountDownLatch(1);
@Override
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable {
assertFalse(ctx.isOriginLocal());
InvocationStage invocationStage = makeStage(invokeNext(ctx, command));
assertFalse(invocationStage.toString(), invocationStage.isDone());
log.debug("Received incomplete stage");
latch.countDown();
return invocationStage;
}
public void await() throws InterruptedException {
boolean success = latch.await(10, TimeUnit.SECONDS);
if (!success) {
throw new TimeoutException("Timed out waiting for PrepareCommand");
}
}
}
}
| 12,453
| 44.287273
| 136
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/EmbeddedTransactionTest.java
|
package org.infinispan.tx;
import static org.infinispan.commons.test.Exceptions.expectException;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.testng.annotations.Test;
/**
* Set of tests for the {@link org.infinispan.transaction.tm.EmbeddedTransaction}.
*
* @author Pedro Ruivo
* @since 7.2
*/
@Test(groups = "functional", testName = "tx.EmbeddedTransactionTest")
public class EmbeddedTransactionTest extends SingleCacheManagerTest {
private static final String SYNC_CACHE_NAME = "sync-cache";
private static final String XA_CACHE_NAME = "xa-cache";
private static final String KEY = "key";
private static final String VALUE = "value";
public void testFailBeforeWithMarkRollbackFirstSync() throws Exception {
doCommitWithRollbackExceptionTest(Arrays.asList(
new RegisterFailSynchronization(FailMode.BEFORE_MARK_ROLLBACK),
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME))
));
}
public void testFailBeforeWithExceptionFirstSync() throws Exception {
doCommitWithRollbackExceptionTest(Arrays.asList(
new RegisterFailSynchronization(FailMode.BEFORE_THROW_EXCEPTION),
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME))
));
}
public void testFailBeforeWithMarkRollbackSecondSync() throws Exception {
doCommitWithRollbackExceptionTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterFailSynchronization(FailMode.BEFORE_MARK_ROLLBACK),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME))
));
}
public void testFailBeforeWithExceptionSecondSync() throws Exception {
doCommitWithRollbackExceptionTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterFailSynchronization(FailMode.BEFORE_THROW_EXCEPTION),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME))
));
}
public void testEndFailFirstXa() throws Exception {
doCommitWithRollbackExceptionTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterFailXaResource(FailMode.XA_END),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME))
));
}
public void testEndFailSecondXa() throws Exception {
doCommitWithRollbackExceptionTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME)),
new RegisterFailXaResource(FailMode.XA_END)
));
}
public void testPrepareFailFirstXa() throws Exception {
doCommitWithRollbackExceptionTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterFailXaResource(FailMode.XA_PREPARE),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME))
));
}
public void testPrepareFailSecondXa() throws Exception {
doCommitWithRollbackExceptionTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME)),
new RegisterFailXaResource(FailMode.XA_PREPARE)
));
}
public void testCommitFailFirstXa() throws Exception {
doCommitWithExceptionTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterFailXaResource(FailMode.XA_COMMIT),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME))
), HeuristicMixedException.class, true);
}
public void testCommitFailSecondXa() throws Exception {
doCommitWithExceptionTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME)),
new RegisterFailXaResource(FailMode.XA_COMMIT)
), HeuristicMixedException.class, true);
}
public void testRollbackFailFirstXa() throws Exception {
doRollbackWithHeuristicExceptionTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterFailXaResource(FailMode.XA_ROLLBACK),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME))
));
}
public void testRollbackFailSecondXa() throws Exception {
doRollbackWithHeuristicExceptionTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME)),
new RegisterFailXaResource(FailMode.XA_ROLLBACK)
));
}
public void testFailAfterFirstSync() throws Exception {
doAfterCompletionFailTest(Arrays.asList(
new RegisterFailSynchronization(FailMode.AFTER_THROW_EXCEPTION),
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME))
));
}
public void testFailAfterSecondSync() throws Exception {
doAfterCompletionFailTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterFailSynchronization(FailMode.AFTER_THROW_EXCEPTION),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME))
));
}
public void testReadOnlyResource() throws Exception {
//test for ISPN-2813
EmbeddedTransactionManager transactionManager = EmbeddedTransactionManager.getInstance();
transactionManager.begin();
cacheManager.<String, String>getCache(SYNC_CACHE_NAME).put(KEY, VALUE);
cacheManager.<String, String>getCache(XA_CACHE_NAME).put(KEY, VALUE);
transactionManager.getTransaction().enlistResource(new ReadOnlyXaResource());
transactionManager.commit();
assertData();
assertNoTxInAllCaches();
assertNull(transactionManager.getTransaction());
}
public void testNoTransactionAtCommitAlone() throws Exception {
doCommitWithExceptionTest(Collections.singletonList(new RegisterFailXaResource(FailMode.XA_COMMIT_WITH_NOTX)),
HeuristicRollbackException.class, false);
}
public void testNoTransactionAtCommitWithOtherResources() throws Exception {
doCommitWithExceptionTest(Arrays.asList(
new RegisterCacheTransaction(cacheManager.getCache(SYNC_CACHE_NAME)),
new RegisterCacheTransaction(cacheManager.getCache(XA_CACHE_NAME)),
new RegisterFailXaResource(FailMode.XA_COMMIT_WITH_NOTX)
), HeuristicMixedException.class, true);
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(getDefaultStandaloneCacheConfig(true));
ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(true);
builder.transaction().useSynchronization(true);
builder.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup());
cacheManager.defineConfiguration(SYNC_CACHE_NAME, builder.build());
builder = getDefaultStandaloneCacheConfig(true);
builder.transaction().useSynchronization(false);
builder.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup());
cacheManager.defineConfiguration(XA_CACHE_NAME, builder.build());
return cacheManager;
}
private void doCommitWithRollbackExceptionTest(Collection<RegisterTransaction> registerTransactionCollection) throws Exception {
EmbeddedTransactionManager transactionManager = EmbeddedTransactionManager.getInstance();
transactionManager.begin();
for (RegisterTransaction registerTransaction : registerTransactionCollection) {
registerTransaction.register(transactionManager);
}
try {
transactionManager.commit();
fail("RollbackException expected!");
} catch (RollbackException e) {
//expected
}
assertEmpty();
assertNoTxInAllCaches();
assertNull(transactionManager.getTransaction());
}
private void doCommitWithExceptionTest(Collection<RegisterTransaction> registerTransactionCollection,
Class<? extends Exception> exceptionClass, boolean checkData) throws Exception {
EmbeddedTransactionManager transactionManager = EmbeddedTransactionManager.getInstance();
transactionManager.begin();
for (RegisterTransaction registerTransaction : registerTransactionCollection) {
registerTransaction.register(transactionManager);
}
expectException(exceptionClass, transactionManager::commit);
if (checkData) {
assertData();
} else {
assertEmpty();
}
assertNoTxInAllCaches();
assertNull(transactionManager.getTransaction());
}
private void doRollbackWithHeuristicExceptionTest(Collection<RegisterTransaction> registerTransactionCollection) throws Exception {
EmbeddedTransactionManager transactionManager = EmbeddedTransactionManager.getInstance();
transactionManager.begin();
for (RegisterTransaction registerTransaction : registerTransactionCollection) {
registerTransaction.register(transactionManager);
}
try {
transactionManager.rollback();
fail("SystemException expected!");
} catch (SystemException e) {
//expected
}
assertEmpty();
assertNoTxInAllCaches();
assertNull(transactionManager.getTransaction());
}
private void doAfterCompletionFailTest(Collection<RegisterTransaction> registerTransactionCollection) throws Exception {
EmbeddedTransactionManager transactionManager = EmbeddedTransactionManager.getInstance();
transactionManager.begin();
for (RegisterTransaction registerTransaction : registerTransactionCollection) {
registerTransaction.register(transactionManager);
}
transactionManager.commit();
assertData();
assertNoTxInAllCaches();
assertNull(transactionManager.getTransaction());
}
private void assertEmpty() {
assertTrue(cacheManager.getCache(SYNC_CACHE_NAME).isEmpty());
assertTrue(cacheManager.getCache(XA_CACHE_NAME).isEmpty());
}
private void assertData() {
assertEquals(VALUE, cacheManager.getCache(SYNC_CACHE_NAME).get(KEY));
assertEquals(VALUE, cacheManager.getCache(XA_CACHE_NAME).get(KEY));
}
private void assertNoTxInAllCaches() {
assertNoTransactions(cacheManager.getCache(XA_CACHE_NAME));
assertNoTransactions(cacheManager.getCache(SYNC_CACHE_NAME));
}
private enum FailMode {
BEFORE_MARK_ROLLBACK,
BEFORE_THROW_EXCEPTION,
AFTER_THROW_EXCEPTION,
XA_PREPARE,
XA_COMMIT,
XA_COMMIT_WITH_NOTX,
XA_ROLLBACK,
XA_END
}
private interface RegisterTransaction {
void register(TransactionManager transactionManager) throws Exception;
}
//a little hacky, but it is just to avoid implementing everything
private static class ReadOnlyXaResource extends FailXaResource {
private boolean finished;
private ReadOnlyXaResource() {
super(null);
}
@Override
public int prepare(Xid xid) {
finished = true;
return XA_RDONLY;
}
@Override
public void commit(Xid xid, boolean b) throws XAException {
if (finished) {
throw new XAException(XAException.XAER_NOTA);
}
}
@Override
public void rollback(Xid xid) throws XAException {
if (finished) {
throw new XAException(XAException.XAER_NOTA);
}
}
}
private static class FailXaResource implements XAResource {
private final FailMode failMode;
private FailXaResource(FailMode failMode) {
this.failMode = failMode;
}
@Override
public void commit(Xid xid, boolean b) throws XAException {
switch (failMode) {
case XA_COMMIT:
throw new XAException(XAException.XA_HEURCOM);
case XA_COMMIT_WITH_NOTX:
throw new XAException(XAException.XAER_NOTA);
}
}
@Override
public void end(Xid xid, int i) throws XAException {
if (failMode == FailMode.XA_END) {
throw new XAException();
}
}
@Override
public void forget(Xid xid) {/*no-op*/}
@Override
public int getTransactionTimeout() {
return 0;
}
@Override
public boolean isSameRM(XAResource xaResource) {
return xaResource instanceof FailSynchronization && ((FailSynchronization) xaResource).failMode == failMode;
}
@Override
public int prepare(Xid xid) throws XAException {
if (failMode == FailMode.XA_PREPARE) {
throw new XAException();
}
return XA_OK;
}
@Override
public Xid[] recover(int i) {
return new Xid[0];
}
@Override
public void rollback(Xid xid) throws XAException {
if (failMode == FailMode.XA_ROLLBACK) {
throw new XAException();
}
}
@Override
public boolean setTransactionTimeout(int i) {
return false;
}
@Override
public void start(Xid xid, int i) throws XAException {/*no-op*/}
}
private static class FailSynchronization implements Synchronization {
private final Transaction transaction;
private final FailMode failMode;
private FailSynchronization(Transaction transaction, FailMode failMode) {
this.transaction = transaction;
this.failMode = failMode;
}
@Override
public void beforeCompletion() {
switch (failMode) {
case BEFORE_MARK_ROLLBACK:
try {
transaction.setRollbackOnly();
} catch (SystemException e) {
/* ignored */
}
break;
case BEFORE_THROW_EXCEPTION:
throw new RuntimeException("induced!");
}
}
@Override
public void afterCompletion(int status) {
if (failMode == FailMode.AFTER_THROW_EXCEPTION) {
throw new RuntimeException("induced!");
}
}
}
private static class RegisterCacheTransaction implements RegisterTransaction {
private final Cache<String, String> cache;
private RegisterCacheTransaction(Cache<String, String> cache) {
this.cache = cache;
}
@Override
public void register(TransactionManager transactionManager) {
cache.put(KEY, VALUE);
}
}
private static class RegisterFailSynchronization implements RegisterTransaction {
private final FailMode failMode;
private RegisterFailSynchronization(FailMode failMode) {
this.failMode = failMode;
}
@Override
public void register(TransactionManager transactionManager) throws Exception {
Transaction transaction = transactionManager.getTransaction();
FailSynchronization failSynchronization = new FailSynchronization(transaction, failMode);
transaction.registerSynchronization(failSynchronization);
}
}
private static class RegisterFailXaResource implements RegisterTransaction {
private final FailMode failMode;
private RegisterFailXaResource(FailMode failMode) {
this.failMode = failMode;
}
@Override
public void register(TransactionManager transactionManager) throws Exception {
Transaction transaction = transactionManager.getTransaction();
transaction.enlistResource(new FailXaResource(failMode));
}
}
}
| 17,293
| 35.331933
| 134
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TransactionXaAdapterTmIntegrationTest.java
|
package org.infinispan.tx;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.AssertJUnit.assertEquals;
import java.util.UUID;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.context.impl.TransactionalInvocationContextFactory;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.impl.TransactionCoordinator;
import org.infinispan.transaction.impl.TransactionOriginatorChecker;
import org.infinispan.transaction.tm.EmbeddedBaseTransactionManager;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.transaction.xa.LocalXaTransaction;
import org.infinispan.transaction.xa.TransactionFactory;
import org.infinispan.transaction.xa.TransactionXaAdapter;
import org.infinispan.transaction.xa.XaTransactionTable;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.2
*/
@Test(groups = "unit", testName = "tx.TransactionXaAdapterTmIntegrationTest")
public class TransactionXaAdapterTmIntegrationTest {
private LocalXaTransaction localTx;
private TransactionXaAdapter xaAdapter;
private XidImpl xid;
private final UUID uuid = Util.threadLocalRandomUUID();
private TransactionCoordinator txCoordinator;
@BeforeMethod
public void setUp() throws XAException {
Configuration configuration = new ConfigurationBuilder().build();
XaTransactionTable txTable = new XaTransactionTable();
txCoordinator = new TransactionCoordinator();
TestingUtil.inject(txTable, configuration, txCoordinator, TransactionOriginatorChecker.LOCAL);
txTable.start();
txTable.startXidMapping();
TransactionFactory gtf = new TransactionFactory();
gtf.init(false, false, true, false);
GlobalTransaction globalTransaction = gtf.newGlobalTransaction(null, false);
EmbeddedBaseTransactionManager tm = new EmbeddedBaseTransactionManager();
localTx = new LocalXaTransaction(new EmbeddedTransaction(tm), globalTransaction, false, 1, 0);
xid = EmbeddedTransaction.createXid(uuid);
InvocationContextFactory icf = new TransactionalInvocationContextFactory();
CommandsFactory commandsFactory = mock(CommandsFactory.class);
AsyncInterceptorChain invoker = mock(AsyncInterceptorChain.class);
when(invoker.invokeAsync(any(), any())).thenReturn(CompletableFutures.completedNull());
TestingUtil.inject(txCoordinator, commandsFactory, icf, invoker, txTable, configuration);
xaAdapter = new TransactionXaAdapter(localTx, txTable);
xaAdapter.start(xid, 0);
}
public void testPrepareOnNonexistentXid() {
XidImpl xid = EmbeddedTransaction.createXid(uuid);
try {
xaAdapter.prepare(xid);
assert false;
} catch (XAException e) {
assertEquals(XAException.XAER_NOTA, e.errorCode);
}
}
public void testCommitOnNonexistentXid() {
XidImpl xid = EmbeddedTransaction.createXid(uuid);
try {
xaAdapter.commit(xid, false);
assert false;
} catch (XAException e) {
assertEquals(XAException.XAER_NOTA, e.errorCode);
}
}
public void testRollabckOnNonexistentXid() {
XidImpl xid = EmbeddedTransaction.createXid(uuid);
try {
xaAdapter.rollback(xid);
assert false;
} catch (XAException e) {
assertEquals(XAException.XAER_NOTA, e.errorCode);
}
}
public void testPrepareTxMarkedForRollback() {
localTx.markForRollback(true);
try {
xaAdapter.prepare(xid);
assert false;
} catch (XAException e) {
assertEquals(XAException.XA_RBROLLBACK, e.errorCode);
}
}
public void testOnePhaseCommitConfigured() throws XAException {
Configuration configuration = new ConfigurationBuilder().clustering().cacheMode(CacheMode.INVALIDATION_ASYNC).build();
TestingUtil.inject(txCoordinator, configuration);
txCoordinator.start();
assert XAResource.XA_OK == xaAdapter.prepare(xid);
}
public void test1PcAndNonExistentXid() {
Configuration configuration = new ConfigurationBuilder().clustering().cacheMode(CacheMode.INVALIDATION_ASYNC).build();
TestingUtil.inject(txCoordinator, configuration);
try {
XidImpl doesNotExists = EmbeddedTransaction.createXid(uuid);
xaAdapter.commit(doesNotExists, false);
assert false;
} catch (XAException e) {
assertEquals(XAException.XAER_NOTA, e.errorCode);
}
}
public void test1PcAndNonExistentXid2() {
Configuration configuration = new ConfigurationBuilder().clustering().cacheMode(CacheMode.DIST_SYNC).build();
TestingUtil.inject(txCoordinator, configuration);
try {
XidImpl doesNotExists = EmbeddedTransaction.createXid(uuid);
xaAdapter.commit(doesNotExists, true);
assert false;
} catch (XAException e) {
assertEquals(XAException.XAER_NOTA, e.errorCode);
}
}
}
| 5,679
| 37.378378
| 124
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/ModificationListUnitTest.java
|
package org.infinispan.tx;
import static org.infinispan.commons.test.Exceptions.expectException;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.transaction.impl.ModificationList;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.testng.annotations.Test;
/**
* Unit tests for {@link ModificationList}.
*
* @since 14.0
*/
@Test(groups = "functional", testName = "tx.ModificationListUnitTest")
public class ModificationListUnitTest extends AbstractInfinispanTest {
private static WriteCommand mockCommand(boolean cacheModeLocalFlag) {
WriteCommand cmd = Mockito.mock(WriteCommand.class);
Mockito.when(cmd.hasAnyFlag(ArgumentMatchers.anyLong())).thenReturn(cacheModeLocalFlag);
return cmd;
}
public void testZeroAndNegativeCapacity() {
expectException(IllegalArgumentException.class, () -> new ModificationList(0));
expectException(IllegalArgumentException.class, () -> new ModificationList(-1));
}
public void testGrow() {
ModificationList modsList = new ModificationList(1);
int expectedSize = 5;
for (int i = 0; i < expectedSize; ++i) {
modsList.append(mockCommand(true));
}
assertEquals(expectedSize, modsList.size());
assertEquals(expectedSize, modsList.getAllModifications().size());
assertEquals(0, modsList.getModifications().size());
for (int i = 0; i < expectedSize; ++i) {
modsList.append(mockCommand(false));
}
assertEquals(expectedSize * 2, modsList.size());
assertEquals(expectedSize * 2, modsList.getAllModifications().size());
assertEquals(expectedSize, modsList.getModifications().size());
}
public void testFreeze() {
List<WriteCommand> commands = Arrays.asList(mockCommand(false), mockCommand(false), mockCommand(false));
ModificationList modsList = ModificationList.fromCollection(commands);
assertEquals(commands.size(), modsList.size());
assertEquals(commands.size(), modsList.getModifications().size());
assertEquals(commands.size(), modsList.getAllModifications().size());
modsList.freeze();
expectException(IllegalStateException.class, () -> modsList.append(mockCommand(false)));
expectException(IllegalStateException.class, () -> modsList.append(mockCommand(true)));
}
public void testModsOrder() {
List<WriteCommand> commands = Arrays.asList(mockCommand(false), mockCommand(true), mockCommand(false));
ModificationList modsList = ModificationList.fromCollection(commands);
assertEquals(commands.size(), modsList.size());
assertFalse(modsList.isEmpty());
assertEquals(2, modsList.getModifications().size());
assertEquals(3, modsList.getAllModifications().size());
assertTrue(modsList.hasNonLocalModifications());
assertEquals(commands, modsList.getAllModifications());
assertEquals(Arrays.asList(commands.get(0), commands.get(2)), modsList.getModifications());
}
public void testSnapshot() {
List<WriteCommand> commands = Arrays.asList(mockCommand(false), mockCommand(true), mockCommand(false));
ModificationList modsList = ModificationList.fromCollection(commands);
List<WriteCommand> allCommands = modsList.getAllModifications();
List<WriteCommand> nonLocalCommands = modsList.getModifications();
assertEquals(commands.size(), modsList.size());
assertTrue(modsList.hasNonLocalModifications());
assertEquals(2, nonLocalCommands.size());
assertEquals(3, allCommands.size());
assertEquals(commands, allCommands);
assertEquals(Arrays.asList(commands.get(0), commands.get(2)), nonLocalCommands);
modsList.append(mockCommand(false));
assertEquals(commands.size() + 1, modsList.size());
// Snapshot should be unchanged
assertEquals(2, nonLocalCommands.size());
assertEquals(3, allCommands.size());
assertEquals(commands, allCommands);
assertEquals(Arrays.asList(commands.get(0), commands.get(2)), nonLocalCommands);
modsList.append(mockCommand(true));
assertEquals(commands.size() + 2, modsList.size());
// Snapshot should be unchanged
assertEquals(2, nonLocalCommands.size());
assertEquals(3, allCommands.size());
assertEquals(commands, allCommands);
assertEquals(Arrays.asList(commands.get(0), commands.get(2)), nonLocalCommands);
}
}
| 4,685
| 38.711864
| 110
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/LockReleaseWithNoWriteTest.java
|
package org.infinispan.tx;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
/**
* @author Mircea Markus <mircea.markus@jboss.com> (C) 2011 Red Hat Inc.
* @since 5.1
*/
@Test (groups = "functional", testName = "tx.LockReleaseWithNoWriteTest")
public class LockReleaseWithNoWriteTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
dcc.transaction().lockingMode(LockingMode.PESSIMISTIC);
createCluster(TestDataSCI.INSTANCE, dcc, 2);
waitForClusterToForm();
}
public void testLocksReleased1() throws Exception {
runtTest(1, 0);
}
public void testLocksReleased2() throws Exception {
runtTest(1, 1);
}
public void testLocksReleased3() throws Exception {
runtTest(0, 0);
}
public void testLocksReleased4() throws Exception {
runtTest(0, 1);
}
private void runtTest(int lockOwner, int txOwner) throws NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
Object key = getKeyForCache(lockOwner);
tm(txOwner).begin();
advancedCache(txOwner).lock(key);
tm(txOwner).commit();
assertNotLocked(key);
}
}
| 1,815
| 33.264151
| 172
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/ContextAffectsTransactionReadCommittedTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import jakarta.transaction.Transaction;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
/**
* This test is to ensure that values in the context are properly counted for various cache operations
*
* @author wburns
* @since 6.0
*/
@Test (groups = "functional", testName = "tx.ContextAffectsTransactionReadCommittedTest")
public class ContextAffectsTransactionReadCommittedTest extends SingleCacheManagerTest {
protected StorageType storage;
@Factory
public Object[] factory() {
return new Object[] {
new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.BINARY),
new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.OBJECT),
new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.OFF_HEAP)
};
}
public ContextAffectsTransactionReadCommittedTest withStorage(StorageType storage) {
this.storage = storage;
return this;
}
@Override
protected String parameters() {
return "[storage=" + storage + "]";
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(true);
builder.memory().storageType(storage);
configure(builder);
return TestCacheManagerFactory.createCacheManager(builder);
}
protected void configure(ConfigurationBuilder builder) {
builder.locking().isolationLevel(IsolationLevel.READ_COMMITTED);
}
public void testSizeAfterClearInBranchedTransaction() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.get(1));
//clear is non transactional
cache.clear();
assertEquals(1, cache.size());
assertEquals("v1", cache.get(1));
} finally {
safeCommit(false);
}
}
public void testEntrySetAfterClearInBranchedTransaction() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.get(1));
//clear is non transactional
cache.clear();
Set<Map.Entry<Object, Object>> entrySet = cache.entrySet();
assertEquals(1, entrySet.size());
assertTrue(entrySet.contains(TestingUtil.createMapEntry(1, "v1")));
Iterator<Map.Entry<Object, Object>> iterator = entrySet.iterator();
Map.Entry<Object, Object> entry = iterator.next();
assertEquals(1, entry.getKey());
assertEquals("v1", entry.getValue());
assertFalse(iterator.hasNext());
} finally {
safeCommit(false);
}
}
public void testKeySetAfterClearInBranchedTransaction() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.get(1));
//clear is non transactional
cache.clear();
Set<Object> keySet = cache.keySet();
assertEquals(1, keySet.size());
assertTrue(keySet.contains(1));
Iterator<Object> iterator = keySet.iterator();
Object key = iterator.next();
assertEquals(1, key);
assertFalse(iterator.hasNext());
} finally {
safeCommit(false);
}
}
public void testValuesAfterClearInBranchedTransaction() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.get(1));
//clear is non transactional
cache.clear();
Collection<Object> values = cache.values();
assertEquals(1, values.size());
assertTrue(values.contains("v1"));
Iterator<Object> iterator = values.iterator();
Object value = iterator.next();
assertEquals("v1", value);
assertFalse(iterator.hasNext());
} finally {
safeCommit(false);
}
}
public void testSizeAfterClearInBranchedTransactionOnWrite() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.put(1, "v2"));
//clear is non transactional
cache.clear();
assertEquals(1, cache.size());
assertEquals("v2", cache.get(1));
} finally {
safeCommit(true);
}
}
public void testEntrySetAfterClearInBranchedTransactionOnWrite() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.put(1, "v2"));
//clear is non transactional
cache.clear();
Set<Map.Entry<Object, Object>> entrySet = cache.entrySet();
assertEquals(1, entrySet.size());
Map.Entry<Object, Object> entry = entrySet.iterator().next();
assertEquals(1, entry.getKey());
assertEquals("v2", entry.getValue());
assertTrue(entrySet.contains(TestingUtil.<Object, Object>createMapEntry(1, "v2")));
} finally {
safeCommit(true);
}
}
public void testKeySetAfterClearInBranchedTransactionOnWrite() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.put(1, "v2"));
//clear is non transactional
cache.clear();
Set<Object> keySet = cache.keySet();
assertEquals(1, keySet.size());
assertTrue(keySet.contains(1));
} finally {
safeCommit(true);
}
}
public void testValuesAfterClearInBranchedTransactionOnWrite() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.put(1, "v2"));
//clear is non transactional
cache.clear();
Collection<Object> values = cache.values();
assertEquals(1, values.size());
assertTrue(values.contains("v2"));
} finally {
safeCommit(true);
}
}
public void testSizeAfterRemoveInBranchedTransaction() throws Exception {
cache.put(1, "v1");
cache.put(2, "v2");
tm().begin();
try {
assertEquals("v1", cache.get(1));
Transaction suspended = tm().suspend();
cache.remove(1);
tm().resume(suspended);
assertEquals(2, cache.size());
assertEquals("v1", cache.get(1));
assertEquals("v2", cache.get(2));
} finally {
safeCommit(false);
}
}
public void testEntrySetAfterRemoveInBranchedTransaction() throws Exception {
cache.put(1, "v1");
cache.put(2, "v2");
tm().begin();
try {
assertEquals("v1", cache.get(1));
Transaction suspended = tm().suspend();
cache.remove(1);
tm().resume(suspended);
Set<Map.Entry<Object, Object>> entrySet = cache.entrySet();
assertEquals(2, entrySet.size());
for (Map.Entry<Object, Object> entry : entrySet) {
Object key = entry.getKey();
Object value = entry.getValue();
if (entry.getKey().equals(1)) {
assertEquals("v1", value);
} else if (key.equals(2)) {
assertEquals("v2", value);
} else {
fail("Unexpected entry found: " + entry);
}
}
assertTrue(entrySet.contains(TestingUtil.<Object, Object>createMapEntry(1, "v1")));
assertTrue(entrySet.contains(TestingUtil.<Object, Object>createMapEntry(2, "v2")));
} finally {
safeCommit(false);
}
}
public void testKeySetAfterRemoveInBranchedTransaction() throws Exception {
cache.put(1, "v1");
cache.put(2, "v2");
tm().begin();
try {
assertEquals("v1", cache.get(1));
Transaction suspended = tm().suspend();
cache.remove(1);
tm().resume(suspended);
Set<Object> keySet = cache.keySet();
assertEquals(2, keySet.size());
assertTrue(keySet.contains(1));
assertTrue(keySet.contains(2));
} finally {
safeCommit(false);
}
}
public void testValuesAfterRemoveInBranchedTransaction() throws Exception {
cache.put(1, "v1");
cache.put(2, "v2");
tm().begin();
try {
assertEquals("v1", cache.get(1));
Transaction suspended = tm().suspend();
cache.remove(1);
tm().resume(suspended);
Collection<Object> values = cache.values();
assertEquals(2, values.size());
assertTrue(values.contains("v1"));
assertTrue(values.contains("v2"));
} finally {
safeCommit(false);
}
}
public void testSizeAfterDoubleRemoveInBranchedTransaction() throws Exception {
cache.put(1, "v1");
cache.put(2, "v2");
tm().begin();
try {
assertEquals("v1", cache.remove(1));
Transaction suspended = tm().suspend();
assertEquals("v1", cache.remove(1));
tm().resume(suspended);
assertEquals(1, cache.size());
assertEquals("v2", cache.get(2));
} finally {
safeCommit(true);
}
}
public void testEntrySetAfterDoubleRemoveInBranchedTransaction() throws Exception {
cache.put(1, "v1");
cache.put(2, "v2");
tm().begin();
try {
assertEquals("v1", cache.remove(1));
Transaction suspended = tm().suspend();
assertEquals("v1", cache.remove(1));
tm().resume(suspended);
Set<Map.Entry<Object, Object>> entrySet = cache.entrySet();
assertEquals(1, entrySet.size());
Map.Entry<Object, Object> entry = entrySet.iterator().next();
assertEquals(2, entry.getKey());
assertEquals("v2", entry.getValue());
assertTrue(entrySet.contains(TestingUtil.<Object, Object>createMapEntry(2, "v2")));
} finally {
safeCommit(true);
}
}
public void testKeySetAfterDoubleRemoveInBranchedTransaction() throws Exception {
cache.put(1, "v1");
cache.put(2, "v2");
tm().begin();
try {
assertEquals("v1", cache.remove(1));
Transaction suspended = tm().suspend();
assertEquals("v1", cache.remove(1));
tm().resume(suspended);
Set<Object> keySet = cache.keySet();
assertEquals(1, keySet.size());
assertTrue(keySet.contains(2));
} finally {
safeCommit(true);
}
}
public void testValuesAfterDoubleRemoveInBranchedTransaction() throws Exception {
cache.put(1, "v1");
cache.put(2, "v2");
tm().begin();
try {
assertEquals("v1", cache.remove(1));
Transaction suspended = tm().suspend();
assertEquals("v1", cache.remove(1));
tm().resume(suspended);
Collection<Object> values = cache.values();
assertEquals(1, values.size());
assertTrue(values.contains("v2"));
} finally {
safeCommit(true);
}
}
public void testSizeAfterPutInBranchedTransactionButRemove() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.remove(1));
Transaction suspended = tm().suspend();
assertEquals("v1", cache.put(1, "v2"));
tm().resume(suspended);
assertEquals(0, cache.size());
} finally {
safeCommit(true);
}
}
public void testEntrySetAfterPutInBranchedTransactionButRemove() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.remove(1));
Transaction suspended = tm().suspend();
assertEquals("v1", cache.put(1, "v2"));
tm().resume(suspended);
Set<Map.Entry<Object, Object>> entrySet = cache.entrySet();
assertEquals(0, entrySet.size());
assertFalse(entrySet.iterator().hasNext());
assertFalse(entrySet.contains(TestingUtil.<Object, Object>createMapEntry(1, "v2")));
} finally {
safeCommit(true);
}
}
public void testKeySetAfterPutInBranchedTransactionButRemove() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.remove(1));
Transaction suspended = tm().suspend();
assertEquals("v1", cache.put(1, "v2"));
tm().resume(suspended);
Set<Object> keySet = cache.keySet();
assertEquals(0, keySet.size());
assertFalse(keySet.iterator().hasNext());
assertFalse(keySet.contains(1));
} finally {
safeCommit(true);
}
}
public void testValuesAfterPutInBranchedTransactionButRemove() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
assertEquals("v1", cache.remove(1));
Transaction suspended = tm().suspend();
assertEquals("v1", cache.put(1, "v2"));
tm().resume(suspended);
Collection<Object> values = cache.values();
assertEquals(0, values.size());
assertFalse(values.iterator().hasNext());
assertFalse(values.contains("v2"));
} finally {
safeCommit(true);
}
}
protected void safeCommit(boolean throwWriteSkew) throws Exception {
tm().commit();
}
}
| 13,640
| 27.657563
| 102
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TransactionsSpanningDistributedCachesTest.java
|
package org.infinispan.tx;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test(groups = "functional", testName = "tx.TransactionsSpanningDistributedCachesTest")
public class TransactionsSpanningDistributedCachesTest extends TransactionsSpanningReplicatedCachesTest {
@Override
protected ConfigurationBuilder getConfiguration() {
return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
}
@Override
protected void createCacheManagers() throws Exception {
super.createCacheManagers();
cache(0, "cache1");
cache(0, "cache2");
cache(1, "cache1");
cache(1, "cache2");
cache(0);
cache(1);
}
}
| 821
| 25.516129
| 105
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TransactionCleanupWithRecoveryTest.java
|
package org.infinispan.tx;
import jakarta.transaction.Transaction;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.Flag;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "tx.TransactionCleanupWithRecoveryTest")
public class TransactionCleanupWithRecoveryTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() {
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.clustering().cacheMode(CacheMode.REPL_SYNC)
.locking()
.concurrencyLevel(10000)
.isolationLevel(IsolationLevel.REPEATABLE_READ)
.lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis())
.useLockStriping(false)
.transaction()
.transactionMode(TransactionMode.TRANSACTIONAL)
.lockingMode(LockingMode.PESSIMISTIC)
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.recovery().enable();
registerCacheManager(TestCacheManagerFactory.createClusteredCacheManager(cfg),
TestCacheManagerFactory.createClusteredCacheManager(cfg));
}
public void testCleanup() throws Exception {
cache(0).put(1, "v1");
assertNoTx();
}
public void testWithSilentFailure() throws Exception {
Cache<Integer, String> c0 = cache(0), c1 = cache(1);
c0.put(1, "v1");
assertNoTx();
tm(1).begin();
c1.put(1, "v2");
Transaction suspendedTx = tm(1).suspend();
try {
Cache<Integer, String> silentC0 = c0.getAdvancedCache().withFlags(
Flag.FAIL_SILENTLY, Flag.ZERO_LOCK_ACQUISITION_TIMEOUT);
tm(0).begin();
assert !silentC0.getAdvancedCache().lock(1);
assert "v1".equals(silentC0.get(1));
tm(0).rollback();
} finally {
tm(1).resume(suspendedTx);
tm(1).commit();
}
assertNoTx();
}
private void assertNoTx() {
final TransactionTable tt0 = TestingUtil.getTransactionTable(cache(0));
// Message to forget transactions is sent asynchronously
eventually(() -> {
int localTxCount = tt0.getLocalTxCount();
int remoteTxCount = tt0.getRemoteTxCount();
return localTxCount == 0 && remoteTxCount == 0;
});
final TransactionTable tt1 = TestingUtil.getTransactionTable(cache(1));
eventually(() -> {
int localTxCount = tt1.getLocalTxCount();
int remoteTxCount = tt1.getRemoteTxCount();
return localTxCount == 0 && remoteTxCount == 0;
});
}
}
| 3,149
| 33.23913
| 85
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TransactionManagerLookupTest.java
|
package org.infinispan.tx;
import jakarta.transaction.TransactionManager;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.lookup.GenericTransactionManagerLookup;
import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup;
import org.infinispan.commons.tx.lookup.TransactionManagerLookup;
import org.testng.annotations.Test;
/**
* Tests all TransactionManagerLookup impls shipped with Infinispan for correctness
*
* @author Manik Surtani
* @version 4.1
*/
@Test(testName = "tx.TransactionManagerLookupTest", groups = "unit")
public class TransactionManagerLookupTest extends AbstractInfinispanTest {
final GlobalConfiguration globalConfiguration = new GlobalConfigurationBuilder().build();
public void testGenericTransactionManagerLookup() throws Exception {
GenericTransactionManagerLookup lookup = new GenericTransactionManagerLookup();
TestingUtil.inject(lookup, globalConfiguration);
doTest(lookup);
}
public void testDummyTransactionManagerLookup() throws Exception {
doTest(new EmbeddedTransactionManagerLookup());
}
public void testJBossStandaloneJTAManagerLookup() throws Exception {
JBossStandaloneJTAManagerLookup lookup = new JBossStandaloneJTAManagerLookup();
lookup.init(globalConfiguration);
doTest(lookup);
}
protected void doTest(TransactionManagerLookup lookup) throws Exception {
TransactionManager tm = lookup.getTransactionManager();
tm.begin();
tm.commit();
tm.begin();
tm.rollback();
}
}
| 1,824
| 34.096154
| 92
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/RollbackBeforePrepareTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.fail;
import java.util.concurrent.CountDownLatch;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.InCacheMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.concurrent.TimeoutException;
import org.infinispan.util.mocks.ControlledCommandFactory;
import org.testng.annotations.Test;
@Test(testName = "tx.RollbackBeforePrepareTest", groups = "functional")
@InCacheMode({CacheMode.DIST_SYNC, CacheMode.REPL_SYNC})
public class RollbackBeforePrepareTest extends MultipleCacheManagersTest {
public static final long REPL_TIMEOUT = 1000;
public static final long LOCK_TIMEOUT = 500;
private FailPrepareInterceptor failPrepareInterceptor;
protected int numOwners = 3;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder config = getDefaultClusteredCacheConfig(cacheMode, true);
config
.locking().lockAcquisitionTimeout(LOCK_TIMEOUT)
.clustering().remoteTimeout(REPL_TIMEOUT)
.clustering().hash().numOwners(numOwners)
.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.transaction().completedTxTimeout(3600000);
createCluster(config, 3);
waitForClusterToForm();
failPrepareInterceptor = new FailPrepareInterceptor();
extractInterceptorChain(advancedCache(2)).addInterceptor(failPrepareInterceptor, 1);
}
public void testCommitNotSentBeforeAllPrepareAreAck() throws Exception {
ControlledCommandFactory ccf = ControlledCommandFactory.registerControlledCommandFactory(cache(1), PrepareCommand.class);
ccf.gate.close();
try {
cache(0).put("k", "v");
fail();
} catch (Exception e) {
//expected
}
//this will also cause a replication timeout
allowRollbackToRun();
ccf.gate.open();
//give some time for the prepare to execute
Thread.sleep(3000);
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
int remoteTxCount0 = TestingUtil.getTransactionTable(cache(0)).getRemoteTxCount();
int remoteTxCount1 = TestingUtil.getTransactionTable(cache(1)).getRemoteTxCount();
int remoteTxCount2 = TestingUtil.getTransactionTable(cache(2)).getRemoteTxCount();
log.tracef("remote0=%s, remote1=%s, remote2=%s", remoteTxCount0, remoteTxCount1, remoteTxCount2);
return remoteTxCount0 == 0 && remoteTxCount1 == 0 && remoteTxCount2 == 0;
}
});
assertNull(cache(0).get("k"));
assertNull(cache(1).get("k"));
assertNull(cache(2).get("k"));
assertNotLocked("k");
}
/**
* by using timeouts here the worse case is to have false positives, i.e. the test to pass when it shouldn't. no
* false negatives should be possible. In single threaded suit runs this test will generally fail in order
* to highlight a bug.
*/
private static void allowRollbackToRun() throws InterruptedException {
Thread.sleep(REPL_TIMEOUT * 15);
}
public static class FailPrepareInterceptor extends DDAsyncInterceptor {
CountDownLatch failureFinish = new CountDownLatch(1);
@Override
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable {
try {
throw new TimeoutException("Induced!");
} finally {
failureFinish.countDown();
}
}
}
}
| 4,062
| 36.275229
| 127
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TxCleanupServiceTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.infinispan.commands.tx.VersionedCommitCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.infinispan.util.ControlledConsistentHashFactory;
import org.infinispan.util.mocks.ControlledCommandFactory;
import org.testng.annotations.Test;
/**
* Test for https://issues.jboss.org/browse/ISPN-2383
*/
@CleanupAfterMethod
@Test(groups = "functional", testName = "tx.TxCleanupServiceTest")
public class TxCleanupServiceTest extends MultipleCacheManagersTest {
private static final int TX_COUNT = 1;
private ConfigurationBuilder dcc;
private ControlledConsistentHashFactory consistentHashFactory;
@Override
protected void createCacheManagers() throws Throwable {
dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
dcc.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup());
consistentHashFactory = new ControlledConsistentHashFactory.Default(1);
dcc.clustering().hash().numOwners(1).numSegments(1).consistentHashFactory(consistentHashFactory);
createCluster(TestDataSCI.INSTANCE, dcc, 2);
waitForClusterToForm();
}
public void testTransactionStateNotLost() throws Throwable {
final ControlledCommandFactory ccf = ControlledCommandFactory.registerControlledCommandFactory(cache(1), VersionedCommitCommand.class);
ccf.gate.close();
final Map<Object, EmbeddedTransaction> keys2Tx = new HashMap<>(TX_COUNT);
int viewId = advancedCache(0).getRpcManager().getTransport().getViewId();
log.tracef("ViewId before %s", viewId);
//fork it into another thread as this is going to block in commit
Future<Object> future = fork(() -> {
for (int i = 0; i < TX_COUNT; i++) {
Object k = getKeyForCache(1);
tm(0).begin();
cache(0).put(k, k);
EmbeddedTransaction transaction = ((EmbeddedTransactionManager) tm(0)).getTransaction();
keys2Tx.put(k, transaction);
tm(0).commit();
}
return null;
});
//now wait for all the commits to block
eventuallyEquals(TX_COUNT, ccf.blockTypeCommandsReceived::get);
log.tracef("Viewid middle %s", viewId);
//now add a one new member
consistentHashFactory.setOwnerIndexes(2);
addClusterEnabledCacheManager(TestDataSCI.INSTANCE, dcc);
waitForClusterToForm();
viewId = advancedCache(0).getRpcManager().getTransport().getViewId();
log.tracef("Viewid after before %s", viewId);
final Map<Object, EmbeddedTransaction> migratedTx = new HashMap<>(TX_COUNT);
for (Object key : keys2Tx.keySet()) {
if (keyMapsToNode2(key)) {
migratedTx.put(key, keys2Tx.get(key));
}
}
log.tracef("Number of migrated tx is %s", migratedTx.size());
assertEquals(TX_COUNT, migratedTx.size());
eventuallyEquals(migratedTx.size(), () -> TestingUtil.getTransactionTable(cache(2)).getRemoteTxCount());
log.trace("Releasing the gate");
ccf.gate.open();
future.get(10, TimeUnit.SECONDS);
eventuallyEquals(0, () -> TestingUtil.getTransactionTable(cache(2)).getRemoteTxCount());
eventually(() -> {
boolean allZero = true;
for (int i = 0; i < 3; i++) {
TransactionTable tt = TestingUtil.getTransactionTable(cache(i));
// assertEquals("For cache " + i, 0, tt.getLocalTxCount());
// assertEquals("For cache " + i, 0, tt.getRemoteTxCount());
int local = tt.getLocalTxCount();
int remote = tt.getRemoteTxCount();
log.tracef("For cache %d, localTxCount=%s, remoteTxCount=%s", i, local, remote);
log.tracef(String.format("For cache %s , localTxCount=%s, remoteTxCount=%s", i, local, remote));
allZero = allZero && (local == 0);
allZero = allZero && (remote == 0);
}
return allZero;
});
for (Object key : keys2Tx.keySet()) {
assertNotLocked(key);
assertEquals(key, cache(0).get(key));
}
}
private boolean keyMapsToNode2(Object key) {
Address owner = owner(key);
return owner.equals(address(2));
}
private Address owner(Object key) {
return advancedCache(0).getDistributionManager().getCacheTopology().getDistribution(key).primary();
}
}
| 5,151
| 35.8
| 141
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/ReadOnlyRepeatableReadTxTest.java
|
package org.infinispan.tx;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
/**
* @author William Burns
* @since 6.0
*/
@Test (groups = "functional", testName = "tx.ReadOnlyRepeatableReadTxTest")
@CleanupAfterMethod
public class ReadOnlyRepeatableReadTxTest extends ReadOnlyTxTest {
protected void configure(ConfigurationBuilder builder) {
super.configure(builder);
builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
}
}
| 615
| 29.8
| 75
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/StaleLockAfterTxAbortTest.java
|
package org.infinispan.tx;
import java.util.concurrent.CountDownLatch;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.testng.annotations.Test;
/**
* This tests the following pattern:
* <p/>
* Thread T1 holds lock for key K. TX1 attempts to lock a key K. Waits for lock. TM times out the tx and aborts the tx
* (calls XA.end, XA.rollback). T1 releases lock. Wait a few seconds. Make sure there are no stale locks (i.e., when the
* thread for TX1 wakes up and gets the lock on K, it then releases and aborts).
*
* @author manik
*/
@Test (testName = "tx.StaleLockAfterTxAbortTest", groups = "unit")
public class StaleLockAfterTxAbortTest extends SingleCacheManagerTest {
final String k = "key";
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder c = getDefaultStandaloneCacheConfig(true);
c.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup()).useSynchronization(false).recovery().disable();
return TestCacheManagerFactory.createCacheManager(c);
}
public void doTest() throws Throwable {
cache.put(k, "value"); // init value
assertEventuallyNotLocked(cache, k);
// InvocationContextContainerImpl icc = (InvocationContextContainerImpl) TestingUtil.extractComponent(cache, InvocationContextContainer.class);
// InvocationContext ctx = icc.getInvocationContext();
// LockManager lockManager = TestingUtil.extractComponent(cache, LockManager.class);
// lockManager.lockAndRecord(k, ctx);
// ctx.putLookedUpEntry(k, null);
EmbeddedTransactionManager dtm = (EmbeddedTransactionManager) tm();
tm().begin();
cache.put(k, "some");
final EmbeddedTransaction transaction = dtm.getTransaction();
transaction.runPrepare();
tm().suspend();
// test that the key is indeed locked.
assertLocked(cache, k);
final CountDownLatch txStartedLatch = new CountDownLatch(1);
TxThread transactionThread = new TxThread(cache, txStartedLatch);
transactionThread.start();
txStartedLatch.countDown();
Thread.sleep(500); // in case the thread needs some time to get to the locking code
// now abort the tx.
transactionThread.tm.resume(transactionThread.tx);
transactionThread.tm.rollback();
// now release the lock
tm().resume(transaction);
transaction.runCommit(true);
transactionThread.join();
assertEventuallyNotLocked(cache, k);
}
private class TxThread extends Thread {
final Cache<Object, Object> cache;
volatile Transaction tx;
volatile Exception exception;
final TransactionManager tm;
final CountDownLatch txStartedLatch;
private TxThread(Cache<Object, Object> cache, CountDownLatch txStartedLatch) {
this.cache = cache;
this.tx = null;
this.tm = cache.getAdvancedCache().getTransactionManager();
this.txStartedLatch = txStartedLatch;
}
@Override
public void run() {
try {
// Now start a new tx.
tm.begin();
tx = tm.getTransaction();
log.trace("Started transaction " + tx);
txStartedLatch.countDown();
cache.put(k, "v2"); // this should block.
} catch (Exception e) {
exception = e;
}
}
}
}
| 3,884
| 34.972222
| 148
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TxCompletionForRolledBackTxOptTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.fail;
import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.tx.VersionedPrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.mocks.ControlledCommandFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "tx.TxCompletionForRolledBackTxOptTest")
public class TxCompletionForRolledBackTxOptTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
dcc.clustering().hash().numOwners(1).transaction().lockingMode(LockingMode.OPTIMISTIC);
createCluster(TestDataSCI.INSTANCE, dcc, 3);
waitForClusterToForm();
extractInterceptorChain(advancedCache(2)).addInterceptor(new RollbackBeforePrepareTest.FailPrepareInterceptor(), 1);
}
public void testTxCompletionNotSentForRollback() throws Throwable {
ControlledCommandFactory cf = ControlledCommandFactory.registerControlledCommandFactory(cache(1), null);
tm(0).begin();
Object k1 = getKeyForCache(1);
Object k2 = getKeyForCache(2);
cache(0).put(k1, k1);
cache(0).put(k2, k2);
try {
tm(0).commit();
fail();
} catch (Throwable t) {
log.debugf("Got expected exception", t);
}
assertNotLocked(k1);
assertNotLocked(k2);
assertNull(cache(0).get(k1));
assertNull(cache(0).get(k2));
assertEquals(cf.received(VersionedPrepareCommand.class), 1);
assertEquals(cf.received(RollbackCommand.class), 1);
assertEquals(cf.received(TxCompletionNotificationCommand.class), 0);
}
}
| 2,218
| 38.625
| 122
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/NoAutoCommitAndPferTest.java
|
package org.infinispan.tx;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "tx.NoAutoCommitAndPferTest")
public class NoAutoCommitAndPferTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder dsc = getDefaultStandaloneCacheConfig(true);
dsc.transaction().autoCommit(false);
return TestCacheManagerFactory.createCacheManager(dsc);
}
public void testPferNoAutoCommitExplicitTransaction() throws Exception {
tm().begin();
cache.putForExternalRead("k1","v");
tm().commit();
assert cache.get("k1").equals("v"); //here is the failure!
}
public void testPferNoAutoCommit() throws Exception {
cache.putForExternalRead("k2","v");
assert cache.get("k2").equals("v"); //here is the failure!
}
}
| 1,101
| 33.4375
| 75
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/Use1PcForInducedTransactionTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.testng.Assert.assertEquals;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.Test;
@Test (groups = "functional", testName = "tx.Use1PcForInducedTransactionTest")
public class Use1PcForInducedTransactionTest extends MultipleCacheManagersTest {
private InvocationCountInterceptor ic0;
private InvocationCountInterceptor ic1;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
c.transaction().use1PcForAutoCommitTransactions(true);
createCluster(c, 2);
waitForClusterToForm();
ic0 = new InvocationCountInterceptor();
extractInterceptorChain(cache(0)).addInterceptor(ic0, 1);
ic1 = new InvocationCountInterceptor();
extractInterceptorChain(cache(1)).addInterceptor(ic1, 1);
}
public void testSinglePhaseCommit() {
cache(0).put("k", "v");
assert cache(0).get("k").equals("v");
assert cache(1).get("k").equals("v");
assertNotLocked("k");
assertEquals(ic0.prepareInvocations, 1);
assertEquals(ic1.prepareInvocations, 1);
assertEquals(ic0.commitInvocations, 0);
assertEquals(ic0.commitInvocations, 0);
}
public static class InvocationCountInterceptor extends DDAsyncInterceptor {
volatile int prepareInvocations;
volatile int commitInvocations;
@Override
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable {
prepareInvocations ++;
return super.visitPrepareCommand(ctx, command);
}
@Override
public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable {
commitInvocations ++;
return super.visitCommitCommand(ctx, command);
}
}
}
| 2,306
| 33.432836
| 107
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/PrepareProcessedAfterOriginatorCrashTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.remoting.inboundhandler.AbstractDelegatingHandler;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler;
import org.infinispan.remoting.inboundhandler.Reply;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.impl.TransactionTable;
import org.testng.annotations.Test;
/**
* Tests the following scenario:
* <pre>
* - tx1 originated on N1 writes a single key that maps to N2
* - tx1 prepares and before committing crashes
* - the prepare is blocked on N2 before the tx is created
* - TransactionTable.cleanupStaleTransactions kicks in on N2 but doesn't clean up the transaction
* as it hasn't been prepared yet
* - the prepare is now executed on N2
* - the test makes sure that the transaction doesn't acquire any locks and doesn't leak
* within N1
* </pre>
*
* @author Mircea Markus
* @since 5.2
*/
@Test(groups = "functional", testName = "tx.PrepareProcessedAfterOriginatorCrashTest")
public class PrepareProcessedAfterOriginatorCrashTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
dcc.clustering().hash().numOwners(1);
createClusteredCaches(2, dcc);
}
public void testBelatedTransactionDoesntLeak() throws Throwable {
CountDownLatch prepareReceived = new CountDownLatch(1);
CountDownLatch prepareBlocked = new CountDownLatch(1);
CountDownLatch prepareExecuted = new CountDownLatch(1);
Cache receiver = cache(1);
PerCacheInboundInvocationHandler originalInvocationHandler = TestingUtil.extractComponent(receiver, PerCacheInboundInvocationHandler.class);
PerCacheInboundInvocationHandler blockingInvocationHandler = new AbstractDelegatingHandler(originalInvocationHandler) {
@Override
public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) {
if (!(command instanceof PrepareCommand)) {
delegate.handle(command, reply, order);
return;
}
try {
prepareReceived.countDown();
prepareBlocked.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new IllegalLifecycleStateException(e);
}
log.trace("Processing belated prepare");
delegate.handle(command, returnValue -> {
prepareExecuted.countDown();
reply.reply(returnValue);
}, order);
}
};
TestingUtil.replaceComponent(receiver, PerCacheInboundInvocationHandler.class, blockingInvocationHandler, true);
TestingUtil.extractComponentRegistry(receiver).cacheComponents();
final Object key = getKeyForCache(1);
fork(() -> {
try {
cache(0).put(key, "v");
} catch (Throwable e) {
//possible as the node is being killed
}
});
prepareReceived.await(10, TimeUnit.SECONDS);
killMember(0);
//give TransactionTable.cleanupStaleTransactions some time to run
Thread.sleep(5000);
prepareBlocked.countDown();
prepareExecuted.await(10, TimeUnit.SECONDS);
log.trace("Finished waiting for belated prepare to complete");
final TransactionTable transactionTable = TestingUtil.getTransactionTable(receiver);
assertEquals(0, transactionTable.getRemoteTxCount());
assertEquals(0, transactionTable.getLocalTxCount());
assertFalse(receiver.getAdvancedCache().getLockManager().isLocked(key));
}
}
| 4,293
| 39.130841
| 146
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/RemoteLockCleanupStressTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.sleepThread;
import jakarta.transaction.Status;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.concurrent.locks.LockManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
@Test (groups = "unstable", testName = "tx.RemoteLockCleanupStressTest", invocationCount = 20, description = "original group: functional")
@CleanupAfterMethod
public class RemoteLockCleanupStressTest extends MultipleCacheManagersTest {
private static final Log log = LogFactory.getLog(RemoteLockCleanupStressTest.class);
private String key = "locked-counter";
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true);
c.clustering().stateTransfer().fetchInMemoryState(true)
.locking().lockAcquisitionTimeout(1500);
createClusteredCaches(2, c);
}
public void testLockRelease() {
final EmbeddedCacheManager cm1 = manager(0);
final EmbeddedCacheManager cm2 = manager(1);
Thread t1 = new Thread(new CounterTask(cm1));
Thread t2 = new Thread(new CounterTask(cm2));
t1.start();
t2.start();
sleepThread(1000);
t2.interrupt();
TestingUtil.killCacheManagers(cm2);
cacheManagers.remove(1);
sleepThread(1100);
t1.interrupt();
LockManager lm = TestingUtil.extractComponent(cm1.getCache(), LockManager.class);
Object owner = lm.getOwner(key);
assert ownerIsLocalOrUnlocked(owner, cm1.getAddress()) : "Bad lock owner " + owner;
}
private boolean ownerIsLocalOrUnlocked(Object owner, Address self) {
if (owner == null) return true;
if (owner instanceof GlobalTransaction) {
GlobalTransaction gtx = ((GlobalTransaction) owner);
return gtx.getAddress().equals(self);
} else {
return false;
}
}
class CounterTask implements Runnable {
EmbeddedCacheManager cm;
CounterTask(EmbeddedCacheManager cm) {
this.cm = cm;
}
@Override
public void run() {
for (int i=0; i<25; i++) run_();
}
public void run_() {
Cache cache = cm.getCache();
TransactionManager tx = cache.getAdvancedCache().getTransactionManager();
try {
tx.begin();
} catch (Exception ex) {
log.debug("Exception starting transaction", ex);
}
try {
log.debug("aquiring lock on cache " + cache.getName() + " key " + key + "...");
cache.getAdvancedCache().lock(key);
Integer val = (Integer) cache.get(key);
log.debug("current value : " + val);
if (val == null) {
val = 0;
} else {
val++;
}
cache.put(key, val);
TestingUtil.sleepRandom(200);
log.debug("commit...");
tx.commit();
log.debug("done commit");
} catch (Exception ex) {
try {
log.debug("rollback... " + ex.getLocalizedMessage());
tx.rollback();
log.debug("done rollback");
} catch (Exception rex) {
log.debug("Exception rolling back", rex);
}
} finally {
try {
log.debug("tx status at the end : ");
switch (tx.getStatus()) {
case Status.STATUS_ACTIVE:
log.debug("active");
break;
case Status.STATUS_COMMITTED:
log.debug("committed");
break;
case Status.STATUS_COMMITTING:
log.debug("committing");
break;
case Status.STATUS_MARKED_ROLLBACK:
log.debug("makerd rollback");
break;
case Status.STATUS_NO_TRANSACTION:
log.debug("no transaction");
break;
case Status.STATUS_PREPARED:
log.debug("preprared");
break;
case Status.STATUS_PREPARING:
log.debug("preparing");
break;
case Status.STATUS_ROLLEDBACK:
log.debug("rolledback");
break;
case Status.STATUS_ROLLING_BACK:
log.debug("rolling back");
break;
case Status.STATUS_UNKNOWN:
log.debug("unknown");
break;
default:
log.debug(tx.getStatus());
}
} catch (Exception ex) {
log.debug("Exception retrieving transaction status", ex);
}
}
}
}
}
| 5,470
| 33.19375
| 138
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/RemoteTxNotCreatedOnGetTest.java
|
package org.infinispan.tx;
import static org.testng.Assert.assertEquals;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.impl.TransactionTable;
import org.testng.annotations.Test;
/**
* @author Mircea Markus <mircea.markus@jboss.com> (C) 2011 Red Hat Inc.
* @since 5.1
*/
@Test(groups = "functional", testName = "tx.RemoteTxNotCreatedOnGetTest")
public class RemoteTxNotCreatedOnGetTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
dcc.clustering().l1().disable().hash().numOwners(1);
createCluster(TestDataSCI.INSTANCE, dcc, 2);
waitForClusterToForm();
}
public void testRemoteTxCreation() throws Throwable {
Object key = getKeyForCache(1);
cache(1).put(key, "v");
assertEquals("v", cache(0).get(key));
assertEquals("v", cache(1).get(key));
Thread.sleep(1000);
TransactionTable tt1 = TestingUtil.getTransactionTable(cache(1));
assertEquals(tt1.getRemoteTransactions().size(), 0);
tm(0).begin();
log.trace("Before going remotely");
cache(0).get(key);
assertEquals(tt1.getRemoteTransactions().size(), 0);
tm(0).commit();
}
}
| 1,532
| 32.326087
| 91
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TransactionCleanupTest.java
|
package org.infinispan.tx;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test(groups = "functional", testName = "tx.TransactionCleanupTest")
public class TransactionCleanupTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = getConfiguration();
createCluster(dcc, 2);
waitForClusterToForm();
}
protected ConfigurationBuilder getConfiguration() {
return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true);
}
public void transactionCleanupTest1() throws Throwable {
runtTest(1, false);
}
public void transactionCleanupTest2() throws Throwable {
runtTest(0, false);
}
public void transactionCleanupTest3() throws Throwable {
runtTest(1, true);
}
public void transactionCleanupTest4() throws Throwable {
runtTest(0, true);
}
private void runtTest(int initiatorIndex, boolean rollback) throws Throwable{
tm(initiatorIndex).begin();
cache(initiatorIndex).put("k", "v");
if (rollback) {
tm(initiatorIndex).rollback();
} else {
tm(initiatorIndex).commit();
}
assertNotLocked("k");
eventually(() -> (TestingUtil.getTransactionTable(cache(0)).getRemoteTxCount() == 0) &&
(TestingUtil.getTransactionTable(cache(0)).getLocalTxCount() == 0) &&
(TestingUtil.getTransactionTable(cache(1)).getRemoteTxCount() == 0) &&
(TestingUtil.getTransactionTable(cache(1)).getLocalTxCount() == 0));
}
}
| 1,793
| 29.40678
| 93
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/NonTxCacheInterceptorTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertFalse;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.impl.TxInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test (groups = "functional", testName = "tx.NonTxCacheInterceptorTest")
public class NonTxCacheInterceptorTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.createCacheManager(getDefaultStandaloneCacheConfig(false));
}
public void testNoTxInterceptor() {
final AsyncInterceptorChain interceptorChain = cache.getAdvancedCache().getAsyncInterceptorChain();
log.trace(interceptorChain);
assertFalse(interceptorChain.containsInterceptorType(TxInterceptor.class));
}
}
| 1,040
| 33.7
| 105
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/Use1PcForInducedTxLockingTest.java
|
package org.infinispan.tx;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.testng.annotations.Test;
@Test (groups = "functional", testName = "tx.Use1PcForInducedTxLockingTest")
public class Use1PcForInducedTxLockingTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
dcc.transaction().use1PcForAutoCommitTransactions(true);
dcc.clustering().hash().numOwners(1);
createCluster(TestDataSCI.INSTANCE, dcc, 2);
waitForClusterToForm();
}
public void testCorrectLocking() {
Object k0 = getKeyForCache(0);
cache(1).put(k0, "v0");
assertNotLocked(k0);
assertNoTransactions();
cache(0).put(k0, "v0");
assertNotLocked(k0);
assertNoTransactions();
}
}
| 1,048
| 31.78125
| 91
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/StateTransferTransactionTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import jakarta.transaction.InvalidTransactionException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.infinispan.Cache;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commons.tx.TransactionImpl;
import org.infinispan.commons.tx.lookup.TransactionManagerLookup;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.LocalTxInvocationContext;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.interceptors.impl.TxInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.transaction.impl.LocalTransaction;
import org.infinispan.transaction.lookup.TransactionSynchronizationRegistryLookup;
import org.infinispan.transaction.tm.EmbeddedBaseTransactionManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Reproducer for ISPN-12798
* <p>
* The issue is the WF {@link TransactionManager#resume(Transaction)} is invoked with the ApplyStateTransaction. The WF
* {@link TransactionManager} doesn't know the instance and fails with {@link InvalidTransactionException}.
*
* @author Pedro Ruivo
* @since 12.1
*/
@Test(groups = "functional", testName = "tx.StateTransferTransactionTest")
public class StateTransferTransactionTest extends MultipleCacheManagersTest {
private static final Log log = LogFactory.getLog(StateTransferTransactionTest.class);
@Override
protected void createCacheManagers() throws Throwable {
createCluster(2);
}
@DataProvider(name = "data")
public static Object[][] configurationFiles() {
return new Object[][]{
{true, true},
{true, false},
{false, false},
};
}
@Test(dataProvider = "data")
public void testStateTransferTransactionNotEnlisted(boolean useSync, boolean useRegistry) {
final String cacheName = String.format("cache-%s", suffix(useSync, useRegistry));
final String key = String.format("key-%s", suffix(useSync, useRegistry));
log.debugf("Starting cache in node0");
manager(0).defineConfiguration(cacheName, configurationBuilder(useSync, useRegistry).build());
Cache<String, String> cache0 = manager(0).getCache(cacheName);
cache0.put(key, "value");
log.debugf("Starting cache in node1");
manager(1).defineConfiguration(cacheName, configurationBuilder(useSync, useRegistry).build());
Cache<String, String> cache1 = manager(1).getCache(cacheName);
waitForClusterToForm(cacheName);
CollectTxInterceptor interceptor = cache1.getAdvancedCache().getAsyncInterceptorChain().findInterceptorWithClass(CollectTxInterceptor.class);
assertEquals(1, interceptor.stateTransferTransactions.size());
TransactionImpl stateTransferTx = interceptor.stateTransferTransactions.iterator().next();
//useSync=false will fail here because Infinispan invokes ApplyStateTransaction.enlistResource() directly
assertTrue("Found XaResource", stateTransferTx.getEnlistedResources().isEmpty());
//useSync=true & useRegistry=false fails here because Infinispan invokes ApplyStateTransaction.registerSynchronization() directly
assertTrue("Found Synchronization", stateTransferTx.getEnlistedSynchronization().isEmpty());
//useSync=true & useRegistry=false fails here. DummyTransactionManager.resume() throws an exception which fails the state transfer
//it simulates the WF environment.
assertEquals("Wrong value in cache1", "value", cache1.get(key));
}
private static String suffix(boolean useSync, boolean useRegistry) {
return String.format("%s-%s", useSync ? "sync" : "xa", useRegistry ? "registry" : "no-registry");
}
private static ConfigurationBuilder configurationBuilder(boolean useSync, boolean useRegistry) {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
builder.transaction()
.useSynchronization(useSync)
.transactionManagerLookup(new DummyTransactionManagerLookup());
if (useRegistry) {
builder.transaction().transactionSynchronizationRegistryLookup(new DummyTransactionSynchronizationRegistryLookup());
}
builder.customInterceptors().addInterceptor().interceptor(new CollectTxInterceptor()).after(TxInterceptor.class);
builder.clustering().hash().numSegments(1);
return builder;
}
private static boolean isStateTransferTransaction(Transaction tx) {
return tx instanceof TransactionImpl && ((TransactionImpl) tx).getXid().getFormatId() == 2;
}
static class CollectTxInterceptor extends BaseCustomAsyncInterceptor {
private final Set<TransactionImpl> stateTransferTransactions;
CollectTxInterceptor() {
stateTransferTransactions = Collections.synchronizedSet(new HashSet<>());
}
@Override
protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
if (ctx.isInTxScope() && ctx.isOriginLocal()) {
LocalTransaction localTx = ((LocalTxInvocationContext) ctx).getCacheTransaction();
Transaction tx = localTx.getTransaction();
if (isStateTransferTransaction(tx)) {
log.debugf("collect transaction %s. list=%s", tx, stateTransferTransactions);
stateTransferTransactions.add((TransactionImpl) tx);
}
}
return super.handleDefault(ctx, command);
}
}
static class DummyTransactionManager extends EmbeddedBaseTransactionManager {
@Override
public void resume(Transaction tx) throws InvalidTransactionException, IllegalStateException, SystemException {
if (isStateTransferTransaction(tx)) {
log.debugf("Resume invoked with invalid transaction %s", tx);
//simulates WF exception
throw new InvalidTransactionException("Transaction is not a supported instance");
}
super.resume(tx);
}
}
static class DummyTransactionManagerLookup implements TransactionManagerLookup {
private static final DummyTransactionManager INSTANCE = new DummyTransactionManager();
@Override
public TransactionManager getTransactionManager() throws Exception {
return INSTANCE;
}
}
static class DummyTransactionSynchronizationRegistry implements TransactionSynchronizationRegistry {
@Override
public Object getTransactionKey() {
return null;
}
@Override
public int getTransactionStatus() {
return 0;
}
@Override
public boolean getRollbackOnly() throws IllegalStateException {
return false;
}
@Override
public void setRollbackOnly() throws IllegalStateException {
}
@Override
public void registerInterposedSynchronization(Synchronization synchronization) throws IllegalStateException {
Transaction tx = DummyTransactionManagerLookup.INSTANCE.getTransaction();
if (tx == null) {
throw new IllegalStateException();
}
try {
tx.registerSynchronization(synchronization);
} catch (RollbackException | SystemException e) {
throw new IllegalStateException(e);
}
}
@Override
public Object getResource(Object o) throws IllegalStateException {
return null;
}
@Override
public void putResource(Object o, Object o1) throws IllegalStateException {
}
}
static class DummyTransactionSynchronizationRegistryLookup implements TransactionSynchronizationRegistryLookup {
private static final DummyTransactionSynchronizationRegistry INSTANCE = new DummyTransactionSynchronizationRegistry();
@Override
public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() {
return INSTANCE;
}
}
}
| 8,587
| 38.394495
| 147
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TxCompletionForRolledBackTxTest.java
|
package org.infinispan.tx;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.mocks.ControlledCommandFactory;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.2
*/
@Test (groups = "functional", testName = "tx.TxCompletionForRolledBackTxTest")
public class TxCompletionForRolledBackTxTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
dcc.clustering().hash().numOwners(1).transaction().lockingMode(LockingMode.PESSIMISTIC);
amend(dcc);
createCluster(TestDataSCI.INSTANCE, dcc, 2);
waitForClusterToForm();
}
protected void amend(ConfigurationBuilder dcc) {}
public void testTxCompletionNotSentForRollback() throws Throwable {
ControlledCommandFactory cf = ControlledCommandFactory.registerControlledCommandFactory(cache(1), null);
tm(0).begin();
Object k = getKeyForCache(1);
cache(0).put(k,"k");
tm(0).rollback();
assertNotLocked(k);
assertNull(cache(0).get(k));
assertEquals(cf.received(RollbackCommand.class), 1);
assertEquals(cf.received(TxCompletionNotificationCommand.class), 0);
}
}
| 1,725
| 34.22449
| 110
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/StaleLockRecoveryTest.java
|
package org.infinispan.tx;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.remoting.RemoteException;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.concurrent.TimeoutException;
import org.testng.annotations.Test;
/**
* Tests what happens when a member acquires locks and then dies.
*
* @author Manik Surtani
* @since 4.0
*/
@Test(groups = "functional", testName = "tx.StaleLockRecoveryTest")
public class StaleLockRecoveryTest extends MultipleCacheManagersTest {
private Cache<String, String> c1, c2;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true);
c.transaction().lockingMode(LockingMode.PESSIMISTIC)
.locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis());
createClusteredCaches(2, "tx", c);
c1 = cache(0, "tx");
c2 = cache(1, "tx");
}
public void testStaleLock() throws SystemException, NotSupportedException {
c1.put("k", "v");
assert c1.get("k").equals("v");
assert c2.get("k").equals("v");
TransactionManager tm = TestingUtil.getTransactionManager(c1);
tm.begin();
c1.getAdvancedCache().lock("k");
tm.suspend();
// test that both c1 and c2 have locked k
assertLocked(c1, "k");
assertLocked(c2, "k");
cacheManagers.get(0).stop();
TestingUtil.blockUntilViewReceived(c2, 1);
EmbeddedCacheManager cacheManager = c2.getCacheManager();
assert cacheManager.getMembers().size() == 1;
// may take a while from when the view change is seen through to when the lock is cleared
TestingUtil.sleepThread(1000);
assertNotLocked(c2, "k");
}
private void assertLocked(Cache<String, String> c, String key) throws SystemException, NotSupportedException {
TransactionManager tm = TestingUtil.getTransactionManager(c);
tm.begin();
try {
c.put(key, "dummy"); // should time out
assert false : "Should have been locked!";
} catch (TimeoutException e) {
// ignoring timeout exception
} catch (RemoteException e) {
assert e.getCause() instanceof TimeoutException;
// ignoring timeout exception
} finally {
tm.rollback();
}
}
private void assertNotLocked(Cache<String, String> c, String key) throws SystemException, NotSupportedException {
TransactionManager tm = TestingUtil.getTransactionManager(c);
tm.begin();
try {
c.put(key, "dummy"); // should time out
} catch (TimeoutException e) {
assert false : "Should not have been locked!";
} finally {
tm.rollback();
}
}
}
| 3,150
| 33.25
| 116
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/ReadOnlyTxTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.transaction.Transaction;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.Flag;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.LocalXaTransaction;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.2
*/
@Test (groups = "functional", testName = "tx.ReadOnlyTxTest")
@CleanupAfterMethod
public class ReadOnlyTxTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder configuration = getDefaultClusteredCacheConfig(CacheMode.LOCAL, true);
configuration.transaction().lockingMode(LockingMode.PESSIMISTIC);
configure(configuration);
return TestCacheManagerFactory.createCacheManager(configuration);
}
protected void configure(ConfigurationBuilder builder) {
builder.transaction().useSynchronization(false);
}
public void testSimpleReadOnlTx() throws Exception {
tm().begin();
assert cache.get("k") == null;
Transaction transaction = tm().suspend();
LocalXaTransaction localTransaction = (LocalXaTransaction) txTable().getLocalTransaction(transaction);
assert localTransaction != null && localTransaction.isReadOnly();
}
public void testNotROWhenHasWrites() throws Exception {
tm().begin();
cache.put("k", "v");
assert TestingUtil.extractLockManager(cache).isLocked("k");
Transaction transaction = tm().suspend();
LocalXaTransaction localTransaction = (LocalXaTransaction) txTable().getLocalTransaction(transaction);
assert localTransaction != null && !localTransaction.isReadOnly();
}
public void testROWhenHasOnlyLocksAndReleasedProperly() throws Exception {
cache.put("k", "v");
tm().begin();
cache.getAdvancedCache().withFlags(Flag.FORCE_WRITE_LOCK).get("k");
assert TestingUtil.extractLockManager(cache).isLocked("k");
Transaction transaction = tm().suspend();
LocalXaTransaction localTransaction = (LocalXaTransaction) txTable().getLocalTransaction(transaction);
assert localTransaction != null && localTransaction.isReadOnly();
tm().resume(transaction);
tm().commit();
assert !TestingUtil.extractLockManager(cache).isLocked("k");
}
public void testSingleCommitCommand() throws Exception {
cache.put("k", "v");
CommitCommandCounterInterceptor counterInterceptor = new CommitCommandCounterInterceptor();
extractInterceptorChain(cache).addInterceptor(counterInterceptor, 0);
try {
tm().begin();
AssertJUnit.assertEquals("Wrong value for key k.", "v", cache.get("k"));
tm().commit();
} finally {
extractInterceptorChain(cache).removeInterceptor(counterInterceptor.getClass());
}
AssertJUnit.assertEquals("Wrong number of CommitCommand.", numberCommitCommand(), counterInterceptor.counter.get());
}
protected int numberCommitCommand() {
//in this case, the transactions are committed in 1 phase due to pessimistic locking.
return 0;
}
private TransactionTable txTable() {
return TestingUtil.getTransactionTable(cache);
}
class CommitCommandCounterInterceptor extends DDAsyncInterceptor {
public final AtomicInteger counter = new AtomicInteger(0);
@Override
public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable {
counter.incrementAndGet();
return invokeNext(ctx, command);
}
}
}
| 4,304
| 37.4375
| 122
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/TxListenerInvocationSequenceTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.TransactionCompleted;
import org.infinispan.notifications.cachelistener.annotation.TransactionRegistered;
import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent;
import org.infinispan.notifications.cachelistener.event.TransactionCompletedEvent;
import org.infinispan.notifications.cachelistener.event.TransactionRegisteredEvent;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.org
*/
@Test(groups = "functional", testName = "tx.TxListenerInvocationSequenceTest")
public class TxListenerInvocationSequenceTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cacheConfig = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
createClusteredCaches(2, cacheConfig);
waitForClusterToForm();
}
public void testSameInvokingSequence() {
TxListener l0 = new TxListener(0);
cache(0).addListener(l0);
TxListener l1 = new TxListener(1);
cache(1).addListener(l1);
cache(0).put("k", "v");
assertEquals(l0.log, l1.log);
assertEquals(l0.log,Arrays.asList(TxEvent.STARTED, TxEvent.CREATED, TxEvent.COMPLETED));
}
enum TxEvent {
STARTED, CREATED, COMPLETED
}
@Listener
public static class TxListener {
int cacheIndex;
List<TxEvent> log = new ArrayList<TxEvent>(3);
public TxListener(int cacheIndex) {
this.cacheIndex = cacheIndex;
}
@TransactionRegistered
public void startTx(TransactionRegisteredEvent tre) {
if (!tre.isPre()) log.add(TxEvent.STARTED);
}
@CacheEntryCreated
public void entryCreated(CacheEntryCreatedEvent cec) {
if (cec.isPre()) log.add(TxEvent.CREATED);
}
@TransactionCompleted
public void txCompleted(TransactionCompletedEvent tce) {
if (!tce.isPre()) log.add(TxEvent.COMPLETED);
}
}
}
| 2,456
| 30.909091
| 99
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/FailureDuringPrepareTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.testng.Assert.assertEquals;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.distribution.rehash.XAResourceAdapter;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test(groups = "functional", testName = "tx.FailureDuringPrepareTest")
@CleanupAfterMethod
public class FailureDuringPrepareTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
c.clustering().hash().numOwners(3);
createCluster(c, 3);
waitForClusterToForm();
}
public void testResourceCleanedIfPrepareFails() throws Exception {
runTest(false);
}
public void testResourceCleanedIfPrepareFails2() throws Exception {
runTest(true);
}
private void runTest(boolean multipleResources) throws NotSupportedException, SystemException, RollbackException {
extractInterceptorChain(advancedCache(1)).addInterceptor(new FailInterceptor(), 2);
tm(0).begin();
cache(0).put("k","v");
if (multipleResources) {
tm(0).getTransaction().enlistResource(new XAResourceAdapter());
}
assertEquals(lockManager(0).getNumberOfLocksHeld(), 0);
assertEquals(lockManager(1).getNumberOfLocksHeld(), 0);
assertEquals(lockManager(2).getNumberOfLocksHeld(), 0);
try {
tm(0).commit();
assert false;
} catch (Exception e) {
log.debug("Ignoring expected exception during prepare", e);
}
assertEquals(lockManager(0).getNumberOfLocksHeld(), 0);
assertEquals(lockManager(1).getNumberOfLocksHeld(), 0);
assertEquals(lockManager(2).getNumberOfLocksHeld(), 0);
}
static class FailInterceptor extends DDAsyncInterceptor {
@Override
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable {
return invokeNextAndFinally(ctx, command, (rCtx, rCommand, rv, throwable) -> {
//allow the prepare to succeed then crash
throw new RuntimeException("Induced fault!");
});
}
}
}
| 2,779
| 32.902439
| 117
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/ParticipantFailsAfterPrepareTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.extractLockManager;
import static org.infinispan.tx.recovery.RecoveryTestUtil.beginAndSuspendTx;
import static org.infinispan.tx.recovery.RecoveryTestUtil.commitTransaction;
import static org.infinispan.tx.recovery.RecoveryTestUtil.prepareTransaction;
import static org.testng.AssertJUnit.assertEquals;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.MagicKey;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.TransactionTable;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
*/
@Test(groups = "functional", testName = "tx.ParticipantFailsAfterPrepareTest")
@CleanupAfterMethod
public class ParticipantFailsAfterPrepareTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder configuration = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC);
configuration
.locking()
.useLockStriping(false)
.transaction()
.transactionMode(TransactionMode.TRANSACTIONAL)
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.lockingMode(LockingMode.OPTIMISTIC)
.useSynchronization(false)
.recovery()
.disable()
.clustering()
.stateTransfer()
.fetchInMemoryState(false)
.hash()
.numOwners(3);
createCluster(TestDataSCI.INSTANCE, configuration, 4);
waitForClusterToForm();
}
public void testNonOriginatorPrimaryFailsAfterPrepare() throws Exception {
testNonOriginatorFailsAfterPrepare(1, 1);
}
public void testNonOriginatorBackupFailsAfterPrepare() throws Exception {
testNonOriginatorFailsAfterPrepare(0, 2);
}
private void testNonOriginatorFailsAfterPrepare(int primaryOwnerIndex, int toKillIndex) throws Exception {
Address originator = address(0);
Address primaryOwner = address(primaryOwnerIndex);
Address toKill = address(toKillIndex);
MagicKey key = new MagicKey(cache(primaryOwnerIndex), cache(toKillIndex));
Cache<Object, Object> originatorCache = cache(0);
DistributionManager dm0 = advancedCache(0).getDistributionManager();
EmbeddedTransaction dummyTransaction = beginAndSuspendTx(originatorCache, key);
prepareTransaction(dummyTransaction);
log.debugf("Killing %s, key owners are %s", toKill, dm0.getCacheTopology().getWriteOwners(key));
killMember(toKillIndex);
log.debugf("Killed %s, key owners are %s", toKill, dm0.getCacheTopology().getWriteOwners(key));
for (Cache<Object, Object> c : caches()) {
if (!address(c).equals(originator)) {
TransactionTable nonOwnerTxTable = TestingUtil.extractComponent(c, TransactionTable.class);
assertEquals(1, nonOwnerTxTable.getRemoteGlobalTransaction().size());
}
// If the primary owner changes, the lock is not re-acquired on the new primary owner
// However, the old primary owner doesn't release the lock - it's just ignored by new transactions
boolean expectLocked = address(c).equals(primaryOwner);
boolean locked = extractLockManager(c).isLocked(key);
log.tracef("On %s, locked = %s", address(c), locked);
assertEquals(expectLocked, locked);
}
log.trace("About to commit. Killed node is: " + toKill);
commitTransaction(dummyTransaction);
//now check whether all caches have the same content and no locks acquired
for (Cache<?, ?> c : caches()) {
// If the new owner becomes the primary, it will release the key asynchronously
assertEventuallyNotLocked(c, key);
assertEquals(1, c.keySet().size());
}
}
}
| 4,438
| 41.682692
| 109
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/NoRecoveryManagerByDefaultTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.getCacheObjectName;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import javax.management.ObjectName;
import org.infinispan.commons.jmx.MBeanServerLookup;
import org.infinispan.commons.jmx.TestMBeanServerLookup;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.TransactionMode;
import org.testng.annotations.Test;
/**
* Ensures that there is no recovery manager registered in JMX by default.
*
* @author Manik Surtani
* @since 5.2
*/
@Test(testName = "tx.NoRecoveryManagerByDefaultTest", groups = "functional")
public class NoRecoveryManagerByDefaultTest extends SingleCacheManagerTest {
private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create();
public void testNoRecoveryManager() {
assertTrue(cache.getCacheConfiguration().transaction().transactionMode().isTransactional());
String jmxDomain = cacheManager.getCacheManagerConfiguration().jmx().domain();
ObjectName recoveryManager = getCacheObjectName(jmxDomain, cache.getName() + "(local)", "RecoveryManager");
assertFalse(mBeanServerLookup.getMBeanServer().isRegistered(recoveryManager));
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder().nonClusteredDefault();
gcb.jmx().enabled(true).mBeanServerLookup(mBeanServerLookup);
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
return TestCacheManagerFactory.createCacheManager(gcb, cb);
}
}
| 1,975
| 41.956522
| 113
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/SimpleLockTest.java
|
package org.infinispan.tx;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
@Test (testName = "tx.SimpleLockTest", groups = "functional")
public class SimpleLockTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
final ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
c.transaction().lockingMode(LockingMode.PESSIMISTIC);
createCluster(TestDataSCI.INSTANCE, c, 2);
waitForClusterToForm();
}
public void testA() throws Exception {
Object a = getKeyForCache(1);
tm(0).begin();
cache(0).put("x", "b");
advancedCache(0).lock(a);
assertKeyLockedCorrectly(a);
tm(0).commit();
}
}
| 989
| 30.935484
| 95
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/LargeTransactionTest.java
|
package org.infinispan.tx;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* Test for: https://jira.jboss.org/jira/browse/ISPN-149.
*
* @author Mircea.Markus@jboss.com
*/
@Test(testName = "tx.LargeTransactionTest", groups = "functional")
public class LargeTransactionTest extends MultipleCacheManagersTest {
private static final Log log = LogFactory.getLog(LargeTransactionTest.class);
public static final String TEST_CACHE = "TestCache";
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder c = new ConfigurationBuilder();
c.clustering().cacheMode(CacheMode.REPL_SYNC)
.remoteTimeout(30000)
.transaction().transactionMode(TransactionMode.TRANSACTIONAL)
.invocationBatching().enable()
.locking().lockAcquisitionTimeout(60000).useLockStriping(false);
EmbeddedCacheManager container = TestCacheManagerFactory.createClusteredCacheManager(c);
container.start();
registerCacheManager(container);
container.defineConfiguration(TEST_CACHE, c.build());
container.startCaches(TEST_CACHE);
Cache cache1 = container.getCache(TEST_CACHE);
assert cache1.getCacheConfiguration().clustering().cacheMode().equals(CacheMode.REPL_SYNC);
cache1.start();
container = TestCacheManagerFactory.createClusteredCacheManager(c);
container.start();
registerCacheManager(container);
container.defineConfiguration(TEST_CACHE, c.build());
container.startCaches(TEST_CACHE);
Cache cache2 = container.getCache(TEST_CACHE);
assert cache2.getCacheConfiguration().clustering().cacheMode().equals(CacheMode.REPL_SYNC);
}
public void testLargeTx() throws Exception {
Cache cache1 = cache(0, TEST_CACHE);
Cache cache2 = cache(1, TEST_CACHE);
TransactionManager tm = TestingUtil.getTransactionManager(cache1);
tm.begin();
for (int i = 0; i < 200; i++)
cache1.put("key" + i, "value" + i);
log.trace("___________ before commit");
tm.commit();
for (int i = 0; i < 200; i++) {
assert cache2.get("key" + i).equals("value"+i);
}
}
public void testSinglePutInTx() throws Exception {
Cache cache1 = cache(0, TEST_CACHE);
Cache cache2 = cache(1, TEST_CACHE);
TransactionManager tm = TestingUtil.getTransactionManager(cache1);
tm.begin();
cache1.put("key", "val");
log.trace("___________ before commit");
tm.commit();
assert cache2.get("key").equals("val");
}
public void testSimplePutNoTx() {
Cache cache1 = cache(0, TEST_CACHE);
Cache cache2 = cache(1, TEST_CACHE);
cache1.put("key", "val");
assert cache2.get("key").equals("val");
}
}
| 3,278
| 36.261364
| 97
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/LocalModeTxTest.java
|
package org.infinispan.tx;
import static org.infinispan.test.TestingUtil.getTransactionTable;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.impl.TransactionTable;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "tx.LocalModeTxTest")
public class LocalModeTxTest extends SingleCacheManagerTest {
protected StorageType storage;
@Factory
public Object[] factory() {
return new Object[] {
new LocalModeTxTest().withStorage(StorageType.BINARY),
new LocalModeTxTest().withStorage(StorageType.OBJECT),
new LocalModeTxTest().withStorage(StorageType.OFF_HEAP)
};
}
@Override
protected EmbeddedCacheManager createCacheManager() {
ConfigurationBuilder configuration = getDefaultStandaloneCacheConfig(true);
configuration.memory().storageType(storage);
EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(configuration);
cache = cm.getCache();
return cm;
}
public LocalModeTxTest withStorage(StorageType storage) {
this.storage = storage;
return this;
}
@Override
protected String parameters() {
return "[storage=" + storage + "]";
}
public void testTxCommit1() throws Exception {
TransactionManager tm = TestingUtil.getTransactionManager(cache);
tm.begin();
cache.put("key", "value");
Transaction t = tm.suspend();
assertTrue(cache.isEmpty());
tm.resume(t);
tm.commit();
assertFalse(cache.isEmpty());
}
public void testTxCommit3() throws Exception {
TransactionManager tm = TestingUtil.getTransactionManager(cache);
tm.begin();
cache.put("key", "value");
tm.commit();
assertFalse(cache.isEmpty());
}
public void testNonTx() throws Exception {
cache.put("key", "value");
assertFalse(cache.isEmpty());
}
public void testTxCommit2() throws Exception {
TransactionManager tm = TestingUtil.getTransactionManager(cache);
cache.put("key", "old");
tm.begin();
assertEquals("old", cache.get("key"));
cache.put("key", "value");
assertEquals("value", cache.get("key"));
Transaction t = tm.suspend();
assertEquals("old", cache.get("key"));
tm.resume(t);
tm.commit();
assertEquals("value", cache.get("key"));
assertFalse(cache.isEmpty());
}
public void testKeySet() throws Exception {
tm().begin();
cache.put("k1", "v1");
cache.put("k2", "v2");
assertEquals(2, cache.keySet().size());
assertEquals(2, cache.values().size());
tm().commit();
assertEquals(2, cache.keySet().size());
assertEquals(2, cache.values().size());
}
public void testKeySet2() throws Exception {
cache.put("k1", "v1");
cache.put("k2", "v2");
assertEquals(2, cache.keySet().size());
assertEquals(2, cache.values().size());
tm().begin();
assertEquals(2, cache.keySet().size());
assertEquals(2, cache.values().size());
cache.remove("k1");
assertEquals(1, cache.keySet().size());
assertEquals(1, cache.values().size());
tm().rollback();
assertEquals(2, cache.keySet().size());
assertEquals(2, cache.values().size());
}
public void testKeySetAlterValue() throws Exception {
cache.put("k1", "v1");
cache.put("k2", "v2");
assertEquals(2, cache.keySet().size());
assertEquals(2, cache.values().size());
tm().begin();
assertEquals(2, cache.keySet().size());
assertEquals(2, cache.values().size());
cache.put("k1", "v3");
assertEquals(2, cache.keySet().size());
assertEquals(2, cache.values().size());
assert cache.values().contains("v3");
tm().rollback();
assertEquals(2, cache.keySet().size());
assertEquals(2, cache.values().size());
}
public void testTxCleanupWithKeySet() throws Exception {
tm().begin();
assertEquals(0, cache.keySet().size());
TransactionTable txTable = getTransactionTable(cache);
assertEquals(1, txTable.getLocalTransactions().size());
tm().commit();
assertEquals(0, txTable.getLocalTransactions().size());
}
public void testTxCleanupWithEntrySet() throws Exception {
tm().begin();
assertEquals(0, cache.entrySet().size());
TransactionTable txTable = getTransactionTable(cache);
assertEquals(1, txTable.getLocalTransactions().size());
tm().commit();
assertEquals(0, txTable.getLocalTransactions().size());
}
public void testTxCleanupWithValues() throws Exception {
tm().begin();
assertEquals(0, cache.values().size());
TransactionTable txTable = getTransactionTable(cache);
assertEquals(1, txTable.getLocalTransactions().size());
tm().commit();
assertEquals(0, txTable.getLocalTransactions().size());
}
public void testTxCleanupWithSize() throws Exception {
tm().begin();
assertEquals(0, cache.size());
TransactionTable txTable = getTransactionTable(cache);
assertEquals(1, txTable.getLocalTransactions().size());
tm().commit();
assertEquals(0, txTable.getLocalTransactions().size());
}
}
| 5,812
| 32.601156
| 90
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.