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/persistence/support/EnsureNonBlockingStore.java
|
package org.infinispan.persistence.support;
import java.util.concurrent.CompletionStage;
import java.util.function.Predicate;
import jakarta.transaction.Transaction;
import org.infinispan.commons.test.BlockHoundHelper;
import org.infinispan.commons.util.IntSet;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.persistence.spi.InitializationContext;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.persistence.spi.NonBlockingStore;
import org.reactivestreams.Publisher;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
public class EnsureNonBlockingStore<K, V> extends WaitDelegatingNonBlockingStore<K, V> {
public EnsureNonBlockingStore(NonBlockingStore<K, V> delegate, KeyPartitioner keyPartitioner) {
super(delegate, keyPartitioner);
}
@Override
public CompletionStage<Void> start(InitializationContext ctx) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().start(ctx));
}
@Override
public CompletionStage<Void> stop() {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().stop());
}
@Override
public CompletionStage<Boolean> isAvailable() {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().isAvailable());
}
@Override
public CompletionStage<MarshallableEntry<K, V>> load(int segment, Object key) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().load(segment, key));
}
@Override
public CompletionStage<Boolean> containsKey(int segment, Object key) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().containsKey(segment, key));
}
@Override
public CompletionStage<Void> write(int segment, MarshallableEntry<? extends K, ? extends V> entry) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().write(segment, entry));
}
@Override
public CompletionStage<Boolean> delete(int segment, Object key) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().delete(segment, key));
}
@Override
public CompletionStage<Void> addSegments(IntSet segments) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().addSegments(segments));
}
@Override
public CompletionStage<Void> removeSegments(IntSet segments) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().removeSegments(segments));
}
@Override
public CompletionStage<Void> clear() {
return BlockHoundHelper.ensureNonBlocking(delegate()::clear);
}
@Override
public CompletionStage<Void> batch(int publisherCount, Publisher<NonBlockingStore.SegmentedPublisher<Object>> removePublisher,
Publisher<NonBlockingStore.SegmentedPublisher<MarshallableEntry<K, V>>> writePublisher) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().batch(publisherCount, removePublisher, writePublisher));
}
@Override
public CompletionStage<Long> size(IntSet segments) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().size(segments));
}
@Override
public CompletionStage<Long> approximateSize(IntSet segments) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().approximateSize(segments));
}
@Override
public Publisher<MarshallableEntry<K, V>> publishEntries(IntSet segments, Predicate<? super K> filter, boolean includeValues) {
return BlockHoundHelper.ensureNonBlocking(() ->
Flowable.fromPublisher(delegate().publishEntries(segments, filter, includeValues))
.subscribeOn(Schedulers.from(BlockHoundHelper.ensureNonBlockingExecutor()))
);
}
@Override
public Publisher<K> publishKeys(IntSet segments, Predicate<? super K> filter) {
return BlockHoundHelper.ensureNonBlocking(() ->
Flowable.fromPublisher(delegate().publishKeys(segments, filter))
.subscribeOn(Schedulers.from(BlockHoundHelper.ensureNonBlockingExecutor()))
);
}
@Override
public Publisher<MarshallableEntry<K, V>> purgeExpired() {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().purgeExpired());
}
@Override
public CompletionStage<Void> prepareWithModifications(Transaction transaction, int publisherCount,
Publisher<SegmentedPublisher<Object>> removePublisher,
Publisher<SegmentedPublisher<MarshallableEntry<K, V>>> writePublisher) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().prepareWithModifications(transaction, publisherCount,
removePublisher, writePublisher));
}
@Override
public CompletionStage<Void> commit(Transaction transaction) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().commit(transaction));
}
@Override
public CompletionStage<Void> rollback(Transaction transaction) {
return BlockHoundHelper.ensureNonBlocking(() -> delegate().rollback(transaction));
}
}
| 4,931
| 37.232558
| 130
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/support/AsyncStoreEvictionTest.java
|
package org.infinispan.persistence.support;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.Cache;
import org.infinispan.commons.configuration.BuiltBy;
import org.infinispan.commons.configuration.ConfigurationFor;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.configuration.cache.AsyncStoreConfiguration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.persistence.dummy.DummyInMemoryStore;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfiguration;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.CacheManagerCallable;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "persistence.decorators.AsyncStoreEvictionTest")
public class AsyncStoreEvictionTest extends AbstractInfinispanTest {
// set to false to fix all the tests
private static final boolean USE_ASYNC_STORE = true;
private static ConfigurationBuilder config(boolean passivation, int threads) {
ConfigurationBuilder config = new ConfigurationBuilder();
config.expiration().wakeUpInterval(100);
config.memory().size(1);
config.persistence()
.passivation(passivation)
.addStore(LockableStoreConfigurationBuilder.class)
.async()
.enabled(USE_ASYNC_STORE);
return config;
}
private final static ThreadLocal<LockableStore> STORE = new ThreadLocal<LockableStore>();
public static class LockableStoreConfigurationBuilder extends DummyInMemoryStoreConfigurationBuilder {
public LockableStoreConfigurationBuilder(PersistenceConfigurationBuilder builder) {
super(builder);
}
@Override
public LockableStoreConfiguration create() {
return new LockableStoreConfiguration(attributes.protect(), async.create());
}
}
@ConfigurationFor(LockableStore.class)
@BuiltBy(LockableStoreConfigurationBuilder.class)
public static class LockableStoreConfiguration extends DummyInMemoryStoreConfiguration {
public LockableStoreConfiguration(AttributeSet attributes, AsyncStoreConfiguration async) {
super(attributes, async);
}
}
public static class LockableStore extends DummyInMemoryStore {
private volatile CompletableFuture<Void> future = CompletableFutures.completedNull();
public LockableStore() {
super();
STORE.set(this);
}
@Override
public CompletionStage<Void> write(int segment, MarshallableEntry entry) {
return future.thenCompose(ignore -> super.write(segment, entry));
}
@Override
public CompletionStage<Boolean> delete(int segment, Object key) {
return future.thenCompose(ignore -> super.delete(segment, key));
}
}
private static abstract class CacheCallable extends CacheManagerCallable {
protected final Cache<String, String> cache;
protected final LockableStore store;
CacheCallable(ConfigurationBuilder builder) {
super(TestCacheManagerFactory.createCacheManager(builder));
cache = cm.getCache();
store = STORE.get();
}
}
public void testEndToEndEvictionPassivation() throws Exception {
testEndToEndEviction(true);
}
public void testEndToEndEviction() throws Exception {
testEndToEndEviction(false);
}
private void testEndToEndEviction(boolean passivation) throws Exception {
TestingUtil.withCacheManager(new CacheCallable(config(passivation, 1)) {
@Override
public void call() {
store.future = new CompletableFuture<>();
try {
cache.put("k1", "v1");
cache.put("k2", "v2"); // force eviction of "k1"
TestingUtil.sleepThread(100); // wait until the only AsyncProcessor thread is blocked
cache.put("k3", "v3");
cache.put("k4", "v4"); // force eviction of "k3"
assert "v3".equals(cache.get("k3")) : "cache must return k3 == v3 (was: " + cache.get("k3") + ")";
} finally {
store.future.complete(null);
}
}
});
}
public void testEndToEndUpdatePassivation() throws Exception {
testEndToEndUpdate(true);
}
public void testEndToEndUpdate() throws Exception {
testEndToEndUpdate(false);
}
private void testEndToEndUpdate(boolean passivation) throws Exception {
TestingUtil.withCacheManager(new CacheCallable(config(passivation, 1)) {
@Override
public void call() {
cache.put("k1", "v0");
cache.put("k2", "v2"); // force eviction of "k1"
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
return store.loadEntry("k1") != null;
}
});
// simulate slow back end store
store.future = new CompletableFuture<>();
try {
cache.put("k3", "v3");
cache.put("k4", "v4"); // force eviction of "k3"
TestingUtil.sleepThread(100); // wait until the only AsyncProcessor thread is blocked
cache.put("k1", "v1");
cache.put("k5", "v5"); // force eviction of "k1"
assert "v1".equals(cache.get("k1")) : "cache must return k1 == v1 (was: " + cache.get("k1") + ")";
} finally {
store.future.complete(null);
}
}
});
}
public void testEndToEndRemovePassivation() throws Exception {
testEndToEndRemove(true);
}
public void testEndToEndRemove() throws Exception {
testEndToEndRemove(false);
}
private void testEndToEndRemove(boolean passivation) throws Exception {
TestingUtil.withCacheManager(new CacheCallable(config(passivation, 2)) {
@Override
public void call() {
cache.put("k1", "v1");
cache.put("k2", "v2"); // force eviction of "k1"
eventually(() -> store.loadEntry("k1") != null);
// simulate slow back end store
store.future = new CompletableFuture<>();
try {
cache.remove("k1");
TestingUtil.sleepThread(100); // wait until the first AsyncProcessor thread is blocked
cache.remove("k1"); // make second AsyncProcessor thread burn asyncProcessorIds
TestingUtil.sleepThread(200); // wait for reaper to collect InternalNullEntry
assert null == cache.get("k1") : "cache must return k1 == null (was: " + cache.get("k1") + ")";
} finally {
store.future.complete(null);
}
}
});
}
public void testNPE() throws Exception {
TestingUtil.withCacheManager(new CacheCallable(config(false, 1)) {
@Override
public void call() {
cache.put("k1", "v1");
cache.remove("k1");
// this causes NPE in AsyncCacheWriter.isLocked(InternalNullEntry.getKey())
cache.put("k2", "v2");
}
});
}
public void testLIRS() throws Exception {
ConfigurationBuilder config = config(false, 1);
config.memory().size(1);
TestingUtil.withCacheManager(new CacheCallable(config) {
@Override
public void call() {
cache.put("k1", "v1");
cache.put("k2", "v2");
cache.put("k1", "v3");
cache.put("k2", "v4");
cache.put("k3", "v3");
cache.put("k4", "v4");
}
});
}
public void testSize() throws Exception {
TestingUtil.withCacheManager(new CacheCallable(config(false, 1)) {
@Override
public void call() {
cache.put("k1", "v1");
cache.put("k2", "v2");
assertEquals("cache size must be 1", 1, cache.getAdvancedCache().getDataContainer().size());
}
});
}
public void testSizeAfterExpiration() throws Exception {
TestingUtil.withCacheManager(new CacheCallable(config(false, 1)) {
@Override
public void call() {
cache.put("k1", "v1");
cache.put("k2", "v2");
TestingUtil.sleepThread(200);
assertFalse("expiry doesn't work even after expiration", 2 == cache.getAdvancedCache().getDataContainer().size());
}
});
}
public void testSizeAfterEvict() throws Exception {
TestingUtil.withCacheManager(new CacheCallable(config(false, 1)) {
@Override
public void call() {
cache.put("k1", "v1");
cache.evict("k1");
assertEquals("cache size must be 0", 0, cache.getAdvancedCache().getDataContainer().size());
}
});
}
public void testSizeAfterRemove() throws Exception {
TestingUtil.withCacheManager(new CacheCallable(config(false, 1)) {
@Override
public void call() {
cache.put("k1", "v1");
cache.remove("k1");
assertEquals("cache size must be 0", 0, cache.getAdvancedCache().getDataContainer().size());
}
});
}
}
| 9,730
| 35.309701
| 126
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/support/BatchAsyncStoreTest.java
|
package org.infinispan.persistence.support;
import java.util.HashMap;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.util.Util;
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.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* BatchAsyncStoreTest performs some additional tests on the AsyncCacheWriter
* but using batches.
*
* @author Sanne Grinovero
* @since 4.1
*/
@Test(groups = "functional", testName = "persistence.decorators.BatchAsyncStoreTest")
public class BatchAsyncStoreTest extends SingleCacheManagerTest {
private final HashMap<Object, Object> cacheCopy = new HashMap<Object, Object>();
private String tmpDirectory;
public BatchAsyncStoreTest() {
cleanup = CleanupPhase.AFTER_METHOD;
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault();
globalBuilder.globalState().enable().persistentLocation(tmpDirectory);
ConfigurationBuilder configuration = new ConfigurationBuilder();
configuration.invocationBatching().enable();
enableTestJdbcStorage(configuration);
return TestCacheManagerFactory.createCacheManager(globalBuilder, configuration);
}
private void enableTestJdbcStorage(ConfigurationBuilder configuration) throws Exception {
configuration
.persistence()
.addSingleFileStore()
.async()
.enable();
}
@Test
public void sequentialOverwritingInBatches() {
cache = cacheManager.getCache();
AdvancedCache<Object,Object> advancedCache = cache.getAdvancedCache();
for (int i = 0; i < 2000;) {
advancedCache.startBatch();
putAValue(advancedCache, i++);
putAValue(advancedCache, i++);
advancedCache.endBatch(true);
}
cacheCopy.putAll(cache);
cache.stop();
cacheManager.stop();
}
private void putAValue(AdvancedCache<Object, Object> advancedCache, int i) {
String key = "k" + (i % 13);
String value = "V" + i;
advancedCache.put(key, value);
}
@Test(dependsOnMethods = "sequentialOverwritingInBatches")
public void indexWasStored() {
cache = cacheManager.getCache();
Assert.assertEquals(0, cache.getAdvancedCache().getDataContainer().size());
boolean failed = false;
for (Object key : cacheCopy.keySet()) {
Object expected = cacheCopy.get(key);
Object actual = cache.get(key);
if (!expected.equals(actual)) {
log.errorf("Failure on key '%s' expected value: '%s' actual value: '%s'", key.toString(), expected, actual);
failed = true;
}
}
Assert.assertFalse(failed);
Assert.assertEquals(cacheCopy.keySet().size(), cache.keySet().size(), "have a different number of keys");
}
@BeforeClass(alwaysRun = true)
protected void setUpTempDir() {
tmpDirectory = CommonsTestingUtil.tmpDirectory(this.getClass());
}
@AfterClass(alwaysRun = true)
protected void clearTempDir() {
Util.recursiveFileRemove(tmpDirectory);
}
}
| 3,566
| 33.631068
| 120
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/support/AsyncStoreTest.java
|
package org.infinispan.persistence.support;
import static org.infinispan.test.TestingUtil.k;
import static org.infinispan.test.TestingUtil.v;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import java.lang.reflect.Method;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.commons.test.TestResourceTracker;
import org.infinispan.commons.util.IntSets;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.marshall.TestObjectStreamMarshaller;
import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil;
import org.infinispan.persistence.async.AsyncNonBlockingStore;
import org.infinispan.persistence.dummy.DummyInMemoryStore;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.infinispan.persistence.spi.InitializationContext;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.persistence.spi.PersistenceException;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.CacheManagerCallable;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.test.fwk.TestInternalCacheEntryFactory;
import org.infinispan.util.PersistenceMockUtil;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "persistence.support.AsyncStoreTest")
public class AsyncStoreTest extends AbstractInfinispanTest {
private static final Log log = LogFactory.getLog(AsyncStoreTest.class);
private AsyncNonBlockingStore<Object, Object> store;
private TestObjectStreamMarshaller marshaller;
private InitializationContext createStore() throws PersistenceException {
ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false);
DummyInMemoryStoreConfigurationBuilder dummyCfg = builder
.persistence()
.addStore(DummyInMemoryStoreConfigurationBuilder.class)
.storeName(AsyncStoreTest.class.getName())
.segmented(false);
dummyCfg
.async()
.enable();
InitializationContext ctx = PersistenceMockUtil.createContext(getClass(), builder.build(), marshaller);
DummyInMemoryStore underlying = new DummyInMemoryStore();
store = new AsyncNonBlockingStore(underlying);
CompletionStages.join(store.start(ctx));
return ctx;
}
@BeforeMethod
public void createMarshalledEntryFactory() {
marshaller = new TestObjectStreamMarshaller();
}
@AfterMethod
public void tearDown() throws PersistenceException {
if (store != null) CompletionStages.join(store.stop());
marshaller.stop();
}
@Test(timeOut=30000)
public void testPutRemove() throws Exception {
TestResourceTracker.testThreadStarted(this.getTestName());
createStore();
final int number = 1000;
String key = "testPutRemove-k-";
String value = "testPutRemove-v-";
doTestPut(number, key, value);
doTestRemove(number, key);
}
@Test(timeOut=30000)
public void testRepeatedPutRemove() throws Exception {
TestResourceTracker.testThreadStarted(this.getTestName());
createStore();
final int number = 10;
final int loops = 2000;
String key = "testRepeatedPutRemove-k-";
String value = "testRepeatedPutRemove-v-";
int failures = 0;
for (int i = 0; i < loops; i++) {
try {
doTestPut(number, key, value);
doTestRemove(number, key);
} catch (Error e) {
failures++;
}
}
assertEquals(0, failures);
}
@Test(timeOut=30000)
public void testPutClearPut() throws Exception {
TestResourceTracker.testThreadStarted(this.getTestName());
createStore();
final int number = 1000;
String key = "testPutClearPut-k-";
String value = "testPutClearPut-v-";
doTestPut(number, key, value);
doTestClear(number, key);
value = "testPutClearPut-v[2]-";
doTestPut(number, key, value);
doTestRemove(number, key);
}
@Test(timeOut=30000)
public void testRepeatedPutClearPut() throws Exception {
TestResourceTracker.testThreadStarted(this.getTestName());
createStore();
final int number = 10;
final int loops = 2000;
String key = "testRepeatedPutClearPut-k-";
String value = "testRepeatedPutClearPut-v-";
String value2 = "testRepeatedPutClearPut-v[2]-";
int failures = 0;
for (int i = 0; i < loops; i++) {
try {
doTestPut(number, key, value);
doTestClear(number, key);
doTestPut(number, key, value2);
} catch (Error e) {
failures++;
}
}
assertEquals(0, failures);
}
@Test(timeOut=30000)
public void testMultiplePutsOnSameKey() throws Exception {
TestResourceTracker.testThreadStarted(this.getTestName());
createStore();
final int number = 1000;
String key = "testMultiplePutsOnSameKey-k";
String value = "testMultiplePutsOnSameKey-v-";
doTestSameKeyPut(number, key, value);
doTestSameKeyRemove(key);
}
@Test(timeOut=30000)
public void testRestrictionOnAddingToAsyncQueue() throws Exception {
TestResourceTracker.testThreadStarted(this.getTestName());
InitializationContext ctx = createStore();
store.delete(0, "blah");
final int number = 10;
String key = "testRestrictionOnAddingToAsyncQueue-k";
String value = "testRestrictionOnAddingToAsyncQueue-v-";
doTestPut(number, key, value);
// stop the cache store
CompletionStages.join(store.stop());
try {
store.write(0, MarshalledEntryUtil.create("k", marshaller));
fail("Should have restricted this entry from being made");
}
catch (CacheException expected) {
}
// clean up
CompletionStages.join(store.start(ctx));
doTestRemove(number, key);
}
private void doTestPut(int number, String key, String value) {
for (int i = 0; i < number; i++) {
InternalCacheEntry cacheEntry = TestInternalCacheEntryFactory.create(key + i, value + i);
store.write(0, MarshalledEntryUtil.create(cacheEntry, marshaller));
}
for (int i = 0; i < number; i++) {
MarshallableEntry me = CompletionStages.join(store.load(0, key + i));
assertNotNull(me);
assertEquals(value + i, me.getValue());
}
}
private void doTestSameKeyPut(int number, String key, String value) {
for (int i = 0; i < number; i++) {
store.write(0, MarshalledEntryUtil.create(key, value + i, marshaller));
}
MarshallableEntry me = CompletionStages.join(store.load(0, key));
assertNotNull(me);
assertEquals(value + (number - 1), me.getValue());
}
private void doTestRemove(final int number, final String key) throws Exception {
for (int i = 0; i < number; i++) store.delete(0, key + i);
for (int i = 0; i < number; i++) assertNull(CompletionStages.join(store.load(0, key + i)));
}
private void doTestSameKeyRemove(String key) {
store.delete(0, key);
assertNull(CompletionStages.join(store.load(0, key)));
}
private void doTestClear(int number, String key) throws Exception {
CompletionStages.join(store.clear());
for (int i = 0; i < number; i++) {
assertNull(CompletionStages.join(store.load(0, key + i)));
}
}
public void testModificationQueueSize(final Method m) throws Exception {
int queueSize = 5;
DelayStore underlying = new DelayStore();
ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false);
builder.persistence()
.addStore(DelayStore.ConfigurationBuilder.class)
.async()
.modificationQueueSize(queueSize);
store = new AsyncNonBlockingStore<>(underlying);
InitializationContext ctx = PersistenceMockUtil.createContext(getClass(), builder.build(), marshaller);
CompletionStages.join(store.start(ctx));
// Delay all the underlying store completions until we complete this future
underlying.delayAfterModification(queueSize + 2);
try {
CountDownLatch queueFullLatch = new CountDownLatch(1);
Future<Void> f = fork(() -> {
// Fill the modifications queue
for (int i = 0; i < queueSize; i++)
CompletionStages.join(store.write(0, MarshalledEntryUtil.create(k(m, i), v(m, i), marshaller)));
// The next one should block
// The first modification is already replicating, but the store still counts it against the queue size
CompletionStage<Void> blockedWrite =
store.write(0, MarshalledEntryUtil.create(k(m, queueSize + 1), v(m, queueSize + 1), marshaller));
assertFalse(blockedWrite.toCompletableFuture().isDone());
queueFullLatch.countDown();
CompletionStages.join(blockedWrite);
});
assertTrue(queueFullLatch.await(10, TimeUnit.SECONDS));
Thread.sleep(50);
assertFalse(f.isDone());
// Size currently doesn't look at the pending replication queue
assertEquals(1, underlying.size());
assertEquals(1, (long) CompletionStages.join(store.size(IntSets.immutableSet(0))));
// Let the task finish
underlying.endDelay();
f.get(10, TimeUnit.SECONDS);
assertEquals(queueSize + 1, underlying.size());
} finally {
underlying.endDelay();
CompletionStages.join(store.stop());
}
}
private static abstract class OneEntryCacheManagerCallable extends CacheManagerCallable {
protected final Cache<String, String> cache;
protected final DelayStore store;
private static ConfigurationBuilder config(boolean passivation) {
ConfigurationBuilder config = new ConfigurationBuilder();
config.memory().maxCount(1)
.persistence().passivation(passivation)
.addStore(DelayStore.ConfigurationBuilder.class)
.async()
// This cannot be 1. When using passivation in doTestEndToEndPutPut we block a store write to key X.
// This would then mean we have a batch of 1 we would not allow any subsequent writes to complete
// as they will be enqueued. This allows us to let the test block passivation but continue.
.modificationQueueSize(2)
.enable();
return config;
}
OneEntryCacheManagerCallable(boolean passivation) {
super(TestCacheManagerFactory.createCacheManager(config(passivation)));
cache = cm.getCache();
store = TestingUtil.getFirstStore(cache);
}
}
public void testEndToEndPutPutPassivation() throws Exception {
doTestEndToEndPutPut(true);
}
public void testEndToEndPutPut() throws Exception {
doTestEndToEndPutPut(false);
}
private void doTestEndToEndPutPut(boolean passivation) throws Exception {
TestingUtil.withCacheManager(new OneEntryCacheManagerCallable(passivation) {
@Override
public void call() throws InterruptedException {
cache.put("X", "1");
cache.put("Y", "1"); // force eviction of "X"
// wait for X to appear in store
eventually(() -> store.loadEntry("X") != null);
// simulate slow back end store
store.delayAfterModification(3);
try {
cache.put("X", "2");
// Needs to be in other thread as non blocking store is invoked in same thread
CompletionStage<String> stage = cache.putAsync("Y", "2"); // force eviction of "X"
if (!passivation) {
CompletionStages.join(stage);
cache.putAsync("Z", "1"); // force eviction of "Y"
}
assertEquals("2", cache.get("X"));
if (!passivation) {
assertEquals("1", cache.get("Z"));
}
} finally {
store.endDelay();
}
}
});
}
public void testEndToEndPutRemovePassivation() throws Exception {
doTestEndToEndPutRemove(true);
}
public void testEndToEndPutRemove() throws Exception {
doTestEndToEndPutRemove(false);
}
private void doTestEndToEndPutRemove(boolean passivation) throws Exception {
TestingUtil.withCacheManager(new OneEntryCacheManagerCallable(passivation) {
@Override
public void call() throws InterruptedException {
cache.put("X", "1");
cache.put("Y", "1"); // force eviction of "X"
// wait for X to appear in store
eventually(() -> store.loadEntry("X") != null);
// simulate slow back end store
store.delayAfterModification(3);
try {
cache.put("replicating", "completes, but replication is stuck on delayed Future");
if (!passivation) {
cache.put("in-queue", "completes, but waiting on previous replication to complete before replicating");
}
// Needs to be in other thread as non blocking store is invoked in same thread
Future<Void> f = fork(() -> {
// This will not return since the replication queue is full from in-queue
cache.remove("X");
});
Exceptions.expectException(TimeoutException.class, () -> f.get(100, TimeUnit.MILLISECONDS));
} finally {
store.endDelay();
}
}
});
}
}
| 14,610
| 36.560411
| 121
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/support/DelayStore.java
|
package org.infinispan.persistence.support;
import static org.testng.AssertJUnit.assertTrue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import org.infinispan.commons.configuration.BuiltBy;
import org.infinispan.commons.configuration.ConfigurationFor;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.util.IntSet;
import org.infinispan.configuration.cache.AsyncStoreConfiguration;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.persistence.dummy.DummyInMemoryStore;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfiguration;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Flowable;
/**
* Test store that can delay store operations (or their completion).
*
* @author Dan Berindei
* @since 13.0
*/
public class DelayStore extends DummyInMemoryStore {
private static final Log log = LogFactory.getLog(DelayStore.class);
private final AtomicInteger delayBeforeModificationCount = new AtomicInteger();
private final AtomicInteger delayAfterModificationCount = new AtomicInteger();
private final AtomicInteger delayBeforeEmitCount = new AtomicInteger();
private volatile CompletableFuture<Void> delayFuture = CompletableFutures.completedNull();
public void delayBeforeModification(int count) {
assertTrue(delayFuture.isDone());
delayFuture = new CompletableFuture<>();
delayBeforeModificationCount.set(count);
}
public void delayAfterModification(int count) {
assertTrue(delayFuture.isDone());
delayFuture = new CompletableFuture<>();
delayAfterModificationCount.set(count);
}
public void delayBeforeEmit(int count) {
assertTrue(delayFuture.isDone());
delayFuture = new CompletableFuture<>();
delayBeforeEmitCount.set(count);
}
public void endDelay() {
CompletableFuture<Void> oldFuture = delayFuture;
if (oldFuture.isDone())
return;
log.tracef("Resuming delayed store operations");
delayFuture = CompletableFutures.completedNull();
oldFuture.complete(null);
}
@Override
public CompletionStage<Void> write(int segment, MarshallableEntry entry) {
CompletionStage<Void> stage = CompletableFutures.completedNull();
if (!delayFuture.isDone() && delayBeforeModificationCount.decrementAndGet() >= 0) {
log.tracef("Delaying before write to %s", entry.getKey());
stage = delayFuture;
}
stage = stage.thenCompose(__ -> super.write(segment, entry));
if (!delayFuture.isDone() && delayAfterModificationCount.decrementAndGet() >= 0) {
log.tracef("Delaying after write to %s", entry.getKey());
stage = stage.thenCompose(ignore -> delayFuture.thenRun(() -> {
log.tracef("Resuming write to %s", entry.getKey());
}));
}
return stage;
}
@Override
public CompletionStage<Boolean> delete(int segment, Object key) {
CompletionStage<Boolean> stage = CompletableFutures.completedNull();
if (!delayFuture.isDone() && delayBeforeModificationCount.decrementAndGet() >= 0) {
log.tracef("Delaying before write to %s", key);
stage = delayFuture.thenApply(__ -> true);
}
stage = stage.thenCompose(__ -> super.delete(segment, key));
if (!delayFuture.isDone() && delayAfterModificationCount.decrementAndGet() >= 0) {
log.tracef("Delaying after write to %s", key);
stage = stage.thenCompose(removed -> delayFuture.thenApply(__ -> {
log.tracef("Resuming write to %s", key);
return removed;
}));
}
return stage;
}
@Override
public Flowable<MarshallableEntry> publishEntries(IntSet segments, Predicate filter, boolean fetchValue) {
return super.publishEntries(segments, filter, fetchValue)
.delay(me -> {
if (!delayFuture.isDone() && delayBeforeEmitCount.decrementAndGet() >= 0) {
return Completable.fromCompletionStage(delayFuture).toFlowable();
} else {
return Flowable.empty();
}
});
}
@BuiltBy(ConfigurationBuilder.class)
@ConfigurationFor(DelayStore.class)
public static class Configuration extends DummyInMemoryStoreConfiguration {
public Configuration(AttributeSet attributes, AsyncStoreConfiguration async) {
super(attributes, async);
}
}
public static class ConfigurationBuilder extends DummyInMemoryStoreConfigurationBuilder {
public ConfigurationBuilder(PersistenceConfigurationBuilder builder) {
super(builder);
}
@Override
public Configuration create() {
return new Configuration(attributes.protect(), async.create());
}
}
}
| 5,299
| 36.588652
| 109
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/support/ReplAsyncStoreTest.java
|
package org.infinispan.persistence.support;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.distribution.MagicKey;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* @author wburns
* @since 9.4
*/
@Test(groups = "functional", testName = "persistence.support.ReplAsyncStoreTest")
public class ReplAsyncStoreTest extends MultipleCacheManagersTest {
protected final String CACHE_NAME = "testCache";
private boolean shared;
ReplAsyncStoreTest shared(boolean shared) {
this.shared = shared;
return this;
}
enum Op {
SIZE {
@Override
void perform(MagicKey key, Cache<MagicKey, String> cache) {
assertEquals(1, cache.size());
}
},
KEY_ITERATOR {
@Override
void perform(MagicKey key, Cache<MagicKey, String> cache) {
Iterator<?> iterator = cache.keySet().iterator();
assertTrue(iterator.hasNext());
assertEquals(key, iterator.next());
assertFalse(iterator.hasNext());
}
},
ENTRY_COLLECT {
@Override
void perform(MagicKey key, Cache<MagicKey, String> cache) {
List<Map.Entry<MagicKey, String>> list = cache.entrySet().stream().collect(Collectors::toList);
assertEquals(1, list.size());
assertEquals(key, list.get(0).getKey());
}
}
;
abstract void perform(MagicKey key, Cache<MagicKey, String> cache);
}
@Override
public Object[] factory() {
return new Object[] {
new ReplAsyncStoreTest().shared(false),
new ReplAsyncStoreTest().shared(true),
};
}
@Override
protected String[] parameterNames() {
return new String[] { "shared" };
}
@Override
protected Object[] parameterValues() {
return new Object[] { shared };
}
@Override
protected void createCacheManagers() throws Throwable {
org.infinispan.configuration.cache.ConfigurationBuilder
cfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true);
cfg.persistence()
.addStore(DelayStore.ConfigurationBuilder.class)
.storeName(shared ? ReplAsyncStoreTest.class.getName() : null)
.shared(shared)
.async().enable();
createClusteredCaches(3, CACHE_NAME, TestDataSCI.INSTANCE, cfg);
waitForClusterToForm(CACHE_NAME);
}
@DataProvider(name = "async-ops")
public Object[][] asyncOperationProvider() {
// Now smash all those ops with a true and false for using primary
return Stream.of(Op.values()).flatMap(op ->
Stream.of(true, false).map(bool -> new Object[] { bool, op }))
.toArray(Object[][]::new);
}
@Test(dataProvider = "async-ops")
public void testOperationAfterInsertAndEvict(boolean primary, Op consumer) {
Cache<MagicKey, String> primaryOwner = cache(0, CACHE_NAME);
Cache<MagicKey, String> backupOwner = cache(1, CACHE_NAME);
MagicKey key = getKeyForCache(primaryOwner);
// Delay the underlying store write
DelayStore primaryStore = TestingUtil.getFirstStore(primaryOwner);
primaryStore.delayBeforeModification(1);
DelayStore backupStore = TestingUtil.getFirstStore(backupOwner);
backupStore.delayBeforeModification(1);
primaryOwner.put(key, "some-value");
Cache<MagicKey, String> cacheToUse;
if (primary) {
cacheToUse = primaryOwner;
} else {
cacheToUse = backupOwner;
}
// Evict the key so it only exists in the store
cacheToUse.evict(key);
consumer.perform(key, cacheToUse);
primaryStore.endDelay();
backupStore.endDelay();
}
}
| 4,230
| 29.65942
| 107
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/support/WaitNonBlockingStore.java
|
package org.infinispan.persistence.support;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.infinispan.commons.util.IntSet;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.persistence.spi.InitializationContext;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.persistence.spi.NonBlockingStore;
import org.infinispan.util.concurrent.CompletionStages;
import org.reactivestreams.Publisher;
import io.reactivex.rxjava3.core.Flowable;
public interface WaitNonBlockingStore<K, V> extends NonBlockingStore<K, V> {
KeyPartitioner getKeyPartitioner();
default Boolean delete(Object key) {
int segment = getKeyPartitioner().getSegment(key);
return join(delete(segment, key));
}
default boolean contains(Object key) {
int segment = getKeyPartitioner().getSegment(key);
return join(containsKey(segment, key));
}
default MarshallableEntry<K, V> loadEntry(Object key) {
int segment = getKeyPartitioner().getSegment(key);
return join(load(segment, key));
}
default void write(MarshallableEntry<K, V> entry) {
int segment = getKeyPartitioner().getSegment(entry.getKey());
join(write(segment, entry));
}
default void batchUpdate(int publisherCount, Publisher<SegmentedPublisher<Object>> removePublisher,
Publisher<NonBlockingStore.SegmentedPublisher<MarshallableEntry<K, V>>> writePublisher) {
join(batch(publisherCount, removePublisher, writePublisher));
}
default boolean checkAvailable() {
return join(isAvailable());
}
default long sizeWait(IntSet segments) {
return join(size(segments));
}
default long approximateSizeWait(IntSet segments) {
return join(approximateSize(segments));
}
default void clearAndWait() {
join(clear());
}
default void startAndWait(InitializationContext ctx) {
join(start(ctx));
}
default void stopAndWait() {
join(stop());
}
default List<K> publishKeysWait(IntSet segments, Predicate<? super K> filter) {
return join(Flowable.fromPublisher(publishKeys(segments, filter))
.collect(Collectors.toList())
.toCompletionStage());
}
default List<MarshallableEntry<K, V>> publishEntriesWait(IntSet segments, Predicate<? super K> filter,
boolean includeValues) {
return join(Flowable.fromPublisher(publishEntries(segments, filter, includeValues))
.collect(Collectors.toList())
.toCompletionStage());
}
default List<MarshallableEntry<K, V>> purge() {
return join(Flowable.fromPublisher(purgeExpired())
.collect(Collectors.toList())
.toCompletionStage());
}
// This method is here solely for byte code augmentation with blockhound
default <V> V join(CompletionStage<V> stage) {
return CompletionStages.join(stage);
}
}
| 3,056
| 31.178947
| 105
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/support/FailStore.java
|
package org.infinispan.persistence.support;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import org.infinispan.commons.configuration.BuiltBy;
import org.infinispan.commons.configuration.ConfigurationFor;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.util.IntSet;
import org.infinispan.configuration.cache.AsyncStoreConfiguration;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.persistence.dummy.DummyInMemoryStore;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfiguration;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.test.TestException;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import io.reactivex.rxjava3.core.Flowable;
/**
* Test store that can fail store operations
*
* @author Dan Berindei
* @since 13.0
*/
public class FailStore extends DummyInMemoryStore {
private static final Log log = LogFactory.getLog(FailStore.class);
private final AtomicInteger failModificationCount = new AtomicInteger();
private final AtomicInteger failPublishCount = new AtomicInteger();
public void failModification(int count) {
failModificationCount.set(count);
}
public void failPublish(int count) {
failPublishCount.set(count);
}
@Override
public CompletionStage<Void> write(int segment, MarshallableEntry entry) {
if (failModificationCount.decrementAndGet() >= 0) {
log.tracef("Delaying before write to %s", entry.getKey());
return CompletableFuture.failedFuture(new TestException("Simulated write failure"));
}
return super.write(segment, entry);
}
@Override
public CompletionStage<Boolean> delete(int segment, Object key) {
if (failModificationCount.decrementAndGet() >= 0) {
log.tracef("Delaying before write to %s", key);
return CompletableFuture.failedFuture(new TestException("Simulated write failure"));
}
return super.delete(segment, key);
}
@Override
public Flowable<MarshallableEntry> publishEntries(IntSet segments, Predicate filter, boolean fetchValue) {
if (failPublishCount.decrementAndGet() >= 0) {
return Flowable.error(new TestException("Simulated subscribe failure"));
}
return super.publishEntries(segments, filter, fetchValue);
}
@BuiltBy(ConfigurationBuilder.class)
@ConfigurationFor(FailStore.class)
public static class Configuration extends DummyInMemoryStoreConfiguration {
public Configuration(AttributeSet attributes, AsyncStoreConfiguration async) {
super(attributes, async);
}
}
public static class ConfigurationBuilder extends DummyInMemoryStoreConfigurationBuilder {
public ConfigurationBuilder(PersistenceConfigurationBuilder builder) {
super(builder);
}
@Override
public Configuration create() {
return new Configuration(attributes.protect(), async.create());
}
}
}
| 3,265
| 34.89011
| 109
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/support/WaitDelegatingNonBlockingStore.java
|
package org.infinispan.persistence.support;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.persistence.spi.NonBlockingStore;
public class WaitDelegatingNonBlockingStore<K, V> extends DelegatingNonBlockingStore<K, V> implements WaitNonBlockingStore<K, V> {
private final NonBlockingStore<K, V> nonBlockingStore;
private final KeyPartitioner keyPartitioner;
public WaitDelegatingNonBlockingStore(NonBlockingStore<K, V> nonBlockingStore, KeyPartitioner keyPartitioner) {
this.nonBlockingStore = nonBlockingStore;
this.keyPartitioner = keyPartitioner;
}
@Override
public NonBlockingStore<K, V> delegate() {
return nonBlockingStore;
}
@Override
public KeyPartitioner getKeyPartitioner() {
return keyPartitioner;
}
}
| 799
| 31
| 130
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/sifs/SoftIndexFileStoreTest.java
|
package org.infinispan.persistence.sifs;
import static org.testng.AssertJUnit.assertNull;
import java.nio.file.Paths;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.persistence.BaseNonBlockingStoreTest;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.persistence.spi.NonBlockingStore;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "persistence.sifs.SoftIndexFileStoreTest")
public class SoftIndexFileStoreTest extends BaseNonBlockingStoreTest {
protected String tmpDirectory;
@BeforeClass(alwaysRun = true)
protected void setUpTempDir() {
tmpDirectory = CommonsTestingUtil.tmpDirectory(getClass());
}
@AfterClass(alwaysRun = true)
protected void clearTempDir() {
Util.recursiveFileRemove(tmpDirectory);
}
@Override
protected NonBlockingStore createStore() {
return new NonBlockingSoftIndexFileStore();
}
@Override
protected Configuration buildConfig(ConfigurationBuilder configurationBuilder) {
return configurationBuilder.persistence()
.addSoftIndexFileStore()
.dataLocation(Paths.get(tmpDirectory, "data").toString())
.indexLocation(Paths.get(tmpDirectory, "index").toString())
.maxFileSize(1000)
.build();
}
// test for ISPN-5753
public void testOverrideWithExpirableAndCompaction() throws InterruptedException {
// write immortal entry
store.write(marshalledEntry(internalCacheEntry("key", "value1", -1)));
writeGibberish(); // make sure that compaction happens - value1 is compacted
store.write(marshalledEntry(internalCacheEntry("key", "value2", 1)));
timeService.advance(2);
writeGibberish(); // make sure that compaction happens - value2 expires
store.stop();
startStore(store);
// value1 has been overwritten and value2 has expired
MarshallableEntry entry = store.loadEntry("key");
assertNull(entry != null ? entry.getKey() + "=" + entry.getValue() : null, entry);
}
private void writeGibberish() {
for (int i = 0; i < 100; ++i) {
store.write(marshalledEntry(internalCacheEntry("foo", "bar", -1)));
store.delete("foo");
}
}
}
| 2,512
| 34.9
| 88
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/sifs/SoftIndexFileStoreSplitInnerNodeTest.java
|
package org.infinispan.persistence.sifs;
import static org.testng.AssertJUnit.assertEquals;
import java.nio.file.Paths;
import org.infinispan.Cache;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "persistence.sifs.SoftIndexFileStoreSplitInnerNodeTest")
public class SoftIndexFileStoreSplitInnerNodeTest extends MultipleCacheManagersTest {
protected String tmpDirectory;
private final int MAX_ENTRIES = 597 + 1;
private static final String CACHE_NAME = "SIFS-Backed";
private Cache<Object, Object> c1;
@BeforeSuite(alwaysRun = true)
protected void setUpTempDir() {
tmpDirectory = CommonsTestingUtil.tmpDirectory(getClass());
}
@AfterSuite(alwaysRun = true)
protected void clearTempDir() {
Util.recursiveFileRemove(tmpDirectory);
}
@Override
protected void createCacheManagers() {
ConfigurationBuilder cb = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
cb.memory().maxCount((long) Math.ceil(MAX_ENTRIES * 0.2))
.persistence().passivation(false)
.addSoftIndexFileStore()
.dataLocation(Paths.get(tmpDirectory, "data").toString())
.indexLocation(Paths.get(tmpDirectory, "index").toString())
.indexSegments(1)
.purgeOnStartup(true)
.preload(false)
.expiration().wakeUpInterval(Long.MAX_VALUE)
.indexing().disable();
createClusteredCaches(2, cb, CACHE_NAME);
c1 = cache(0, CACHE_NAME);
}
/**
* Reproducer for ISPN-13968.
*
* This will create 3 segments in the store. The keys `k367` and `k527` map to segment 0.
* This store segment has two inner nodes. At first, we would try to search the inner node's leaf,
* since we do not find the segment 0 in the leaf, we would skip the complete segment, ignoring some keys.
*
* We added a change to: if the segment is not present in the inner node's leaf, we try the next
* one, if exists any.
*/
public void testPopulatingAndQueryingSize() {
for (int i = 0; i < MAX_ENTRIES; i++) {
c1.put("k" + i, "v" + i);
}
assertEquals(MAX_ENTRIES, c1.size());
}
}
| 2,549
| 34.915493
| 109
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/sifs/SoftIndexFileStoreRestartTest.java
|
package org.infinispan.persistence.sifs;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import org.infinispan.Cache;
import org.infinispan.commons.lambda.NamedLambdas;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.configuration.cache.StoreConfigurationBuilder;
import org.infinispan.distribution.BaseDistStoreTest;
import org.infinispan.persistence.sifs.configuration.DataConfiguration;
import org.infinispan.persistence.support.WaitDelegatingNonBlockingStore;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.concurrent.CompletionStages;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "persistence.sifs.SoftIndexFileStoreRestartTest")
public class SoftIndexFileStoreRestartTest extends BaseDistStoreTest<Integer, String, SoftIndexFileStoreRestartTest> {
protected String tmpDirectory;
protected int fileSize;
{
// We don't really need a cluster
INIT_CLUSTER_SIZE = 1;
l1CacheEnabled = false;
segmented = true;
}
SoftIndexFileStoreRestartTest fileSize(int fileSize) {
this.fileSize = fileSize;
return this;
}
@Override
public Object[] factory() {
return Stream.of(CacheMode.DIST_SYNC, CacheMode.LOCAL)
.flatMap(type ->
Stream.builder()
.add(new SoftIndexFileStoreRestartTest().fileSize(1_000).cacheMode(type))
.add(new SoftIndexFileStoreRestartTest().fileSize(10_000).cacheMode(type))
.add(new SoftIndexFileStoreRestartTest().fileSize(320_000).cacheMode(type))
.add(new SoftIndexFileStoreRestartTest().fileSize(2_000_000).cacheMode(type))
.add(new SoftIndexFileStoreRestartTest().fileSize(DataConfiguration.MAX_FILE_SIZE.getDefaultValue()).cacheMode(type))
.build()
).toArray();
}
@Override
protected String[] parameterNames() {
return concat(super.parameterNames(), "fileSize");
}
@Override
protected Object[] parameterValues() {
return concat(super.parameterValues(), fileSize);
}
@BeforeClass(alwaysRun = true)
@Override
public void createBeforeClass() throws Throwable {
tmpDirectory = CommonsTestingUtil.tmpDirectory(getClass());
super.createBeforeClass();
}
@AfterClass(alwaysRun = true)
@Override
protected void destroy() {
super.destroy();
Util.recursiveFileRemove(tmpDirectory);
}
@Override
protected StoreConfigurationBuilder addStore(PersistenceConfigurationBuilder persistenceConfigurationBuilder, boolean shared) {
// We don't support shared for SIFS
assert !shared;
return persistenceConfigurationBuilder.addSoftIndexFileStore()
// Force some extra files
.maxFileSize(fileSize)
.dataLocation(Paths.get(tmpDirectory, "data").toString())
.indexLocation(Paths.get(tmpDirectory, "index").toString());
}
public void testRestartWithNoIndex() throws Throwable {
int size = 10;
for (int i = 0; i < size; i++) {
cache(0, cacheName).put(i, "value-" + i);
}
assertEquals(size, cache(0, cacheName).size());
// Add in an extra remove to make things more interesting, originally this caused compcation to always error
cache(0, cacheName).remove(4);
killMember(0, cacheName);
// Delete the index which should force it to rebuild
Util.recursiveFileRemove(Paths.get(tmpDirectory, "index"));
createCacheManagers();
assertEquals(size - 1, cache(0, cacheName).size());
for (int i = 0; i < size; i++) {
if (i == 4) {
assertNull(cache(0, cacheName).get(i));
} else {
assertEquals("value-" + i, cache(0, cacheName).get(i));
}
}
}
static <K, V> NonBlockingSoftIndexFileStore<K, V> getStoreFromCache(Cache<K, V> cache) {
WaitDelegatingNonBlockingStore<K, V> storeDel = TestingUtil.getFirstStoreWait(cache);
return (NonBlockingSoftIndexFileStore<K, V>) storeDel.delegate();
}
@DataProvider(name = "restart")
Object[][] restartProvider() {
return new Object[][]{
{NamedLambdas.of("DELETE", () -> {
Path path = Path.of(tmpDirectory, "index", cacheName, "index", "index.stats");
path.toFile().delete();
})},
{NamedLambdas.of("NO-DELETE", () -> {
})}
};
}
@Test(dataProvider = "restart")
public void testStatsUponRestart(Runnable runnable) throws Throwable {
int attempts = 5;
long previousSize = -1;
for (int i = 0; i < attempts; ++i) {
previousSize = performRestart(runnable, previousSize, i);
}
}
long performRestart(Runnable runnable, long previousUsedSize, int iterationCount) throws Throwable {
log.debugf("Iteration: %s", iterationCount);
int size = 10;
Cache<Integer, String> cache = cache(0, cacheName);
for (int i = 0; i < size; i++) {
// Skip a different insert each time (after first)
if (iterationCount > 0 && i != iterationCount) {
continue;
}
String prev = cache.put(i, "iteration-" + iterationCount + " value-" + i);
if (iterationCount > 0) {
assertNotNull(prev);
// TODO: https://issues.redhat.com/browse/ISPN-13969 to fix this
// assertEquals("iteration-" + (iterationCount - 1) + " value-" + i, prev);
}
}
assertEquals(size, cache.size());
killMember(0, cacheName);
long actualSize = SoftIndexFileStoreTestUtils.dataDirectorySize(tmpDirectory, cacheName);
SoftIndexFileStoreTestUtils.StatsValue stats = SoftIndexFileStoreTestUtils.readStatsFile(tmpDirectory, cacheName, log);
assertEquals(actualSize, stats.getStatsSize());
// Make sure the previous size is the same
if (previousUsedSize >= 0) {
assertEquals("Restart attempt: " + iterationCount, previousUsedSize, actualSize - stats.getFreeSize());
}
runnable.run();
// Recreate the cache manager for next run(s)
createCacheManagers();
return actualSize - stats.getFreeSize();
}
@DataProvider(name = "booleans")
Object[][] booleans() {
return new Object[][]{
{Boolean.TRUE}, {Boolean.FALSE}};
}
@Test(dataProvider = "booleans")
public void testRestartWithEntryUpdatedMultipleTimes(boolean leafOrNode) throws Throwable {
// Current serialized size is 54 bytes, so this number has to be large enough to cause a file to fill to
// actually compact something
int size = 20;
String key = "compaction";
// We want to test both a leaf and node storage on the root node
int extraInserts = leafOrNode ? size : size * 256;
for (int i = 0; i < extraInserts; i++) {
// Have some extra entries which prevent it from running compaction at beginning
cache(0, cacheName).put(i, "value-" + i);
}
for (int i = 0; i < size; i++) {
cache(0, cacheName).put(key, "value-" + i);
}
assertEquals(extraInserts + 1, cache(0, cacheName).size());
cache(0, cacheName).remove(3);
killMember(0, cacheName);
// NOTE: we keep the index, so we ensure upon restart that it is correct
long actualSize = SoftIndexFileStoreTestUtils.dataDirectorySize(tmpDirectory, cacheName);
SoftIndexFileStoreTestUtils.StatsValue stats = SoftIndexFileStoreTestUtils.readStatsFile(tmpDirectory, cacheName, log);
assertEquals(actualSize, stats.getStatsSize());
createCacheManagers();
WaitDelegatingNonBlockingStore store = TestingUtil.getFirstStoreWait(cache(0, cacheName));
Compactor compactor = TestingUtil.extractField(store.delegate(), "compactor");
// Force compaction for the previous file
CompletionStages.join(compactor.forceCompactionForAllNonLogFiles());
assertEquals("value-" + (size - 1), cache(0, cacheName).get(key));
killMember(0, cacheName);
actualSize = SoftIndexFileStoreTestUtils.dataDirectorySize(tmpDirectory, cacheName);
stats = SoftIndexFileStoreTestUtils.readStatsFile(tmpDirectory, cacheName, log);
assertEquals(actualSize, stats.getStatsSize());
// Other tests need a cache manager still
createCacheManagers();
}
}
| 8,920
| 35.863636
| 141
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/sifs/SoftIndexFileStoreTestUtils.java
|
package org.infinispan.persistence.sifs;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import org.infinispan.util.logging.Log;
public class SoftIndexFileStoreTestUtils {
public static class StatsValue {
private final long freeSize;
private final long statsSize;
public long getFreeSize() {
return freeSize;
}
public long getStatsSize() {
return statsSize;
}
private StatsValue(long freeSize, long statsSize) {
this.freeSize = freeSize;
this.statsSize = statsSize;
}
}
public static StatsValue readStatsFile(String tmpDirectory, String cacheName, Log log) throws IOException {
long statsSize = 0;
long freeSize = 0;
try (FileChannel statsChannel = new RandomAccessFile(
Path.of(tmpDirectory, "index", cacheName, "index", "index.stats").toFile(), "r").getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate(4 + 4 + 4 + 8);
while (Index.read(statsChannel, buffer)) {
buffer.flip();
// Ignore id
int file = buffer.getInt();
int length = buffer.getInt();
int free = buffer.getInt();
// Ignore expiration
buffer.getLong();
buffer.flip();
statsSize += length;
freeSize += free;
log.debugf("File: %s Length: %s free: %s", file, length, free);
}
}
return new StatsValue(freeSize, statsSize);
}
public static long dataDirectorySize(String tmpDirectory, String cacheName) {
Path dataPath = Path.of(tmpDirectory, "data", cacheName, "data");
File[] dataFiles = dataPath.toFile().listFiles();
long length = 0;
for (File file : dataFiles) {
length += file.length();
}
return length;
}
}
| 1,962
| 27.867647
| 110
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/sifs/SoftIndexFileStoreFileStatsTest.java
|
package org.infinispan.persistence.sifs;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Paths;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.time.ControlledTimeService;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.persistence.support.WaitDelegatingNonBlockingStore;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.concurrent.BlockingManagerTestUtil;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "persistence.sifs.SoftIndexFileStoreFileStatsTest")
public class SoftIndexFileStoreFileStatsTest extends SingleCacheManagerTest {
protected String tmpDirectory;
@BeforeClass(alwaysRun = true)
protected void setUpTempDir() {
tmpDirectory = CommonsTestingUtil.tmpDirectory(getClass());
}
@AfterClass(alwaysRun = true)
protected void clearTempDir() {
Util.recursiveFileRemove(tmpDirectory);
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
GlobalConfigurationBuilder global = new GlobalConfigurationBuilder();
global.globalState().persistentLocation(CommonsTestingUtil.tmpDirectory(this.getClass()));
return TestCacheManagerFactory.newDefaultCacheManager(true, global, new ConfigurationBuilder());
}
protected PersistenceConfigurationBuilder createCacheStoreConfig(PersistenceConfigurationBuilder persistence) {
persistence
.addSoftIndexFileStore()
.dataLocation(Paths.get(tmpDirectory, "data").toString())
.indexLocation(Paths.get(tmpDirectory, "index").toString())
.maxFileSize(1000)
.purgeOnStartup(false)
// Effectively disable reaper for tests
.expiration().wakeUpInterval(Long.MAX_VALUE);
return persistence;
}
void configureCache(String cacheName) {
ConfigurationBuilder cb = new ConfigurationBuilder();
createCacheStoreConfig(cb.persistence());
TestingUtil.defineConfiguration(cacheManager, cacheName, cb.build());
}
ControlledTimeService defineCacheConfigurationAndInjectTimeService(String cacheName) {
configureCache(cacheName);
ControlledTimeService controlledTimeService = new ControlledTimeService();
TimeService prev = TestingUtil.replaceComponent(cacheManager, TimeService.class, controlledTimeService, true);
controlledTimeService.setActualTimeService(prev);
return controlledTimeService;
}
static class MyCompactionObserver implements Compactor.CompactionExpirationSubscriber {
private final BlockingQueue<Object> syncQueue;
private final CountDownLatch completionLatch = new CountDownLatch(1);
private volatile Throwable error;
MyCompactionObserver(BlockingQueue<Object> syncQueue) {
this.syncQueue = syncQueue;
}
@Override
public void onEntryPosition(EntryPosition entryPosition) throws IOException {
try {
log.trace("EntryPosition found: " + entryPosition);
syncQueue.offer(entryPosition, 10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new IOException(e);
}
}
@Override
public void onEntryEntryRecord(EntryRecord entryRecord) throws IOException {
try {
log.trace("EntryRecord found: " + entryRecord);
syncQueue.offer(entryRecord, 10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new IOException(e);
}
}
@Override
public void onComplete() {
log.trace("Expiration compaction completed");
completionLatch.countDown();
}
@Override
public void onError(Throwable t) {
log.warn("Throwable encountered: ", t);
error = t;
completionLatch.countDown();
}
void waitForCompletion() throws InterruptedException {
assertTrue(completionLatch.await(10, TimeUnit.SECONDS));
if (error != null) {
throw new AssertionError(error);
}
}
}
Map.Entry<Integer, Compactor.Stats> extractCompletedStat(ConcurrentMap<Integer, Compactor.Stats> statsMap) {
Map.Entry<Integer, Compactor.Stats> completedStats = null;
for (Map.Entry<Integer, Compactor.Stats> entry : statsMap.entrySet()) {
if (entry.getValue().isCompleted()) {
if (completedStats != null) {
fail("More than one stat was completed: " + statsMap);
}
completedStats = entry;
}
}
return completedStats;
}
@Test(dataProvider = "booleans")
public void testOverwriteLogFileSize(Method m, boolean performExpirationAfterFirst) throws InterruptedException {
String cacheName = m.getName() + "-" + performExpirationAfterFirst;
configureCache(cacheName);
BlockingManagerTestUtil.replaceManagersWithInline(cacheManager);
Cache<String, Object> cache = cacheManager.getCache(cacheName);
cache.start();
WaitDelegatingNonBlockingStore store = TestingUtil.getFirstStoreWait(cache);
Compactor compactor = TestingUtil.extractField(store.delegate(), "compactor");
ConcurrentMap<Integer, Compactor.Stats> statsMap = compactor.getFileStats();
cache.put("k1", "v1");
cache.put("k1", "v1");
if (performExpirationAfterFirst) {
MyCompactionObserver myCompactionObserver = new MyCompactionObserver(new ArrayBlockingQueue<>(5));
compactor.performExpirationCompaction(myCompactionObserver);
myCompactionObserver.waitForCompletion();
}
assertEquals(1, statsMap.size());
Map.Entry<Integer, Compactor.Stats> entry = statsMap.entrySet().iterator().next();
int maxInserts = 100;
int insertions = 0;
while (statsMap.containsKey(entry.getKey())) {
cache.put("k1", "v1");
if (++insertions == maxInserts) {
fail("Failed to remove stats map after " + maxInserts + " stats were: " + statsMap);
}
}
}
@DataProvider(name = "booleans")
public static Object[][] booleans() {
return new Object[][]{{Boolean.FALSE}, {Boolean.TRUE}};
}
@Test(dataProvider = "booleans")
public void testExpirationStats(Method m, boolean extraRemovedEntry) throws InterruptedException {
String cacheName = m.getName() + "-" + extraRemovedEntry;
ControlledTimeService controlledTimeService = defineCacheConfigurationAndInjectTimeService(cacheName);
BlockingManagerTestUtil.replaceManagersWithInline(cacheManager);
try {
Cache<String, Object> cache = cacheManager.getCache(cacheName);
cache.start();
WaitDelegatingNonBlockingStore store = TestingUtil.getFirstStoreWait(cache);
Compactor compactor = TestingUtil.extractField(store.delegate(), "compactor");
ConcurrentMap<Integer, Compactor.Stats> statsMap = compactor.getFileStats();
cache.put("k1", "v1", 3, TimeUnit.MILLISECONDS);
long expectedExpirationTime = controlledTimeService.wallClockTime() + 3;
assertEquals(0, statsMap.size());
// This causes the logFile to be added to the statsMap before expiration compaction
if (extraRemovedEntry) {
cache.put("removed", "remove-me");
cache.remove("removed");
assertEquals(1, statsMap.size());
Compactor.Stats stat = statsMap.values().iterator().next();
int freeAmount = stat.getFree();
assertTrue("Something should have been freed", freeAmount != 0);
}
controlledTimeService.advance(4);
BlockingQueue<Object> queue = new ArrayBlockingQueue<>(10);
MyCompactionObserver myCompactionObserver = new MyCompactionObserver(queue);
compactor.performExpirationCompaction(myCompactionObserver);
// Due to inline BlockingManager will be done on same thread so already finished
myCompactionObserver.waitForCompletion();
assertEquals(1, queue.size());
assertEquals(1, statsMap.size());
Compactor.Stats stat = statsMap.values().iterator().next();
int freeAmount = stat.getFree();
assertTrue("Something should have been freed", freeAmount != 0);
int i = 1;
// Fill it up until we have 1 complete logFile, 1 compacted file and 1 logFile
Map.Entry<Integer, Compactor.Stats> entry;
while ((entry = extractCompletedStat(statsMap)) == null) {
cache.put("k" + i, "v" + i, 4, TimeUnit.MILLISECONDS);
i++;
if (i > 100) {
fail("Shouldn't require 100 iterations...");
}
}
Compactor.Stats completedStats = entry.getValue();
assertTrue("Stats were: " + completedStats, completedStats.getFree() > 0);
assertEquals(expectedExpirationTime, completedStats.getNextExpirationTime());
assertFalse(completedStats.isScheduled());
// Now we remove the other values until the file gets compacted
for (int j = 1; j < i; ++j) {
cache.remove("k" + j);
if (!statsMap.containsKey(entry.getKey())) {
completedStats = null;
break;
}
}
assertNull("File " + entry.getKey() + " was still not removed... stats were: " + statsMap, completedStats);
} finally {
TestingUtil.replaceComponent(cacheManager, TimeService.class, controlledTimeService.getActualTimeService(), true);
}
}
}
| 10,641
| 37.981685
| 123
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/sifs/SoftIndexFileStoreCompatibilityTest.java
|
package org.infinispan.persistence.sifs;
import static org.infinispan.persistence.sifs.NonBlockingSoftIndexFileStore.PREFIX_10_1;
import static org.infinispan.persistence.sifs.NonBlockingSoftIndexFileStore.PREFIX_11_0;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletionException;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.persistence.IdentityKeyValueWrapper;
import org.infinispan.persistence.AbstractPersistenceCompatibilityTest;
import org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfigurationBuilder;
import org.infinispan.test.data.Value;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Tests if {@link NonBlockingSoftIndexFileStore} can migrate data from Infinispan 10.1.x.
*
* @author Pedro Ruivo
* @since 11.0
*/
@Test(groups = "functional", testName = "persistence.sifs.SoftIndexFileStoreCompatibilityTest")
public class SoftIndexFileStoreCompatibilityTest extends AbstractPersistenceCompatibilityTest<Value> {
private static final Map<Version, VersionMeta> data = new HashMap<>(2);
static {
data.put(Version._10_1, new VersionMeta("sifs/10_1_x_sifs_data", PREFIX_10_1));
data.put(Version._11_0, new VersionMeta("sifs/11_0_x_sifs_data", PREFIX_11_0));
}
public SoftIndexFileStoreCompatibilityTest() {
super(IdentityKeyValueWrapper.instance());
}
@Override
protected void amendGlobalConfigurationBuilder(GlobalConfigurationBuilder builder) {
super.amendGlobalConfigurationBuilder(builder);
builder.globalState().persistentLocation(CommonsTestingUtil.tmpDirectory());
}
@Override
protected void beforeStartCache() throws Exception {
Path dataLocation = getStoreLocation(combinePath(tmpDirectory, "data"), "data");
Path indexLocation = getStoreLocation(combinePath(tmpDirectory, "index"), "index");
dataLocation.toFile().mkdirs();
indexLocation.toFile().mkdirs();
data.get(oldVersion).copyFiles(dataLocation, indexLocation);
}
@Override
protected String cacheName() {
return "sifs-store-cache";
}
@Override
protected void configurePersistence(ConfigurationBuilder builder, boolean generatingData) {
builder.persistence().addStore(SoftIndexFileStoreConfigurationBuilder.class)
.segmented(newSegmented)
.dataLocation(combinePath(tmpDirectory, "data"))
.indexLocation(combinePath(tmpDirectory, "index"));
}
@DataProvider
public Object[][] segmented() {
return new Object[][] {
{false, true},
{true, true},
};
}
@Test(dataProvider = "segmented")
public void testReadWriteFrom101(boolean oldSegmented, boolean newSegmented) throws Exception {
setParameters(Version._10_1, oldSegmented, newSegmented);
beforeStartCache();
cacheManager.defineConfiguration(cacheName(), cacheConfiguration(false).build());
Exceptions.expectException(CacheConfigurationException.class, CompletionException.class, ".*ISPN000616.*",
() -> cacheManager.getCache(cacheName()));
}
@Test(dataProvider = "segmented")
public void testReadWriteFrom11(boolean oldSegmented, boolean newSegmented) throws Exception {
setParameters(Version._11_0, oldSegmented, newSegmented);
doTestReadWrite();
}
static class VersionMeta {
final String root;
final String prefix;
VersionMeta(String root, String prefix) {
this.root = root;
this.prefix = prefix;
}
void copyFiles(Path dataLocation, Path indexLocation) throws IOException {
String dataPath = String.format("%s/data/%s", root, prefix + 0);
copyFile(dataPath, dataLocation, prefix + 0);
for (int i = 0; i < 3; i++) {
String indexFile = "index." + i;
String indexPath = String.format("%s/index/%s", root, indexFile);
copyFile(indexPath, indexLocation, indexFile);
}
}
}
}
| 4,337
| 35.453782
| 112
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/sifs/SoftIndexFileStoreFunctionalTest.java
|
package org.infinispan.persistence.sifs;
import java.nio.file.Paths;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.persistence.BaseStoreFunctionalTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "persistence.sifs.SoftIndexFileStoreFunctionalTest")
public class SoftIndexFileStoreFunctionalTest extends BaseStoreFunctionalTest {
protected String tmpDirectory;
@BeforeClass(alwaysRun = true)
protected void setUpTempDir() {
tmpDirectory = CommonsTestingUtil.tmpDirectory(getClass());
}
@AfterClass(alwaysRun = true)
protected void clearTempDir() {
Util.recursiveFileRemove(tmpDirectory);
}
@Override
protected PersistenceConfigurationBuilder createCacheStoreConfig(PersistenceConfigurationBuilder persistence,
String cacheName, boolean preload) {
persistence
.addSoftIndexFileStore()
.dataLocation(Paths.get(tmpDirectory, "data").toString())
.indexLocation(Paths.get(tmpDirectory, "index").toString())
.purgeOnStartup(false).preload(preload)
// Effectively disable reaper for tests
.expiration().wakeUpInterval(Long.MAX_VALUE);
return persistence;
}
}
| 1,450
| 35.275
| 112
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/persistence/sifs/SoftIndexFileStoreStressTest.java
|
package org.infinispan.persistence.sifs;
import static org.testng.AssertJUnit.assertEquals;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.infinispan.Cache;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.persistence.support.WaitDelegatingNonBlockingStore;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestBlocking;
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 = "stress", testName = "persistence.sifs.SoftIndexFileStoreStressTest")
public class SoftIndexFileStoreStressTest extends SingleCacheManagerTest {
private static final String CACHE_NAME = "stress-test-cache";
protected String tmpDirectory;
@BeforeClass(alwaysRun = true)
protected void setUpTempDir() {
tmpDirectory = CommonsTestingUtil.tmpDirectory(getClass());
}
@AfterClass(alwaysRun = true, dependsOnMethods = "destroyAfterClass")
protected void clearTempDir() throws IOException {
SoftIndexFileStoreTestUtils.StatsValue statsValue = SoftIndexFileStoreTestUtils.readStatsFile(tmpDirectory, CACHE_NAME, log);
long dataDirectorySize = SoftIndexFileStoreTestUtils.dataDirectorySize(tmpDirectory, CACHE_NAME);
assertEquals(dataDirectorySize, statsValue.getStatsSize());
Util.recursiveFileRemove(tmpDirectory);
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
GlobalConfigurationBuilder global = new GlobalConfigurationBuilder();
global.globalState().persistentLocation(CommonsTestingUtil.tmpDirectory(this.getClass()));
global.cacheContainer().security().authorization().enable();
return TestCacheManagerFactory.newDefaultCacheManager(false, global, new ConfigurationBuilder());
}
protected PersistenceConfigurationBuilder createCacheStoreConfig(PersistenceConfigurationBuilder persistence, String cacheName, boolean preload) {
persistence
.addSoftIndexFileStore()
.dataLocation(Paths.get(tmpDirectory, "data").toString())
.indexLocation(Paths.get(tmpDirectory, "index").toString())
.maxFileSize(1000)
.async().enabled(true)
.purgeOnStartup(false).preload(preload)
// Effectively disable reaper for tests
.expiration().wakeUpInterval(Long.MAX_VALUE);
return persistence;
}
public void testConstantReadsWithCompaction() throws InterruptedException, ExecutionException, TimeoutException {
ConfigurationBuilder cb = TestCacheManagerFactory.getDefaultCacheConfiguration(false);
createCacheStoreConfig(cb.persistence(), CACHE_NAME, false);
TestingUtil.defineConfiguration(cacheManager, CACHE_NAME, cb.build());
Cache<String, Object> cache = cacheManager.getCache(CACHE_NAME);
cache.start();
int numKeys = 22;
for (int i = 0; i < numKeys; ++i) {
cache.put("key-" + i, "value-" + i);
}
WaitDelegatingNonBlockingStore<?, ?> store = TestingUtil.getFirstStoreWait(cache);
Compactor compactor = TestingUtil.extractField(store.delegate(), "compactor");
AtomicBoolean continueRunning = new AtomicBoolean(true);
Future<Void> retrievalFork = fork(() -> {
while (continueRunning.get()) {
int i = ThreadLocalRandom.current().nextInt(numKeys);
assertEquals("value-" + i, cache.get("key-" + i));
}
});
Future<Void> writeFork = fork(() -> {
while (continueRunning.get()) {
int i = ThreadLocalRandom.current().nextInt(numKeys);
String sb = i +
"vjaofijeawofiejafioeh23uh123eu213heu1he u1ni 1uh13iueh 1iuehn12ujhen12ujhn2112w!@KEO@J!E I!@JEIO! J@@@E1j ie1jvjaofijeawofiejafioeha".repeat(i);
cache.put("k" + i, sb);
}
});
Future<Void> removeFork = fork(() -> {
while (continueRunning.get()) {
int i = ThreadLocalRandom.current().nextInt(numKeys);
cache.remove("k" + i);
}
});
Future<Void> compactionFork = fork(() -> {
while (continueRunning.get()) {
try {
compactor.forceCompactionForAllNonLogFiles()
.toCompletableFuture().get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
throw e;
}
}
});
long startTime = System.nanoTime();
long secondsToRun = TimeUnit.MINUTES.toSeconds(2);
while (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime) < secondsToRun) {
if (retrievalFork.isDone() || compactionFork.isDone() || writeFork.isDone() || removeFork.isDone()) {
continueRunning.set(false);
break;
}
TestingUtil.sleepThread(200);
}
continueRunning.set(false);
try {
TestBlocking.get(retrievalFork, 10, TimeUnit.SECONDS);
TestBlocking.get(compactionFork, 10, TimeUnit.SECONDS);
TestBlocking.get(writeFork, 10, TimeUnit.SECONDS);
TestBlocking.get(removeFork, 10, TimeUnit.SECONDS);
} catch (Throwable t) {
log.tracef(Util.threadDump());
throw t;
}
}
}
| 5,935
| 39.657534
| 163
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/expiry/ReplAutoCommitExpiryTest.java
|
package org.infinispan.expiry;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @author wburns
* @since 9.0
*/
@Test(groups = "functional", testName = "expiry.ReplAutoCommitExpiryTest")
public class ReplAutoCommitExpiryTest extends AutoCommitExpiryTest {
protected ReplAutoCommitExpiryTest() {
super(CacheMode.REPL_SYNC, true);
}
}
| 395
| 23.75
| 74
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/expiry/DistNoAutoCommitExpiryTest.java
|
package org.infinispan.expiry;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @author wburns
* @since 9.0
*/
@Test(groups = "functional", testName = "expiry.DistNoAutoCommitExpiryTest")
public class DistNoAutoCommitExpiryTest extends AutoCommitExpiryTest {
protected DistNoAutoCommitExpiryTest() {
super(CacheMode.DIST_SYNC, false);
}
}
| 402
| 24.1875
| 76
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/expiry/ReplicatedExpiryTest.java
|
package org.infinispan.expiry;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.entries.MortalCacheEntry;
import org.infinispan.container.entries.TransientCacheEntry;
import org.infinispan.container.entries.TransientMortalCacheEntry;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "expiry.ReplicatedExpiryTest")
public class ReplicatedExpiryTest extends MultipleCacheManagersTest {
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false);
createClusteredCaches(2, "cache", builder);
}
public void testLifespanExpiryReplicates() {
Cache c1 = cache(0,"cache");
Cache c2 = cache(1,"cache");
long lifespan = 3000;
c1.put("k", "v", lifespan, MILLISECONDS);
InternalCacheEntry ice = c2.getAdvancedCache().getDataContainer().get("k");
assert ice instanceof MortalCacheEntry;
assert ice.getLifespan() == lifespan;
assert ice.getMaxIdle() == -1;
}
public void testIdleExpiryReplicates() {
Cache c1 = cache(0,"cache");
Cache c2 = cache(1,"cache");
long idle = 3000;
c1.put("k", "v", -1, MILLISECONDS, idle, MILLISECONDS);
InternalCacheEntry ice = c2.getAdvancedCache().getDataContainer().get("k");
assert ice instanceof TransientCacheEntry;
assert ice.getMaxIdle() == idle;
assert ice.getLifespan() == -1;
}
public void testBothExpiryReplicates() {
Cache c1 = cache(0,"cache");
Cache c2 = cache(1,"cache");
long lifespan = 10000;
long idle = 3000;
c1.put("k", "v", lifespan, MILLISECONDS, idle, MILLISECONDS);
InternalCacheEntry ice = c2.getAdvancedCache().getDataContainer().get("k");
assert ice instanceof TransientMortalCacheEntry;
assert ice.getLifespan() == lifespan : "Expected " + lifespan + " but was " + ice.getLifespan();
assert ice.getMaxIdle() == idle : "Expected " + idle + " but was " + ice.getMaxIdle();
}
}
| 2,328
| 38.474576
| 102
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/expiry/LocalNoAutoCommitExpiryTest.java
|
package org.infinispan.expiry;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @author wburns
* @since 9.0
*/
@Test(groups = "functional", testName = "expiry.LocalNoAutoCommitExpiryTest")
public class LocalNoAutoCommitExpiryTest extends AutoCommitExpiryTest {
protected LocalNoAutoCommitExpiryTest() {
super(CacheMode.LOCAL, false);
}
}
| 401
| 24.125
| 77
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/expiry/LocalAutoCommitExpiryTest.java
|
package org.infinispan.expiry;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @author wburns
* @since 9.0
*/
@Test(groups = "functional", testName = "expiry.LocalAutoCommitExpiryTest")
public class LocalAutoCommitExpiryTest extends AutoCommitExpiryTest {
protected LocalAutoCommitExpiryTest() {
super(CacheMode.LOCAL, true);
}
}
| 394
| 23.6875
| 75
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/expiry/ReplNoAutoCommitExpiryTest.java
|
package org.infinispan.expiry;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @author wburns
* @since 9.0
*/
@Test(groups = "functional", testName = "expiry.ReplNoAutoCommitExpiryTest")
public class ReplNoAutoCommitExpiryTest extends AutoCommitExpiryTest {
protected ReplNoAutoCommitExpiryTest() {
super(CacheMode.REPL_SYNC, false);
}
}
| 402
| 24.1875
| 76
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/expiry/ExpiryTest.java
|
package org.infinispan.expiry;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.infinispan.test.TestingUtil.v;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.container.DataContainer;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.manager.CacheContainer;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.ControlledTimeService;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "expiry.ExpiryTest")
public class ExpiryTest extends AbstractInfinispanTest {
public static final int EXPIRATION_TIMEOUT = 3000;
public static final int IDLE_TIMEOUT = 3000;
public static final int EXPIRATION_CHECK_TIMEOUT = 2000;
CacheContainer cm;
protected ControlledTimeService timeService;
@BeforeMethod
public void setUp() {
cm = TestCacheManagerFactory.createCacheManager(false);
timeService = new ControlledTimeService();
TestingUtil.replaceComponent(cm, TimeService.class, timeService, true);
}
@AfterMethod
public void tearDown() {
TestingUtil.killCacheManagers(cm);
cm = null;
}
public void testLifespanExpiryInPut() throws InterruptedException {
Cache<String, String> cache = getCache();
long lifespan = EXPIRATION_TIMEOUT;
cache.put("k", "v", lifespan, MILLISECONDS);
DataContainer dc = cache.getAdvancedCache().getDataContainer();
InternalCacheEntry se = dc.get("k");
assert se.getKey().equals("k");
assert se.getValue().equals("v");
assert se.getLifespan() == lifespan;
assert se.getMaxIdle() == -1;
assert !se.isExpired(timeService.wallClockTime());
assert cache.get("k").equals("v");
timeService.advance(lifespan + 100);
assert se.isExpired(timeService.wallClockTime());
assert cache.get("k") == null;
}
protected Cache<String, String> getCache() {
return cm.getCache();
}
public void testIdleExpiryInPut() throws InterruptedException {
Cache<String, String> cache = getCache();
long idleTime = IDLE_TIMEOUT;
cache.put("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS);
DataContainer dc = cache.getAdvancedCache().getDataContainer();
InternalCacheEntry se = dc.get("k");
assert se.getKey().equals("k");
assert se.getValue().equals("v");
assert se.getLifespan() == -1;
assert se.getMaxIdle() == idleTime;
assert !se.isExpired(timeService.wallClockTime());
assert cache.get("k").equals("v");
timeService.advance(idleTime + 100);
assertTrue(se.isExpired(timeService.wallClockTime()));
assertNull(cache.get("k"));
}
public void testLifespanExpiryInPutAll() throws InterruptedException {
Cache<String, String> cache = getCache();
final long lifespan = EXPIRATION_TIMEOUT;
Map<String, String> m = new HashMap();
m.put("k1", "v");
m.put("k2", "v");
cache.putAll(m, lifespan, MILLISECONDS);
String v1 = cache.get("k1");
String v2 = cache.get("k2");
assertEquals("v", v1);
assertEquals("v", v2);
timeService.advance(lifespan + 100);
assertNull(cache.get("k1"));
assertNull(cache.get("k2"));
}
public void testIdleExpiryInPutAll() throws InterruptedException {
Cache<String, String> cache = getCache();
final long idleTime = EXPIRATION_TIMEOUT;
Map<String, String> m = new HashMap<String, String>();
m.put("k1", "v");
m.put("k2", "v");
cache.putAll(m, -1, MILLISECONDS, idleTime, MILLISECONDS);
assertEquals("v", cache.get("k1"));
assertEquals("v", cache.get("k2"));
timeService.advance(idleTime + 100);
assertNull(cache.get("k1"));
assertNull(cache.get("k2"));
}
public void testLifespanExpiryInPutIfAbsent() throws InterruptedException {
Cache<String, String> cache = getCache();
final long lifespan = EXPIRATION_TIMEOUT;
assert cache.putIfAbsent("k", "v", lifespan, MILLISECONDS) == null;
long partial = lifespan / 10;
// Sleep some time within the lifespan boundaries
timeService.advance(lifespan - partial);
assertEquals("v", cache.get("k"));
// Sleep some time that guarantees that it'll be over the lifespan
timeService.advance(lifespan);
assertNull(cache.get("k"));
cache.put("k", "v");
assert cache.putIfAbsent("k", "v", lifespan, MILLISECONDS) != null;
}
public void testIdleExpiryInPutIfAbsent() throws InterruptedException {
Cache<String, String> cache = getCache();
long idleTime = EXPIRATION_TIMEOUT;
assertNull(cache.putIfAbsent("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS));
assertEquals("v", cache.get("k"));
timeService.advance(idleTime + 100);
assertNull(cache.get("k"));
cache.put("k", "v");
assertNotNull(cache.putIfAbsent("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS));
}
public void testLifespanExpiryInReplace() throws InterruptedException {
Cache<String, String> cache = getCache();
final long lifespan = EXPIRATION_TIMEOUT;
assertNull(cache.get("k"));
assertNull(cache.replace("k", "v", lifespan, MILLISECONDS));
assertNull(cache.get("k"));
cache.put("k", "v-old");
assertEquals("v-old", cache.get("k"));
assertNotNull(cache.replace("k", "v", lifespan, MILLISECONDS));
assertEquals("v", cache.get("k"));
timeService.advance(lifespan + 100);
assertNull(cache.get("k"));
cache.put("k", "v");
assertTrue(cache.replace("k", "v", "v2", lifespan, MILLISECONDS));
timeService.advance(lifespan + 100);
assert cache.get("k") == null;
}
public void testIdleExpiryInReplace() throws InterruptedException {
Cache<String, String> cache = getCache();
long idleTime = EXPIRATION_TIMEOUT;
assertNull(cache.get("k"));
assertNull(cache.replace("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS));
assertNull(cache.get("k"));
cache.put("k", "v-old");
assertEquals("v-old", cache.get("k"));
assertNotNull(cache.replace("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS));
assertEquals("v", cache.get("k"));
timeService.advance(idleTime + 100);
assertNull(cache.get("k"));
cache.put("k", "v");
assertTrue(cache.replace("k", "v", "v2", -1, MILLISECONDS, idleTime, MILLISECONDS));
timeService.advance(idleTime + 100);
assertNull(cache.get("k"));
}
@Test
public void testEntrySetAfterExpiryInPut(Method m) throws Exception {
doTestEntrySetAfterExpiryInPut(m, cm);
}
public void testEntrySetAfterExpiryInTransaction(Method m) throws Exception {
CacheContainer cc = createTransactionalCacheContainer();
try {
doEntrySetAfterExpiryInTransaction(m, cc);
} finally {
cc.stop();
}
}
public void testEntrySetAfterExpiryWithStore(Method m) throws Exception {
String location = CommonsTestingUtil.tmpDirectory(ExpiryTest.class);
CacheContainer cc = createCacheContainerWithStore(location);
try {
doTestEntrySetAfterExpiryInPut(m, cc);
} finally {
cc.stop();
Util.recursiveFileRemove(location);
}
}
private CacheContainer createTransactionalCacheContainer() {
CacheContainer cc = TestCacheManagerFactory.createCacheManager(
TestCacheManagerFactory.getDefaultCacheConfiguration(true));
TestingUtil.replaceComponent(cc, TimeService.class, timeService, true);
return cc;
}
private CacheContainer createCacheContainerWithStore(String location) {
GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault();
globalBuilder.globalState().persistentLocation(location);
CacheContainer cc = TestCacheManagerFactory.createCacheManager(globalBuilder, new ConfigurationBuilder());
TestingUtil.replaceComponent(cc, TimeService.class, timeService, true);
return cc;
}
private void doTestEntrySetAfterExpiryInPut(Method m, CacheContainer cc) throws Exception {
Cache<Integer, String> cache = cc.getCache();
Map dataIn = new HashMap();
dataIn.put(1, v(m, 1));
dataIn.put(2, v(m, 2));
final long lifespan = EXPIRATION_TIMEOUT;
cache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);
timeService.advance(lifespan + 100);
assertEquals(0, cache.entrySet().size());
}
private void doEntrySetAfterExpiryInTransaction(Method m, CacheContainer cc) throws Exception {
Cache<Integer, String> cache = cc.getCache();
Set<Map.Entry<Integer, String>> entries;
Map dataIn = new HashMap();
dataIn.put(1, v(m, 1));
dataIn.put(2, v(m, 2));
final long lifespan = EXPIRATION_TIMEOUT;
cache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);
cache.getAdvancedCache().getTransactionManager().begin();
try {
Map txDataIn = new HashMap();
txDataIn.put(3, v(m, 3));
Map allEntriesIn = new HashMap(dataIn);
// Update expectations
allEntriesIn.putAll(txDataIn);
// Add an entry within tx
cache.putAll(txDataIn);
timeService.advance(lifespan + 100);
} finally {
cache.getAdvancedCache().getTransactionManager().commit();
}
assertEquals(1, cache.entrySet().size());
}
public void testKeySetAfterExpiryInPut(Method m) throws Exception {
Cache<Integer, String> cache = cm.getCache();
Map dataIn = new HashMap();
dataIn.put(1, v(m, 1));
dataIn.put(2, v(m, 2));
final long lifespan = EXPIRATION_TIMEOUT;
cache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);
timeService.advance(lifespan + 100);
assertEquals(0, cache.keySet().size());
}
public void testKeySetAfterExpiryInTransaction(Method m) throws Exception {
CacheContainer cc = createTransactionalCacheContainer();
try {
doKeySetAfterExpiryInTransaction(m, cc);
} finally {
cc.stop();
}
}
private void doKeySetAfterExpiryInTransaction(Method m, CacheContainer cc) throws Exception {
Cache<Integer, String> cache = cc.getCache();
Map dataIn = new HashMap();
dataIn.put(1, v(m, 1));
dataIn.put(2, v(m, 2));
final long lifespan = EXPIRATION_TIMEOUT;
cache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);
cache.getAdvancedCache().getTransactionManager().begin();
try {
Map txDataIn = new HashMap();
txDataIn.put(3, v(m, 3));
Map allEntriesIn = new HashMap(dataIn);
// Update expectations
allEntriesIn.putAll(txDataIn);
// Add an entry within tx
cache.putAll(txDataIn);
timeService.advance(lifespan + 100);
} finally {
cache.getAdvancedCache().getTransactionManager().commit();
}
assertEquals(1, cache.keySet().size());
}
public void testValuesAfterExpiryInPut(Method m) throws Exception {
Cache<Integer, String> cache = cm.getCache();
// Values come as a Collection, but comparison of HashMap#Values is done
// by reference equality, so wrap the collection around to set to make
// testing easier, given that we know that there are dup values.
Collection<String> values;
Map<Integer, String> dataIn = new HashMap<>();
dataIn.put(1, v(m, 1));
dataIn.put(2, v(m, 2));
final long lifespan = EXPIRATION_TIMEOUT;
cache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);
timeService.advance(lifespan + 100);
assertEquals(0, cache.values().size());
}
public void testValuesAfterExpiryInTransaction(Method m) throws Exception {
CacheContainer cc = createTransactionalCacheContainer();
try {
doValuesAfterExpiryInTransaction(m, cc);
} finally {
cc.stop();
}
}
public void testTransientEntrypUpdates() {
Cache<Integer, String> cache = cm.getCache();
cache.put(1, "boo", -1, TimeUnit.SECONDS, 10, TimeUnit.SECONDS);
cache.put(1, "boo2");
cache.put(1, "boo3");
}
private void doValuesAfterExpiryInTransaction(Method m, CacheContainer cc) throws Exception {
Cache<Integer, String> cache = cc.getCache();
// Values come as a Collection, but comparison of HashMap#Values is done
// by reference equality, so wrap the collection around to set to make
// testing easier, given that we know that there are dup values.
Collection<String> values;
Map<Integer, String> dataIn = new HashMap<>();
dataIn.put(1, v(m, 1));
dataIn.put(2, v(m, 2));
final long lifespan = EXPIRATION_TIMEOUT;
cache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);
cache.getAdvancedCache().getTransactionManager().begin();
try {
Map<Integer, String> txDataIn = new HashMap<>();
txDataIn.put(3, v(m, 3));
Collection<String> allValuesIn = new ArrayList<>(dataIn.values());
allValuesIn.addAll(txDataIn.values());
// Add an entry within tx
cache.putAll(txDataIn);
timeService.advance(lifespan + 100);
} finally {
cache.getAdvancedCache().getTransactionManager().commit();
}
assertEquals(1, cache.values().size());
}
}
| 14,276
| 34.426799
| 112
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/expiry/DistAutoCommitExpiryTest.java
|
package org.infinispan.expiry;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @author wburns
* @since 9.0
*/
@Test(groups = "functional", testName = "expiry.DistAutoCommitExpiryTest")
public class DistAutoCommitExpiryTest extends AutoCommitExpiryTest {
protected DistAutoCommitExpiryTest() {
super(CacheMode.DIST_SYNC, true);
}
}
| 395
| 23.75
| 74
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/expiry/AutoCommitExpiryTest.java
|
package org.infinispan.expiry;
import static org.testng.AssertJUnit.assertEquals;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
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.configuration.cache.ConfigurationBuilder;
import org.infinispan.expiration.ExpirationManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired;
import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.ControlledTimeService;
import org.infinispan.commons.time.TimeService;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "expiry.AutoCommitExpiryTest")
public abstract class AutoCommitExpiryTest extends SingleCacheManagerTest {
private final CacheMode mode;
private final boolean autoCommit;
protected ControlledTimeService timeService;
protected AutoCommitExpiryTest(CacheMode mode, boolean autoCommit) {
this.mode = mode;
this.autoCommit = autoCommit;
}
@Test
public void testNoAutCommitAndExpiryListener() throws SystemException, NotSupportedException,
HeuristicRollbackException, HeuristicMixedException, RollbackException {
ExpiryListener expiryListener = new ExpiryListener();
Cache<String, String> applicationCache = cacheManager.getCache();
applicationCache.addListener(expiryListener);
TransactionManager tm = applicationCache.getAdvancedCache().getTransactionManager();
tm.begin();
applicationCache.put("test1", "value1", 1, TimeUnit.SECONDS);
tm.commit();
tm.begin();
applicationCache.put("test2", "value2", 1, TimeUnit.SECONDS);
tm.commit();
timeService.advance(TimeUnit.SECONDS.toMillis(10));
ExpirationManager manager = applicationCache.getAdvancedCache().getExpirationManager();
manager.processExpiration();
assertEquals(2, expiryListener.getCount());
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = new ConfigurationBuilder();
if (mode.isClustered()) {
builder.clustering().cacheMode(mode);
}
builder
.statistics().enable()
.transaction()
.transactionMode(TransactionMode.TRANSACTIONAL)
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.autoCommit(autoCommit)
.locking().isolationLevel(IsolationLevel.READ_COMMITTED);
EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(builder);
timeService = new ControlledTimeService();
TestingUtil.replaceComponent(cm, TimeService.class, timeService, true);
return cm;
}
@Listener(primaryOnly = true, observation = Listener.Observation.POST)
public class ExpiryListener {
private final AtomicInteger counter = new AtomicInteger();
public int getCount() {
return counter.get();
}
@CacheEntryExpired
public void expired(CacheEntryExpiredEvent<String, String> event) {
counter.incrementAndGet();
}
}
}
| 3,911
| 36.257143
| 96
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/stats/NotAvailableSingleStatsTest.java
|
package org.infinispan.stats;
import static org.testng.AssertJUnit.assertEquals;
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.test.MultipleCacheManagersTest;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "stats.NotAvailableSingleStatsTest")
public class NotAvailableSingleStatsTest extends MultipleCacheManagersTest {
protected Cache cache;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.LOCAL, false);
cfg.statistics().available(false);
addClusterEnabledCacheManager(cfg);
cache = cache(0);
}
public void testStatsWhenNotAvailable() {
Stats stats = cache.getAdvancedCache().getStats();
assertNotNull(stats);
assertEquals(-1, stats.getHits());
}
}
| 1,005
| 32.533333
| 88
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/stats/SingleStatsTest.java
|
package org.infinispan.stats;
import static org.infinispan.container.offheap.UnpooledOffHeapMemoryAllocator.estimateSizeOverhead;
import static org.infinispan.container.offheap.UnpooledOffHeapMemoryAllocator.offHeapEntrySize;
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 org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.MemoryConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.container.offheap.OffHeapConcurrentMap;
import org.infinispan.context.Flag;
import org.infinispan.eviction.EvictionStrategy;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.transaction.TransactionMode;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "stats.SingleStatsTest")
public class SingleStatsTest extends MultipleCacheManagersTest {
private static final int OFF_HEAP_KEY_SIZE = 6;
private static final int OFF_HEAP_VALUE_SIZE = 8;
private static final long OFF_HEAP_SIZE = estimateSizeOverhead(offHeapEntrySize(true, false /*immortal entries*/, OFF_HEAP_KEY_SIZE, OFF_HEAP_VALUE_SIZE));
protected final int EVICTION_MAX_ENTRIES = 3;
protected final int TOTAL_ENTRIES = 5;
protected StorageType storageType;
protected boolean countBasedEviction;
protected boolean accurateSize = true;
protected EvictionStrategy evictionStrategy = EvictionStrategy.REMOVE;
protected Cache<String, String> cache;
protected Stats stats;
@Override
public Object[] factory() {
return Arrays.stream(EvictionStrategy.values())
.flatMap(strategy ->
Arrays.stream(new Object[]{
new SingleStatsTest().withStorage(StorageType.BINARY).withCountEviction(false).withEvictionStrategy(strategy),
new SingleStatsTest().withStorage(StorageType.BINARY).withCountEviction(true).withEvictionStrategy(strategy),
new SingleStatsTest().withStorage(StorageType.BINARY).withCountEviction(true).withEvictionStrategy(strategy).withAccurateSize(false),
new SingleStatsTest().withStorage(StorageType.HEAP).withCountEviction(true).withEvictionStrategy(strategy),
new SingleStatsTest().withStorage(StorageType.HEAP).withCountEviction(true).withEvictionStrategy(strategy).withAccurateSize(false),
new SingleStatsTest().withStorage(StorageType.OFF_HEAP).withCountEviction(true).withEvictionStrategy(strategy),
new SingleStatsTest().withStorage(StorageType.OFF_HEAP).withCountEviction(false).withEvictionStrategy(strategy),
new SingleStatsTest().withStorage(StorageType.OFF_HEAP).withCountEviction(false).withEvictionStrategy(strategy).withAccurateSize(false),
})
).toArray();
}
@Override
protected String[] parameterNames() {
return concat(super.parameterNames(), "StorageType", "CountBasedEviction", "EvictionStrategy", "AccurateSize");
}
@Override
protected Object[] parameterValues() {
return concat(super.parameterValues(), storageType, countBasedEviction, evictionStrategy, accurateSize);
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.LOCAL, false);
configure(cfg);
GlobalConfigurationBuilder global = defaultGlobalConfigurationBuilder();
global.metrics().accurateSize(accurateSize);
addClusterEnabledCacheManager(global, cfg);
cache = cache(0);
refreshStats();
}
protected void configure(ConfigurationBuilder cfg) {
long size = EVICTION_MAX_ENTRIES;
MemoryConfigurationBuilder memoryConfigurationBuilder = cfg.memory();
memoryConfigurationBuilder.storage(storageType);
if (countBasedEviction) {
memoryConfigurationBuilder.maxCount(size);
} else {
if (storageType == StorageType.OFF_HEAP) {
// Off heap key/value size is 80 bytes
size = estimateSizeOverhead(size * OFF_HEAP_SIZE);
// Have to also include address count overhead
size += estimateSizeOverhead(OffHeapConcurrentMap.INITIAL_SIZE << 3);
} else {
// Binary key/value size is 128 bytes
// Exception requires transactions which adds additional overhead
size *= (128 + (evictionStrategy.isExceptionBased() ? 48 : 0));
}
memoryConfigurationBuilder.maxSize(Long.toString(size));
}
memoryConfigurationBuilder.whenFull(evictionStrategy);
if (evictionStrategy == EvictionStrategy.EXCEPTION) {
cfg.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
}
cfg
.statistics()
.enable()
.persistence()
.passivation(true)
.addStore(DummyInMemoryStoreConfigurationBuilder.class)
.purgeOnStartup(true);
}
public SingleStatsTest withStorage(StorageType storageType) {
this.storageType = storageType;
return this;
}
public SingleStatsTest withCountEviction(boolean countBasedEviction) {
this.countBasedEviction = countBasedEviction;
return this;
}
public SingleStatsTest withEvictionStrategy(EvictionStrategy evictionStrategy) {
this.evictionStrategy = evictionStrategy;
return this;
}
public SingleStatsTest withAccurateSize(boolean accurateSize) {
this.accurateSize = accurateSize;
return this;
}
@AfterMethod
public void cleanCache() {
cache.clear();
cache.getAdvancedCache().getStats().reset();
}
public void testStats() {
refreshStats();
if (accurateSize) {
assertEquals(0, stats.getCurrentNumberOfEntries());
} else {
assertEquals(-1, stats.getCurrentNumberOfEntries());
}
int insertErrors = 0;
for (int i = 0; i < TOTAL_ENTRIES; i++) {
try {
cache.put("key" + i, "value" + i);
} catch (CacheException e) {
insertErrors++;
}
}
if (insertErrors > 0 && TOTAL_ENTRIES - EVICTION_MAX_ENTRIES != insertErrors) {
fail("Number of failed errors was: " + insertErrors + " manually check them.");
}
int expectedSize = TOTAL_ENTRIES - insertErrors;
refreshStats();
// Approximate size stats are the same as the accurate size stats with DummyInMemoryStore
// Only expiration is ignored, and we do not have expired entries
assertEquals(expectedSize, stats.getApproximateEntries());
assertEquals(EVICTION_MAX_ENTRIES, stats.getApproximateEntriesInMemory());
assertEquals(primaryKeysCount(cache), stats.getApproximateEntriesUnique());
if (accurateSize) {
assertEquals(expectedSize, stats.getCurrentNumberOfEntries());
assertEquals(EVICTION_MAX_ENTRIES, stats.getCurrentNumberOfEntriesInMemory());
} else {
assertEquals(-1, stats.getCurrentNumberOfEntries());
assertEquals(-1, stats.getCurrentNumberOfEntriesInMemory());
}
// Eviction stats with passivation can be delayed
eventuallyEquals((long) expectedSize - EVICTION_MAX_ENTRIES, () -> {
refreshStats();
return stats.getEvictions();
});
int additionalMisses = 0;
for (int i = 0; i < expectedSize; i++) {
Cache<?, ?> skipLoaderCache = cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD);
String key = "key" + i;
if (skipLoaderCache.containsKey(key)) {
cache.evict(key);
break;
}
additionalMisses++;
}
refreshStats();
assertEquals(expectedSize - EVICTION_MAX_ENTRIES + 1, stats.getEvictions());
assertEquals("value1", cache.get("key1"));
assertEquals("value2", cache.get("key2"));
assertEquals("value1", cache.remove("key1"));
assertEquals("value2", cache.remove("key2"));
assertNull(cache.remove("non-existing"));
assertNull(cache.get("key1"));
assertNull(cache.get("key2"));
refreshStats();
assertEquals(3, stats.getHits());
assertEquals(2 + additionalMisses, stats.getMisses());
assertEquals(2, stats.getRemoveHits());
assertEquals(1, stats.getRemoveMisses());
assertEquals(5 + additionalMisses, stats.getRetrievals());
assertEquals(TOTAL_ENTRIES, stats.getStores());
cache.put("other-key", "value");
refreshStats();
assertEquals(TOTAL_ENTRIES + 1, stats.getStores());
assertTrue(stats.getAverageReadTime() >= 0);
assertTrue(stats.getAverageRemoveTime() >= 0);
assertTrue(stats.getAverageWriteTime() >= 0);
assertTrue(stats.getAverageReadTimeNanos() >= 0);
assertTrue(stats.getAverageRemoveTimeNanos() >= 0);
assertTrue(stats.getAverageWriteTimeNanos() >= 0);
if (countBasedEviction || evictionStrategy.isExceptionBased()) {
assertEquals(-1L, stats.getDataMemoryUsed());
} else {
assertTrue(stats.getDataMemoryUsed() > 0);
}
if (storageType == StorageType.OFF_HEAP) {
assertTrue(stats.getOffHeapMemoryUsed() > 0);
}
}
protected long primaryKeysCount(Cache<?, ?> cache) {
return evictionStrategy == EvictionStrategy.EXCEPTION ? EVICTION_MAX_ENTRIES : TOTAL_ENTRIES;
}
protected void refreshStats() {
stats = cache.getAdvancedCache().getStats();
}
}
| 10,001
| 39.991803
| 160
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/stats/ClusteredStatsTest.java
|
package org.infinispan.stats;
import static org.testng.AssertJUnit.assertEquals;
import java.util.stream.IntStream;
import org.infinispan.Cache;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.encoding.DataConversion;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.infinispan.test.TestingUtil;
import org.infinispan.topology.ClusterTopologyManager;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "stats.ClusteredStatsTest")
public class ClusteredStatsTest extends SingleStatsTest {
protected final int CLUSTER_SIZE = 3;
protected final String CACHE_NAME = ClusteredStatsTest.class.getSimpleName();
@Override
public Object[] factory() {
return new Object[]{
new ClusteredStatsTest().withStorage(StorageType.OBJECT).withCountEviction(true),
new ClusteredStatsTest().withStorage(StorageType.OBJECT).withCountEviction(true).withAccurateSize(false),
new ClusteredStatsTest().withStorage(StorageType.OFF_HEAP).withCountEviction(true),
new ClusteredStatsTest().withStorage(StorageType.OFF_HEAP).withCountEviction(true).withAccurateSize(false),
};
}
@Override
protected void createCacheManagers() throws Throwable {
GlobalConfigurationBuilder global = defaultGlobalConfigurationBuilder();
global.metrics().accurateSize(accurateSize);
ConfigurationBuilder configBuilder = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false);
configure(configBuilder);
Configuration config = configBuilder.build();
createCluster(global, new ConfigurationBuilder(), CLUSTER_SIZE);
// ISPN-13022 Define the configuration on a subset of nodes to ensure an exception is not thrown if a cluster member
// does not contain a cache definition
for (int i = 0; i < CLUSTER_SIZE - 1; i++) {
cacheManagers.get(i).createCache(CACHE_NAME, config);
}
TestingUtil.blockUntilViewsReceived(30000, cacheManagers);
TestingUtil.waitForNoRebalance(
IntStream.range(0, CLUSTER_SIZE - 1).mapToObj(i -> cache(i, CACHE_NAME)).toArray(Cache[]::new)
);
cache = cache(0, CACHE_NAME);
refreshStats();
}
public void testClusteredStats() {
for (int i = 0; i < TOTAL_ENTRIES; i++) {
cache.put("key" + i, "value" + i);
}
ClusterCacheStats clusteredStats = TestingUtil.extractComponent(cache, ClusterCacheStats.class);
clusteredStats.setStaleStatsThreshold(1);
// Approximate stats count each entry once for each node
int actualOwners = CLUSTER_SIZE - 1;
assertEquals(actualOwners * TOTAL_ENTRIES, clusteredStats.getApproximateEntries());
assertEquals(actualOwners * EVICTION_MAX_ENTRIES, clusteredStats.getApproximateEntriesInMemory());
assertEquals(TOTAL_ENTRIES, clusteredStats.getApproximateEntriesUnique());
// Accurate stats try to de-duplicate counts
if (accurateSize) {
assertEquals(TOTAL_ENTRIES, clusteredStats.getCurrentNumberOfEntries());
assertEquals(EVICTION_MAX_ENTRIES, clusteredStats.getCurrentNumberOfEntriesInMemory());
} else {
assertEquals(-1, clusteredStats.getCurrentNumberOfEntries());
assertEquals(-1, clusteredStats.getCurrentNumberOfEntriesInMemory());
}
// Eviction stats with passivation can be delayed
eventuallyEquals((long) actualOwners * (TOTAL_ENTRIES - EVICTION_MAX_ENTRIES), clusteredStats::getPassivations);
}
// Reproducer for ISPN-14279.
// Calling approximate size before joining properly causes a division by 0 with non-segmented store.
public void testJoinerStats() {
for (int i = 0; i < TOTAL_ENTRIES; i++) {
cache.put("key" + i, "value" + i);
}
for (int i = 0; i < CLUSTER_SIZE - 1; i++) {
Cache<?, ?> cache = cacheManagers.get(i).getCache(CACHE_NAME);
ClusterTopologyManager crmTM = TestingUtil.extractComponent(cache, ClusterTopologyManager.class);
crmTM.setRebalancingEnabled(false);
}
GlobalConfigurationBuilder globalConfigurationBuilder = defaultGlobalConfigurationBuilder();
globalConfigurationBuilder.metrics().accurateSize(true);
ConfigurationBuilder cb = new ConfigurationBuilder()
.read(cache.getAdvancedCache().getCacheConfiguration(), Combine.DEFAULT);
cb.persistence().clearStores();
Configuration configuration = cb.persistence()
.addStore(DummyInMemoryStoreConfigurationBuilder.class)
.segmented(false)
.clustering()
.hash().numSegments(1)
.build();
EmbeddedCacheManager ecm = addClusterEnabledCacheManager(new GlobalConfigurationBuilder().read(globalConfigurationBuilder.build()), new ConfigurationBuilder());
Stats stats = ecm.createCache(CACHE_NAME, configuration).getAdvancedCache().getStats();
assertEquals(0, stats.getApproximateEntries());
}
@Override
protected long primaryKeysCount(Cache<?, ?> cache) {
DistributionManager dm = TestingUtil.extractComponent(cache, DistributionManager.class);
long count = 0;
for (int i = 0; i < TOTAL_ENTRIES; i++) {
DataConversion keyDataConversion = cache.getAdvancedCache().getKeyDataConversion();
if (dm.getCacheTopology().getDistribution(keyDataConversion.toStorage("key" + i)).isPrimary()) {
count++;
}
}
return count;
}
}
| 5,903
| 44.415385
| 166
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/stats/StatsMinNodeTest.java
|
package org.infinispan.stats;
import static org.testng.AssertJUnit.assertEquals;
import java.util.stream.IntStream;
import org.infinispan.commons.time.TimeService;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.container.DataContainer;
import org.infinispan.eviction.EvictionStrategy;
import org.infinispan.eviction.EvictionType;
import org.infinispan.metadata.EmbeddedMetadata;
import org.infinispan.metadata.Metadata;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.ControlledTimeService;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Tests to make sure that minimum node output is correct
* @author wburns
* @since 9.0
*/
@Test(groups = "functional", testName = "stats.StatsMinNodeTest")
public class StatsMinNodeTest extends MultipleCacheManagersTest {
private static final int MAX_SIZE = 10;
private static final int NUM_NODES = 5;
private static final int NUM_OWNERS = 3;
protected StorageType storageType;
protected EvictionStrategy evictionStrategy;
protected ControlledTimeService timeService;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(cacheMode, false);
configure(cfg);
for (int i = 0; i < NUM_NODES; ++i) {
addClusterEnabledCacheManager(cfg);
}
waitForClusterToForm();
timeService = new ControlledTimeService();
for (int i = 0; i < NUM_NODES; ++i) {
TestingUtil.replaceComponent(manager(i), TimeService.class, timeService, true);
}
}
@AfterMethod
public void cleanCache() {
cache(0).clear();
ClusterCacheStats stats = TestingUtil.extractComponent(cache(0), ClusterCacheStats.class);
stats.reset();
// This way each test will query stats
timeService.advance(stats.getStaleStatsThreshold() + 1);
}
protected void configure(ConfigurationBuilder cfg) {
cfg
.statistics()
.enable()
.clustering()
.hash()
.numOwners(NUM_OWNERS)
.memory()
.storageType(storageType)
.evictionType(EvictionType.COUNT)
.size(MAX_SIZE)
.evictionStrategy(evictionStrategy);
if (evictionStrategy == EvictionStrategy.EXCEPTION) {
cfg.transaction()
.transactionMode(TransactionMode.TRANSACTIONAL);
}
}
public StatsMinNodeTest withStorage(StorageType storageType) {
this.storageType = storageType;
return this;
}
public StatsMinNodeTest withEvictionStrategy(EvictionStrategy evictionStrategy) {
this.evictionStrategy = evictionStrategy;
return this;
}
@Override
public Object[] factory() {
return new Object[]{
new StatsMinNodeTest().withStorage(StorageType.OBJECT).withEvictionStrategy(EvictionStrategy.REMOVE).cacheMode(CacheMode.DIST_SYNC),
new StatsMinNodeTest().withStorage(StorageType.OBJECT).withEvictionStrategy(EvictionStrategy.EXCEPTION).cacheMode(CacheMode.DIST_SYNC),
new StatsMinNodeTest().withStorage(StorageType.OBJECT).withEvictionStrategy(EvictionStrategy.REMOVE).cacheMode(CacheMode.REPL_SYNC),
new StatsMinNodeTest().withStorage(StorageType.OBJECT).withEvictionStrategy(EvictionStrategy.EXCEPTION).cacheMode(CacheMode.REPL_SYNC),
new StatsMinNodeTest().withStorage(StorageType.BINARY).withEvictionStrategy(EvictionStrategy.REMOVE).cacheMode(CacheMode.DIST_SYNC),
new StatsMinNodeTest().withStorage(StorageType.BINARY).withEvictionStrategy(EvictionStrategy.EXCEPTION).cacheMode(CacheMode.DIST_SYNC),
new StatsMinNodeTest().withStorage(StorageType.BINARY).withEvictionStrategy(EvictionStrategy.REMOVE).cacheMode(CacheMode.REPL_SYNC),
new StatsMinNodeTest().withStorage(StorageType.BINARY).withEvictionStrategy(EvictionStrategy.EXCEPTION).cacheMode(CacheMode.REPL_SYNC),
new StatsMinNodeTest().withStorage(StorageType.OFF_HEAP).withEvictionStrategy(EvictionStrategy.REMOVE).cacheMode(CacheMode.DIST_SYNC),
new StatsMinNodeTest().withStorage(StorageType.OFF_HEAP).withEvictionStrategy(EvictionStrategy.EXCEPTION).cacheMode(CacheMode.DIST_SYNC),
new StatsMinNodeTest().withStorage(StorageType.OFF_HEAP).withEvictionStrategy(EvictionStrategy.REMOVE).cacheMode(CacheMode.REPL_SYNC),
new StatsMinNodeTest().withStorage(StorageType.OFF_HEAP).withEvictionStrategy(EvictionStrategy.EXCEPTION).cacheMode(CacheMode.REPL_SYNC),
};
}
@Override
protected String[] parameterNames() {
return concat(super.parameterNames(), "StorageType", "EvictionStrategy");
}
@Override
protected Object[] parameterValues() {
return concat(super.parameterValues(), storageType, evictionStrategy);
}
@Override
protected String parameters() {
return "[" + cacheMode + ", " + storageType + "," + evictionStrategy + "]";
}
private int handleModeEstimate(int desired, CacheMode mode) {
if (mode.isReplicated()) {
// A REPL cache always requires just 1 node as all nodes have all data
return 1;
}
return desired;
}
@DataProvider(name = "capacityTest")
public static Object[][] capacityArguments() {
int numOwnerMin = NUM_NODES - NUM_OWNERS + 1;
// At this point data should matter
int cutOff = MAX_SIZE * NUM_OWNERS / NUM_NODES;
return IntStream.rangeClosed(0, MAX_SIZE).mapToObj(i -> {
// 0 - 6 go through here
if (i <= cutOff) {
return new Object[] {i, numOwnerMin};
} else {
int totalData = i * NUM_OWNERS;
// If there is a remainder of data left, another node has to pick up those as well
boolean needExtra = totalData % MAX_SIZE != 0;
// Min is required because of evictions throwing off calculation as we can only
// store 16.66 repeating inserts without eviction firing off
return new Object[] {i, Math.min(5, totalData / MAX_SIZE + (needExtra ? 1 : 0))};
}
}).toArray(Object[][]::new);
}
@Test(dataProvider = "capacityTest")
public void testCapacity(int inserts, int nodeExpected) {
caches().forEach(c -> {
DataContainer container = c.getAdvancedCache().getDataContainer();
// Just reuse same value
Object value = c.getAdvancedCache().getValueDataConversion().toStorage("foo");
Metadata metadata = new EmbeddedMetadata.Builder().build();
// We just insert into data container directly - as we can guarantee same size then (this can't happen
// in a real cache, but we can control the size easily)
for (int i = 0; i < inserts; ++i) {
Object key = c.getAdvancedCache().getKeyDataConversion().toStorage(i);
container.put(key, value, metadata);
}
});
ClusterCacheStats stats = TestingUtil.extractComponent(cache(0), ClusterCacheStats.class);
assertEquals(handleModeEstimate(nodeExpected, cacheMode), stats.getRequiredMinimumNumberOfNodes());
}
}
| 7,444
| 40.825843
| 149
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/interceptors/CustomInterceptorTest.java
|
package org.infinispan.interceptors;
import static org.infinispan.test.TestingUtil.withCacheManager;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.List;
import org.infinispan.Cache;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.InterceptorConfiguration.Position;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.CacheManagerCallable;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "interceptors.CustomInterceptorTest")
public class CustomInterceptorTest extends AbstractInfinispanTest {
public void testCustomInterceptorProperties() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.customInterceptors().addInterceptor().interceptor(new FooInterceptor()).position(Position.FIRST).addProperty("foo", "bar");
withCacheManager(new CacheManagerCallable(
TestCacheManagerFactory.createCacheManager(builder)) {
@Override
public void call() {
final Cache<Object,Object> cache = cm.getCache();
AsyncInterceptor i =
cache.getAdvancedCache().getAsyncInterceptorChain().getInterceptors().get(0);
assertTrue("Expecting FooInterceptor in the interceptor chain", i instanceof FooInterceptor);
assertEquals("bar", ((FooInterceptor)i).getFoo());
}
});
}
@Test(expectedExceptions=CacheConfigurationException.class)
public void testMissingPosition() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.customInterceptors().addInterceptor().interceptor(new FooInterceptor());
TestCacheManagerFactory.createCacheManager(builder);
}
public void testLastInterceptor() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.customInterceptors().addInterceptor().position(Position.LAST).interceptor(new FooInterceptor());
final EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager();
cacheManager.defineConfiguration("interceptors", builder.build());
withCacheManager(new CacheManagerCallable(cacheManager) {
@Override
public void call() {
List<AsyncInterceptor> interceptors =
cacheManager.getCache("interceptors").getAdvancedCache().getAsyncInterceptorChain()
.getInterceptors();
assertEquals(FooInterceptor.class, interceptors.get(interceptors.size() - 2).getClass());
}
});
}
public void testOtherThanFirstOrLastInterceptor() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.customInterceptors().addInterceptor().position(Position.OTHER_THAN_FIRST_OR_LAST).interceptor(new FooInterceptor());
final EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager();
cacheManager.defineConfiguration("interceptors", builder.build());
withCacheManager(new CacheManagerCallable(cacheManager) {
@Override
public void call() {
AsyncInterceptorChain
interceptorChain = cacheManager.getCache("interceptors").getAdvancedCache().getAsyncInterceptorChain();
assertEquals(interceptorChain.getInterceptors().get(1).getClass(), FooInterceptor.class);
}
});
}
public void testLastInterceptorDefaultCache() {
ConfigurationBuilder builder = new ConfigurationBuilder();
final FooInterceptor interceptor = new FooInterceptor();
builder.customInterceptors().addInterceptor().position(Position.LAST).interceptor(interceptor);
final EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(builder);
withCacheManager(new CacheManagerCallable(cacheManager) {
@Override
public void call() {
List<AsyncInterceptor> interceptors =
cacheManager.getCache().getAdvancedCache().getAsyncInterceptorChain()
.getInterceptors();
Object o = interceptors.get(interceptors.size() - 2);
assertEquals(FooInterceptor.class, o.getClass());
assertFalse(interceptor.putInvoked);
cacheManager.getCache().put("k", "v");
assertEquals("v", cacheManager.getCache().get("k"));
assertTrue(interceptor.putInvoked);
}
});
}
}
| 4,718
| 46.666667
| 137
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/interceptors/ConcurrentInterceptorVisibilityTest.java
|
package org.infinispan.interceptors;
import static org.infinispan.test.TestingUtil.withCacheManager;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.impl.EntryWrappingInterceptor;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.CacheManagerCallable;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* Tests visibility of effects of cache operations on a separate thread once
* they've passed a particular interceptor barrier related to the cache
* operation.
*
* @author Galder Zamarreño
* @since 5.1
*/
@Test(groups = "functional", testName = "interceptors.ConcurrentInterceptorVisibilityTest")
public class ConcurrentInterceptorVisibilityTest extends AbstractInfinispanTest {
public void testSizeVisibility() throws Exception {
updateCache(Visibility.SIZE);
}
@Test(groups = "unstable")
public void testGetVisibility() throws Exception {
updateCache(Visibility.GET);
}
private void updateCache(final Visibility visibility) throws Exception {
final String key = "k-" + visibility;
final String value = "k-" + visibility;
final CountDownLatch entryCreatedLatch = new CountDownLatch(1);
final EntryCreatedInterceptor interceptor = new EntryCreatedInterceptor(entryCreatedLatch);
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.customInterceptors().addInterceptor()
.interceptor(interceptor)
.before(EntryWrappingInterceptor.class);
withCacheManager(new CacheManagerCallable(
TestCacheManagerFactory.createCacheManager(builder)) {
@Override
public void call() throws Exception {
final Cache<Object,Object> cache = cm.getCache();
switch (visibility) {
case SIZE:
assert cache.size() == 0;
break;
case GET:
assert cache.get(key) == null;
break;
}
Future<Void> ignore = fork(() -> {
cache.put(key, value);
return null;
});
try {
entryCreatedLatch.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
switch (visibility) {
case SIZE:
int size = cache.size();
assert size == 1 : "size is: " + size;
assert interceptor.assertKeySet;
break;
case GET:
Object retVal = cache.get(key);
assert retVal != null;
assert retVal.equals(value): "retVal is: " + retVal;
assert interceptor.assertKeySet;
break;
}
ignore.get(5, TimeUnit.SECONDS);
}
});
}
private enum Visibility {
SIZE, GET
}
public static class EntryCreatedInterceptor extends BaseCustomAsyncInterceptor {
private static final Log log = LogFactory.getLog(EntryCreatedInterceptor.class);
final CountDownLatch latch;
volatile boolean assertKeySet;
private EntryCreatedInterceptor(CountDownLatch latch) {
this.latch = latch;
}
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx,
PutKeyValueCommand command) throws Throwable {
// First execute the operation itself
return invokeNextThenAccept(ctx, command, (rCtx, rCommand, rv) -> {
assertKeySet = (cache.keySet().size() == 1);
// After entry has been committed to the container
log.info("Cache entry created, now check in different thread");
latch.countDown();
// Force a bit of delay in the listener
TestingUtil.sleepThread(3000);
});
}
}
}
| 4,376
| 33.195313
| 97
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/interceptors/FooInterceptor.java
|
package org.infinispan.interceptors;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.context.InvocationContext;
public class FooInterceptor extends BaseCustomAsyncInterceptor {
public volatile boolean putInvoked;
private String foo;
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
putInvoked = true;
return super.visitPutKeyValueCommand(ctx, command);
}
}
| 605
| 22.307692
| 110
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/interceptors/distribution/L1WriteSynchronizerTest.java
|
package org.infinispan.interceptors.distribution;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
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.container.entries.ImmortalCacheEntry;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.impl.InternalDataContainer;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.interceptors.locking.ClusteringDependentLogic;
import org.infinispan.metadata.Metadata;
import org.infinispan.statetransfer.StateTransferLock;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Test to ensure proper behavior of {@link L1WriteSynchronizer}
*
* @author wburns
* @since 6.0
*/
@Test(groups = "unit", testName = "interceptors.distribution.L1WriteSynchronizerTest")
public class L1WriteSynchronizerTest extends AbstractInfinispanTest {
private L1WriteSynchronizer sync;
private InternalDataContainer dc;
private StateTransferLock stl;
private ClusteringDependentLogic cdl;
private final long l1Timeout = 1000;
@BeforeMethod
public void beforeMethod() {
dc = mock(InternalDataContainer.class);
stl = mock(StateTransferLock.class);
cdl = mock(ClusteringDependentLogic.class);
when(cdl.getCacheTopology()).thenReturn(mock(LocalizedCacheTopology.class));
sync = new L1WriteSynchronizer(dc, l1Timeout, stl, cdl);
}
@Test
public void testNullICEProvided() throws ExecutionException, InterruptedException {
sync.runL1UpdateIfPossible(null);
assertNull(sync.get());
}
@Test
public void testNullICEProvidedWait() throws ExecutionException, InterruptedException, TimeoutException {
sync.runL1UpdateIfPossible(null);
assertNull(sync.get(1, TimeUnit.SECONDS));
}
@Test
public void testGetReturnValueWait() throws InterruptedException, ExecutionException, TimeoutException {
Object value = new Object();
InternalCacheEntry ice = new ImmortalCacheEntry(value, value);
sync.runL1UpdateIfPossible(ice);
assertEquals(ice, sync.get());
}
@Test
public void testGetReturnValueTimeWait() throws InterruptedException, ExecutionException, TimeoutException {
Object value = new Object();
InternalCacheEntry ice = new ImmortalCacheEntry(value, value);
sync.runL1UpdateIfPossible(ice);
assertEquals(ice, sync.get(1, TimeUnit.SECONDS));
}
@Test
public void testExceptionWait() throws InterruptedException {
Throwable t = mock(Throwable.class);
sync.retrievalEncounteredException(t);
try {
sync.get();
} catch (ExecutionException e) {
assertEquals(t, e.getCause());
}
}
@Test
public void testExceptionTimeWait() throws InterruptedException, TimeoutException {
Throwable t = mock(Throwable.class);
sync.retrievalEncounteredException(t);
try {
sync.get(1, TimeUnit.SECONDS);
fail("Should have thrown an execution exception");
} catch (ExecutionException e) {
assertEquals(t, e.getCause());
}
}
@Test
public void testSpawnedThreadBlockingValue() throws InterruptedException, ExecutionException, TimeoutException {
Object value = new Object();
Future future = fork(() -> sync.get());
try {
future.get(50, TimeUnit.MILLISECONDS);
fail("Should have thrown a timeout exception");
} catch (TimeoutException e) {
// This should time out exception
}
InternalCacheEntry ice = new ImmortalCacheEntry(value, value);
sync.runL1UpdateIfPossible(ice);
assertEquals(ice, future.get(1, TimeUnit.SECONDS));
}
@Test
public void testSpawnedThreadBlockingValueTimeWait() throws InterruptedException, ExecutionException, TimeoutException {
Object value = new Object();
Future future = fork(() -> sync.get(5, TimeUnit.SECONDS));
// This should not return since we haven't signaled the sync yet
try {
future.get(50, TimeUnit.MILLISECONDS);
fail("Should have thrown a timeout exception");
} catch (TimeoutException e) {
// This should time out exception
}
InternalCacheEntry ice = new ImmortalCacheEntry(value, value);
sync.runL1UpdateIfPossible(ice);
assertEquals(ice, future.get(1, TimeUnit.SECONDS));
}
@Test
public void testSpawnedThreadBlockingNullValue() throws InterruptedException, ExecutionException, TimeoutException {
Future future = fork(() -> sync.get());
try {
future.get(50, TimeUnit.MILLISECONDS);
fail("Should have thrown a timeout exception");
} catch (TimeoutException e) {
// This should time out exception
}
sync.runL1UpdateIfPossible(null);
assertNull(future.get(1, TimeUnit.SECONDS));
}
@Test
public void testSpawnedThreadBlockingNullValueTimeWait() throws InterruptedException, ExecutionException, TimeoutException {
Future future = fork(() -> sync.get(5, TimeUnit.SECONDS));
// This should not return since we haven't signaled the sync yet
try {
future.get(50, TimeUnit.MILLISECONDS);
fail("Should have thrown a timeout exception");
} catch (TimeoutException e) {
// This should time out exception
}
sync.runL1UpdateIfPossible(null);
assertNull(future.get(1, TimeUnit.SECONDS));
}
@Test
public void testSpawnedThreadBlockingException() throws InterruptedException, ExecutionException, TimeoutException {
Throwable t = new Exception();
Future future = fork(() -> sync.get());
// This should not return since we haven't signaled the sync yet
try {
future.get(50, TimeUnit.MILLISECONDS);
fail("Should have thrown a timeout exception");
} catch (TimeoutException e) {
// This should time out exception
}
sync.retrievalEncounteredException(t);
try {
sync.get(1, TimeUnit.SECONDS);
fail("Should have thrown an execution exception");
} catch (ExecutionException e) {
assertEquals(t, e.getCause());
}
}
@Test
public void testSpawnedThreadBlockingExceptionTimeWait() throws InterruptedException, ExecutionException, TimeoutException {
Throwable t = new Exception();
Future future = fork(() -> sync.get(5, TimeUnit.SECONDS));
try {
future.get(50, TimeUnit.MILLISECONDS);
fail("Should have thrown a timeout exception");
} catch (TimeoutException e) {
// This should time out exception
}
sync.retrievalEncounteredException(t);
try {
sync.get(1, TimeUnit.SECONDS);
fail("Should have thrown an execution exception");
} catch (ExecutionException e) {
assertEquals(t, e.getCause());
}
}
@Test
public void testWriteCancelled() {
assertTrue(sync.trySkipL1Update());
Object keyValue = new Object();
InternalCacheEntry ice = new ImmortalCacheEntry(keyValue, keyValue);
sync.runL1UpdateIfPossible(ice);
// The dc shouldn't have been updated
verify(dc, never()).put(any(), any(), any(Metadata.class));
}
@Test
public void testWriteCannotCancel() throws InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException {
final CyclicBarrier barrier = new CyclicBarrier(2);
// We use the topology lock as a sync point to know when the write is being attempted - note this is after
// the synchronizer has been marked as a write occurring
doAnswer(i -> { barrier.await(); return null; }).when(stl).acquireSharedTopologyLock();
Future<Void> future = fork(() -> {
Object keyValue = new Object();
InternalCacheEntry ice = new ImmortalCacheEntry(keyValue, keyValue);
sync.runL1UpdateIfPossible(ice);
});
// wait for the thread to try updating
barrier.await(1, TimeUnit.SECONDS);
assertFalse(sync.trySkipL1Update());
future.get(1, TimeUnit.SECONDS);
// The dc should have been updated
verify(dc).put(any(), any(), any(Metadata.class));
}
@Test
public void testDCUpdatedHigherICELifespan() {
verifyDCUpdate(Long.MAX_VALUE, false);
}
@Test
public void testDCUpdatedLowerICELifespan() {
verifyDCUpdate(50, true);
}
private void verifyDCUpdate(long iceLifespan, boolean shouldBeIceLifespan) {
Object value = new Object();
Object key = new Object();
InternalCacheEntry ice = when(mock(InternalCacheEntry.class, RETURNS_DEEP_STUBS).getValue()).thenReturn(value).getMock();
when(ice.getKey()).thenReturn(key);
when(ice.getLifespan()).thenReturn(iceLifespan);
sync.runL1UpdateIfPossible(ice);
verify(dc).put(eq(key), eq(value), any(Metadata.class));
Metadata.Builder verifier = verify(ice.getMetadata().builder());
verifier.lifespan(shouldBeIceLifespan ? iceLifespan : l1Timeout);
verifier.maxIdle(-1);
}
}
| 9,876
| 32.033445
| 130
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/interceptors/impl/AsyncInterceptorChainInvocationTest.java
|
package org.infinispan.interceptors.impl;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.infinispan.commons.test.Exceptions.expectExecutionException;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.SingleKeyNonTxInvocationContext;
import org.infinispan.interceptors.AsyncInterceptor;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.interceptors.InvocationSuccessFunction;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestException;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.testng.annotations.Test;
/**
* @author Dan Berindei
* @since 9.0
*/
@Test(groups = "unit", testName = "interceptors.AsyncInterceptorChainInvocationTest")
public class AsyncInterceptorChainInvocationTest extends AbstractInfinispanTest {
private VisitableCommand testCommand = new GetKeyValueCommand("k", 0, 0);
private VisitableCommand testSubCommand = new LockControlCommand("k", null, 0, null);
private final AtomicReference<String> sideEffects = new AtomicReference<>("");
public void testCompletedStage() {
AsyncInterceptorChain chain = newInterceptorChain(new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return "v1";
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return "v2";
}
});
InvocationContext context = newInvocationContext();
Object returnValue = chain.invoke(context, testCommand);
assertEquals("v1", returnValue);
}
public void testAsyncStage() throws Exception {
CompletableFuture<Object> f = new CompletableFuture<>();
AsyncInterceptorChain chain = newInterceptorChain(new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return asyncValue(f);
}
});
InvocationContext context = newInvocationContext();
CompletableFuture<Object> invokeFuture = chain.invokeAsync(context, testCommand);
assertFalse(invokeFuture.isDone());
f.complete("v1");
assertEquals("v1", invokeFuture.get(10, SECONDS));
}
public void testComposeSync() {
AsyncInterceptorChain chain = newInterceptorChain(new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextAndHandle(ctx, command, (rCtx, rCommand, rv, t) -> "v1");
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return "v2";
}
});
InvocationContext context = newInvocationContext();
Object returnValue = chain.invoke(context, testCommand);
assertEquals("v1", returnValue);
}
public void testComposeAsync() throws Exception {
CompletableFuture<Object> f = new CompletableFuture<>();
AsyncInterceptorChain chain = newInterceptorChain(new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextAndHandle(ctx, command, (rCtx, rCommand, rv, t) -> asyncValue(f));
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return "v1";
}
});
InvocationContext context = newInvocationContext();
CompletableFuture<Object> invokeFuture = chain.invokeAsync(context, testCommand);
assertFalse(invokeFuture.isDone());
f.complete("v2");
assertEquals("v2", invokeFuture.get(10, SECONDS));
}
public void testInvokeNextAsync() throws Exception {
CompletableFuture<Object> f = new CompletableFuture<>();
AsyncInterceptorChain chain = newInterceptorChain(new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return asyncInvokeNext(ctx, command, f);
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return "v1";
}
});
InvocationContext context = newInvocationContext();
CompletableFuture<Object> invokeFuture = chain.invokeAsync(context, testCommand);
assertFalse(invokeFuture.isDone());
f.complete("v");
assertEquals("v1", invokeFuture.get(10, SECONDS));
}
public void testInvokeNextSubCommand() {
AsyncInterceptorChain chain = newInterceptorChain(new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNext(ctx, testSubCommand);
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return command instanceof LockControlCommand ? "subCommand" : "command";
}
});
InvocationContext context = newInvocationContext();
Object returnValue = chain.invoke(context, testCommand);
assertEquals("subCommand", returnValue);
}
public void testInvokeNextAsyncSubCommand() throws Exception {
CompletableFuture<Object> f = new CompletableFuture<>();
AsyncInterceptorChain chain = newInterceptorChain(new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return asyncInvokeNext(ctx, testSubCommand, f);
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return command instanceof LockControlCommand ? "subCommand" : "command";
}
});
InvocationContext context = newInvocationContext();
CompletableFuture<Object> invokeFuture = chain.invokeAsync(context, testCommand);
assertFalse(invokeFuture.isDone());
f.complete("v");
assertEquals("subCommand", invokeFuture.get(10, SECONDS));
}
public void testAsyncStageCompose() throws Exception {
CompletableFuture<Object> f = new CompletableFuture<>();
AsyncInterceptorChain chain = newInterceptorChain(new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextAndHandle(ctx, command, (rCtx, rCommand, rv, t) -> "v1");
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return asyncValue(f);
}
});
InvocationContext context = newInvocationContext();
CompletableFuture<Object> invokeFuture = chain.invokeAsync(context, testCommand);
assertFalse(invokeFuture.isDone());
f.complete("v2");
assertEquals("v1", invokeFuture.get(10, SECONDS));
}
public void testAsyncStageComposeAsyncStage() throws Exception {
CompletableFuture<Object> f1 = new CompletableFuture<>();
CompletableFuture<Object> f2 = new CompletableFuture<>();
CompletableFuture<Object> f3 = new CompletableFuture<>();
AsyncInterceptorChain chain = newInterceptorChain(new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextAndHandle(ctx, command, (rCtx, rCommand, rv, t) -> {
InvocationSuccessFunction function = (rCtx1, rCommand1, rv1) -> asyncValue(f3);
return asyncValue(f2).addCallback(rCtx, rCommand, function);
});
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return asyncValue(f1);
}
});
InvocationContext context = newInvocationContext();
CompletableFuture<Object> invokeFuture = chain.invokeAsync(context, testCommand);
assertFalse(invokeFuture.isDone());
f1.complete("v1");
assertFalse(invokeFuture.isDone());
f2.complete("v2");
assertFalse(invokeFuture.isDone());
f3.complete("v3");
assertEquals("v3", invokeFuture.get(10, SECONDS));
}
public void testAsyncInvocationManyHandlers() throws Exception {
sideEffects.set("");
CompletableFuture<Object> f = new CompletableFuture<>();
AsyncInterceptorChain chain = makeChainWithManyHandlers(f);
CompletableFuture<Object> invokeFuture = chain.invokeAsync(newInvocationContext(), testCommand);
f.complete("");
assertHandlers(invokeFuture);
}
public void testSyncInvocationManyHandlers() throws Exception {
sideEffects.set("");
CompletableFuture<Object> f = CompletableFuture.completedFuture("");
AsyncInterceptorChain chain = makeChainWithManyHandlers(f);
CompletableFuture<Object> invokeFuture = chain.invokeAsync(newInvocationContext(), testCommand);
assertHandlers(invokeFuture);
}
private void assertHandlers(CompletableFuture<Object> invokeFuture)
throws InterruptedException, ExecutionException {
assertEquals("|handle|thenApply", invokeFuture.get());
assertEquals("|whenComplete|handle|thenAccept|thenApply", sideEffects.get());
}
public void testAsyncInvocationManyHandlersSyncException() throws Exception {
sideEffects.set("");
CompletableFuture<Object> f = CompletableFuture.failedFuture(new TestException(""));
AsyncInterceptorChain chain = makeChainWithManyHandlers(f);
CompletableFuture<Object> invokeFuture = chain.invokeAsync(newInvocationContext(), testCommand);
assertExceptionHandlers(invokeFuture);
}
public void testAsyncInvocationManyHandlersAsyncException() throws Exception {
sideEffects.set("");
CompletableFuture<Object> f = new CompletableFuture<>();
AsyncInterceptorChain chain = makeChainWithManyHandlers(f);
CompletableFuture<Object> invokeFuture = chain.invokeAsync(newInvocationContext(), testCommand);
f.completeExceptionally(new TestException(""));
assertExceptionHandlers(invokeFuture);
}
private void assertExceptionHandlers(CompletableFuture<Object> invokeFuture) {
String expectedMessage = "|whenComplete|handle|exceptionally";
expectExecutionException(TestException.class, Pattern.quote(expectedMessage), invokeFuture);
assertEquals("|whenComplete|handle|exceptionally", sideEffects.get());
}
private AsyncInterceptorChain makeChainWithManyHandlers(CompletableFuture<Object> f) {
return newInterceptorChain(new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextThenApply(ctx, command, (rCtx, rCommand, rv) ->
afterInvokeNext(ctx, rCtx, command, rCommand, rv, null, "|thenApply"));
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextThenAccept(ctx, command, (rCtx, rCommand, rv) ->
afterInvokeNext(ctx, rCtx, command, rCommand, rv, null, "|thenAccept"));
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextAndExceptionally(ctx, command, (rCtx, rCommand, t) ->
afterInvokeNext(ctx, rCtx, command, rCommand, null, t, "|exceptionally"));
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextAndHandle(ctx, command, (rCtx, rCommand, rv, t) ->
afterInvokeNext(ctx, rCtx, command, rCommand, rv, t, "|handle"));
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextAndFinally(ctx, command, (rCtx, rCommand, rv, t) ->
afterInvokeNext(ctx, rCtx, command, rCommand, rv, t, "|whenComplete"));
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return asyncValue(f);
}
});
}
private String afterInvokeNext(Object rv, Throwable t, String text) {
sideEffects.set(sideEffects.get() + text);
if (t == null) {
return rv.toString() + text;
} else {
throw new TestException(t.getMessage() + text);
}
}
private String afterInvokeNext(VisitableCommand expectedCommand, VisitableCommand command, Object rv, Throwable t,
String text) {
assertEquals(expectedCommand, command);
return afterInvokeNext(rv, t, text);
}
private String afterInvokeNext(InvocationContext expectedCtx, InvocationContext ctx,
VisitableCommand expectedCommand, VisitableCommand command, Object rv, Throwable t,
String text) {
assertEquals(expectedCtx, ctx);
return afterInvokeNext(expectedCommand, command, rv, t, text);
}
public void testDeadlockWithAsyncStage() throws Exception {
CompletableFuture<Object> f1 = new CompletableFuture<>();
CompletableFuture<Object> f2 = new CompletableFuture<>();
AsyncInterceptorChain chain = newInterceptorChain(new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextThenApply(ctx, command, (rCtx, rCommand, rv) -> rv + " " + awaitFuture(f2));
}
}, new BaseAsyncInterceptor() {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
// Add a handler to force the return value to be a full AsyncInvocationStage
InvocationSuccessFunction function = (rCtx, rCommand, rv) -> rv;
return asyncValue(f1).addCallback(ctx, command, function);
}
});
InvocationContext context = newInvocationContext();
CompletableFuture<Object> invokeFuture = chain.invokeAsync(context, testCommand);
assertFalse(invokeFuture.isDone());
Future<Boolean> fork = fork(() -> f1.complete("v1"));
Thread.sleep(100);
assertFalse(fork.isDone());
assertFalse(invokeFuture.isDone());
f2.complete("v2");
fork.get(10, SECONDS);
assertEquals("v1 v2", invokeFuture.getNow(null));
}
private Object awaitFuture(CompletableFuture<Object> f2) {
try {
return f2.get(10, SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw CompletableFutures.asCompletionException(e);
}
}
private SingleKeyNonTxInvocationContext newInvocationContext() {
// Actual implementation doesn't matter, we are only testing the BaseAsyncInvocationContext methods
return new SingleKeyNonTxInvocationContext(null);
}
private AsyncInterceptorChain newInterceptorChain(AsyncInterceptor... interceptors) {
AsyncInterceptorChainImpl chain = new AsyncInterceptorChainImpl();
for (AsyncInterceptor i : interceptors) {
chain.appendInterceptor(i, false);
}
return chain;
}
}
| 16,923
| 42.506427
| 117
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/interceptors/impl/AsyncInterceptorChainTest.java
|
package org.infinispan.interceptors.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.AsyncInterceptor;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* Tests {@link AsyncInterceptorChainImpl} concurrent updates
*
* @author Galder Zamarreño
* @author Sanne Grinovero
* @author Dan Berindei
* @since 9.0
*/
@Test(groups = "functional", testName = "interceptors.AsyncInterceptorChainTest")
public class AsyncInterceptorChainTest extends AbstractInfinispanTest {
private static final Log log = LogFactory.getLog(AsyncInterceptorChainTest.class);
public void testConcurrentAddRemove() throws Exception {
AsyncInterceptorChainImpl ic = new AsyncInterceptorChainImpl();
ic.addInterceptor(new DummyCallInterceptor(), 0);
ic.addInterceptor(new DummyActivationInterceptor(), 1);
CyclicBarrier barrier = new CyclicBarrier(4);
List<Future<Void>> futures = new ArrayList<>(2);
ExecutorService executorService = Executors.newFixedThreadPool(3, getTestThreadFactory("Worker"));
try {
// We do test concurrent add/remove of different types per thread,
// so that the final result is predictable (testable) and that we
// can not possibly fail because of the InterceptorChain checking
// that no interceptor is ever added twice.
futures.add(executorService.submit(new InterceptorChainUpdater(ic, barrier, new DummyCacheMgmtInterceptor())));
futures.add(executorService.submit(new InterceptorChainUpdater(ic, barrier, new DummyDistCacheWriterInterceptor())));
futures.add(executorService.submit(new InterceptorChainUpdater(ic, barrier, new DummyInvalidationInterceptor())));
barrier.await(); // wait for all threads to be ready
barrier.await(); // wait for all threads to finish
log.debug("All threads finished, let's shutdown the executor and check whether any exceptions were reported");
for (Future<Void> future : futures) future.get();
} finally {
executorService.shutdownNow();
}
assert ic.containsInterceptorType(DummyCallInterceptor.class);
assert ic.containsInterceptorType(DummyActivationInterceptor.class);
assert ic.containsInterceptorType(DummyCacheMgmtInterceptor.class);
assert ic.containsInterceptorType(DummyDistCacheWriterInterceptor.class);
assert ic.containsInterceptorType(DummyInvalidationInterceptor.class);
assert ic.getInterceptors().size() == 5 : "Resulting interceptor chain was actually " + ic.getInterceptors();
}
private static class InterceptorChainUpdater implements Callable<Void> {
private final AsyncInterceptorChain ic;
private final CyclicBarrier barrier;
private final AsyncInterceptor interceptor;
InterceptorChainUpdater(AsyncInterceptorChain ic, CyclicBarrier barrier, AsyncInterceptor interceptor) {
this.ic = ic;
this.barrier = barrier;
this.interceptor = interceptor;
}
@Override
public Void call() throws Exception {
final Class<? extends AsyncInterceptor> interceptorClass = interceptor.getClass();
try {
log.debug("Wait for all executions paths to be ready to perform calls");
barrier.await();
// test in a loop as the barrier is otherwise not enough to make sure
// the different testing threads actually do make changes concurrently
// 2000 is still almost nothing in terms of testsuite time.
for (int i = 0; i < 2000; i++) {
ic.removeInterceptor(interceptorClass);
ic.addInterceptor(interceptor, 1);
}
return null;
} finally {
log.debug("Wait for all execution paths to finish");
barrier.await();
}
}
}
static class DummyCallInterceptor extends BaseAsyncInterceptor {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command)
throws Throwable {
return null;
}
}
static class DummyActivationInterceptor extends DummyCallInterceptor {
}
static class DummyCacheMgmtInterceptor extends DummyCallInterceptor {
}
static class DummyDistCacheWriterInterceptor extends DummyCallInterceptor {
}
static class DummyInvalidationInterceptor extends DummyCallInterceptor {
}
}
| 4,973
| 41.512821
| 126
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/interceptors/impl/CacheWriterTxModificationsTest.java
|
package org.infinispan.interceptors.impl;
import static org.infinispan.test.TestingUtil.mapOf;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.DataContainer;
import org.infinispan.functional.FunctionalMap;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.functional.impl.WriteOnlyMapImpl;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.persistence.dummy.DummyInMemoryStore;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.testng.annotations.Test;
/**
* Test that tx modifications are properly applied in stores.
*
* <p>It's a unit test, but uses a full cache manager because it's easier to set up.
* See ISPN-10022.</p>
*
* @since 10.0
*/
@Test(groups = "unit", testName = "interceptors.impl.CacheWriterTxModificationsTest")
public class CacheWriterTxModificationsTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder config = new ConfigurationBuilder();
config.transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC);
config.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class);
return TestCacheManagerFactory.createCacheManager(config);
}
public void testCommit() throws Throwable {
FunctionalMapImpl<Object, Object> functionalMap = FunctionalMapImpl.create(cache.getAdvancedCache());
FunctionalMap.WriteOnlyMap<Object, Object> woMap = WriteOnlyMapImpl.create(functionalMap);
FunctionalMap.ReadWriteMap<Object, Object> rwMap = ReadWriteMapImpl.create(functionalMap);
DummyInMemoryStore store = TestingUtil.getFirstStore(cache);
cache.putAll(mapOf("remove", "initial",
"replace", "initial",
"computeIfPresent", "initial",
"woRemove", "initial",
"rwRemove", "initial"));
tm().begin();
try {
cache.put("put", "value");
cache.putIfAbsent("putIfAbsent", "value");
cache.remove("remove");
cache.replace("replace", "value");
cache.compute("compute", (k, v) -> "value");
cache.computeIfAbsent("computeIfAbsent", k -> "value");
cache.computeIfPresent("computeIfPresent", (k, v) -> "value");
cache.putAll(mapOf("putAll", "value"));
woMap.eval("woSet", entry -> entry.set("value"));
woMap.eval("woRemove", entry -> entry.set("value"));
woMap.eval("rwSet", entry -> entry.set("value"));
woMap.eval("rwRemove", entry -> entry.set("value"));
} finally {
tm().commit();
}
DataContainer<Object, Object> dataContainer = cache.getAdvancedCache().getDataContainer();
dataContainer.forEach(entry -> {
MarshallableEntry storeEntry = store.loadEntry(entry.getKey());
assertNotNull("Missing store entry: " + entry.getKey(), storeEntry);
assertEquals(entry.getValue(), storeEntry.getValue());
});
store.keySet().forEach(k -> {
assertEquals(store.loadEntry(k).getValue(), dataContainer.get(k).getValue());
});
}
}
| 3,734
| 44
| 111
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/interceptors/impl/CacheMgmtInterceptorTest.java
|
package org.infinispan.interceptors.impl;
import static org.infinispan.interceptors.BaseAsyncInterceptor.makeStage;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.read.GetAllCommand;
import org.infinispan.commands.read.GetCacheEntryCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.SingleKeyNonTxInvocationContext;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.interceptors.InvocationStage;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.test.TestException;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.ControlledTimeService;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "interceptors.impl.CacheMgmtInterceptorTest")
public class CacheMgmtInterceptorTest extends AbstractInfinispanTest {
public static final String KEY = "key";
public static final String VALUE = "value";
private CacheMgmtInterceptor interceptor;
private ControlledNextInterceptor nextInterceptor;
private ControlledTimeService timeService;
private InvocationContext ctx;
@BeforeMethod(alwaysRun = true)
public void setup() {
nextInterceptor = new ControlledNextInterceptor();
timeService = new ControlledTimeService();
ctx = new SingleKeyNonTxInvocationContext(null);
interceptor = new CacheMgmtInterceptor();
interceptor.setNextInterceptor(nextInterceptor);
TestingUtil.inject(interceptor, timeService);
interceptor.start();
interceptor.setStatisticsEnabled(true);
}
public void testVisitGetKeyValueCommand() throws Throwable {
GetKeyValueCommand command = new GetKeyValueCommand(KEY, 0, 0);
InvocationStage stage = makeStage(interceptor.visitGetKeyValueCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocation(null);
assertNull(stage.get());
assertEquals(1, interceptor.getAverageReadTime());
}
public void testVisitGetKeyValueCommandException() throws Throwable {
GetKeyValueCommand command = new GetKeyValueCommand(KEY, 0, 0);
InvocationStage stage = makeStage(interceptor.visitGetKeyValueCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocationExceptionally(new TestException());
expectInvocationException(stage);
assertEquals(1, interceptor.getAverageReadTime());
}
public void testVisitGetCacheEntryCommand() throws Throwable {
GetCacheEntryCommand command = new GetCacheEntryCommand(KEY, 0, 0);
InvocationStage stage = makeStage(interceptor.visitGetCacheEntryCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocation(null);
assertNull(stage.get());
assertEquals(1, interceptor.getAverageReadTime());
}
public void testVisitGetCacheEntryCommandException() throws Throwable {
GetCacheEntryCommand command = new GetCacheEntryCommand(KEY, 0, 0);
InvocationStage stage = makeStage(interceptor.visitGetCacheEntryCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocationExceptionally(new TestException());
expectInvocationException(stage);
assertEquals(1, interceptor.getAverageReadTime());
}
public void testVisitGetAllCommand() throws Throwable {
GetAllCommand command = new GetAllCommand(Collections.singleton(KEY), 0, false);
InvocationStage stage = makeStage(interceptor.visitGetAllCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocation(Collections.emptyMap());
assertEquals(Collections.emptyMap(), stage.get());
assertEquals(1, interceptor.getAverageReadTime());
}
public void testVisitGetAllCommandException() throws Throwable {
GetAllCommand command = new GetAllCommand(Collections.singleton(KEY), 0, false);
InvocationStage stage = makeStage(interceptor.visitGetAllCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocationExceptionally(new TestException());
expectInvocationException(stage);
assertEquals(1, interceptor.getAverageReadTime());
}
public void testVisitPutMapCommand() throws Throwable {
PutMapCommand command = new PutMapCommand(Collections.singletonMap(KEY, VALUE), null, 0, null);
InvocationStage stage = makeStage(interceptor.visitPutMapCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocation(null);
assertNull(stage.get());
assertEquals(1, interceptor.getAverageWriteTime());
}
public void testVisitPutMapCommandException() throws Throwable {
PutMapCommand command = new PutMapCommand(Collections.singletonMap(KEY, VALUE), null, 0, null);
InvocationStage stage = makeStage(interceptor.visitPutMapCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocationExceptionally(new TestException());
expectInvocationException(stage);
assertEquals(1, interceptor.getAverageWriteTime());
}
public void testVisitPutKeyValueCommand() throws Throwable {
PutKeyValueCommand command = new PutKeyValueCommand(KEY, VALUE, false, false, null, 0, 0, null);
InvocationStage stage = makeStage(interceptor.visitPutKeyValueCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocation(null);
assertNull(stage.get());
assertEquals(1, interceptor.getAverageWriteTime());
}
public void testVisitPutKeyValueCommandException() throws Throwable {
PutKeyValueCommand command = new PutKeyValueCommand(KEY, VALUE, false, false, null, 0, 0, null);
InvocationStage stage = makeStage(interceptor.visitPutKeyValueCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocationExceptionally(new TestException());
expectInvocationException(stage);
assertEquals(1, interceptor.getAverageWriteTime());
}
public void testVisitReplaceCommand() throws Throwable {
ReplaceCommand command = new ReplaceCommand(KEY, VALUE, false, false, null, 0, 0, null);
InvocationStage stage = makeStage(interceptor.visitReplaceCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocation(null);
assertNull(stage.get());
assertEquals(1, interceptor.getAverageWriteTime());
}
public void testVisitReplaceCommandException() throws Throwable {
ReplaceCommand command = new ReplaceCommand(KEY, VALUE, false, false, null, 0, 0, null);
InvocationStage stage = makeStage(interceptor.visitReplaceCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocationExceptionally(new TestException());
expectInvocationException(stage);
assertEquals(1, interceptor.getAverageWriteTime());
}
public void testVisitRemoveCommand() throws Throwable {
RemoveCommand command = new RemoveCommand(KEY, null, false, 0, 0, null);
InvocationStage stage = makeStage(interceptor.visitRemoveCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocation(VALUE);
assertEquals(VALUE, stage.get());
assertEquals(1, interceptor.getAverageRemoveTime());
}
public void testVisitRemoveCommandException() throws Throwable {
RemoveCommand command = new RemoveCommand(KEY, null, false, 0, 0, null);
InvocationStage stage = makeStage(interceptor.visitRemoveCommand(ctx, command));
assertFalse(stage.isDone());
timeService.advance(1);
nextInterceptor.completeLastInvocationExceptionally(new TestException());
expectInvocationException(stage);
assertEquals(0, interceptor.getAverageRemoveTime());
}
private void expectInvocationException(InvocationStage stage) {
Exceptions.expectException(TestException.class, () -> {
try {
stage.get();
} catch (Exception e) {
throw e;
} catch (Throwable t) {
throw new Exception(t);
}
});
}
class ControlledNextInterceptor extends BaseAsyncInterceptor {
CompletableFuture<Object> lastReturnValue;
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
lastReturnValue = new CompletableFuture<>();
return asyncValue(lastReturnValue);
}
public void completeLastInvocation(Object value) {
lastReturnValue.complete(value);
}
public void completeLastInvocationExceptionally(Throwable t) {
lastReturnValue.completeExceptionally(t);
}
}
}
| 9,797
| 37.727273
| 102
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/interceptors/impl/QueueAsyncInvocationStageTest.java
|
package org.infinispan.interceptors.impl;
import static org.testng.AssertJUnit.assertEquals;
import java.util.concurrent.CompletableFuture;
import org.infinispan.interceptors.InvocationCallback;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* @author Dan Berindei
* @since 9.0
*/
@Test(groups = "unit", testName = "interceptors.QueueAsyncInvocationStageTest")
public class QueueAsyncInvocationStageTest extends AbstractInfinispanTest {
@DataProvider(name = "offsets")
public Object[][] offsets() {
return new Object[][]{{0}, {1}};
}
@Test(dataProvider = "offsets")
public void testExpandCapacity(int splitOffset) throws Throwable {
CompletableFuture<Object> future = new CompletableFuture<>();
QueueAsyncInvocationStage stage =
new QueueAsyncInvocationStage(null, null, future, makeCallback(0));
assertCallback(0, stage.queuePoll());
addAndPoll(stage, splitOffset);
// Now trigger 2 expansions
int count = 2 * QueueAsyncInvocationStage.QUEUE_INITIAL_CAPACITY;
addAndPoll(stage, count);
}
private InvocationCallback makeCallback(int i) {
return (rCtx, rCommand, rv, throwable) -> "v" + i;
}
private void assertCallback(int index, InvocationCallback callback) throws Throwable {
assertEquals("v" + index, callback.apply(null, null, null, null));
}
private void addAndPoll(QueueAsyncInvocationStage stage, int splitOffset) throws Throwable {
for (int i = 0; i < splitOffset; i++) {
stage.queueAdd(makeCallback(i));
}
assertEquals(splitOffset, stage.queueSize());
for (int i = 0; i < splitOffset; i++) {
assertCallback(i, stage.queuePoll());
}
assertEquals(0, stage.queueSize());
}
}
| 1,843
| 32.527273
| 95
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/StoreAsBinaryConfigTest.java
|
package org.infinispan.marshall;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
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.AfterMethod;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.assertEquals;
@Test(groups = "functional", testName = "marshall.StoreAsBinaryConfigTest")
public class StoreAsBinaryConfigTest extends AbstractInfinispanTest {
EmbeddedCacheManager ecm;
@AfterMethod
public void cleanup() {
TestingUtil.killCacheManagers(ecm);
ecm = null;
}
public void testBackwardCompatibility() {
ConfigurationBuilder c = new ConfigurationBuilder();
c.memory().storageType(StorageType.BINARY);
ecm = TestCacheManagerFactory.createCacheManager(c);
assertEquals(StorageType.BINARY, ecm.getCache().getCacheConfiguration().memory().storageType());
}
public void testConfigCloning() {
ConfigurationBuilder c = new ConfigurationBuilder();
c.memory().storageType(StorageType.BINARY);
ConfigurationBuilder builder = new ConfigurationBuilder().read(c.build(), Combine.DEFAULT);
Configuration clone = builder.build();
assertEquals(StorageType.BINARY, clone.memory().storageType());
}
public void testConfigOverriding() {
ConfigurationBuilder c = new ConfigurationBuilder();
c.memory().storageType(StorageType.BINARY);
ecm = TestCacheManagerFactory.createCacheManager(c);
ecm.defineConfiguration("newCache", new ConfigurationBuilder().read(c.build(), Combine.DEFAULT).memory().storageType(StorageType.OBJECT).build());
assertEquals(StorageType.OBJECT, ecm.getCache("newCache").getCacheConfiguration().memory().storageType());
}
}
| 2,049
| 39.196078
| 152
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/MarshallExternalizersTest.java
|
package org.infinispan.marshall;
import static org.infinispan.test.TestingUtil.k;
import static org.testng.AssertJUnit.assertEquals;
import java.lang.reflect.Method;
import org.infinispan.Cache;
import org.infinispan.commons.marshall.PojoWithSerializeWith;
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.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "marshall.MarshallExternalizersTest")
public class MarshallExternalizersTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
createCluster(globalConfigurationBuilder(), configBuilder(), 2);
waitForClusterToForm();
}
protected ConfigurationBuilder configBuilder() {
return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false);
}
protected GlobalConfigurationBuilder globalConfigurationBuilder() {
GlobalConfigurationBuilder globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder();
globalBuilder.serialization().addContextInitializer(TestDataSCI.INSTANCE);
return globalBuilder;
}
public void testReplicateMarshallableByPojo(Method m) {
PojoWithSerializeWith pojo = new PojoWithSerializeWith(17, k(m));
doReplicatePojo(m, pojo);
}
@Test(dependsOnMethods = "testReplicateMarshallableByPojo")
public void testReplicateMarshallableByPojoToNewJoiningNode(Method m) {
PojoWithSerializeWith pojo = new PojoWithSerializeWith(85, k(m));
doReplicatePojoToNewJoiningNode(m, pojo);
}
protected void doReplicatePojo(Method m, Object o) {
Cache cache1 = manager(0).getCache();
Cache cache2 = manager(1).getCache();
cache1.put(k(m), o);
assertEquals(o, cache2.get(k(m)));
}
protected void doReplicatePojoToNewJoiningNode(Method m, Object o) {
Cache cache1 = manager(0).getCache();
EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(globalConfigurationBuilder(), configBuilder());
try {
Cache cache3 = cm.getCache();
cache1.put(k(m), o);
assertEquals(o, cache3.get(k(m)));
} finally {
cm.stop();
}
}
}
| 2,518
| 35.507246
| 131
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/DuplicateIdTest.java
|
package org.infinispan.marshall;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.infinispan.commons.marshall.Ids;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "marshall.DuplicateIdTest")
public class DuplicateIdTest extends AbstractInfinispanTest {
public void testDuplicateMarshallerIds() throws Exception {
Class idHolder = Ids.class;
Map<Integer, Set<String>> dupes = new HashMap<>();
for (Field f : idHolder.getDeclaredFields()) {
if (Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers()) && f.getType().equals(int.class)) {
int val = (Integer) f.get(null);
Set<String> names = dupes.get(val);
if (names == null) names = new HashSet<String>();
names.add(f.getName());
dupes.put(val, names);
}
}
int largest = 0;
for (Map.Entry<Integer, Set<String>> e : dupes.entrySet()) {
assert e.getValue().size() == 1 : "ID " + e.getKey() + " is duplicated by fields " + e.getValue();
largest = Math.max(largest, e.getKey());
}
log.trace("Next available ID is " + (largest + 1));
}
}
| 1,352
| 34.605263
| 122
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/ServiceLoadSerializationContextInitializerTest.java
|
package org.infinispan.marshall;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "marshall.ServiceLoadSerializationContextInitializerTest")
public class ServiceLoadSerializationContextInitializerTest extends AbstractInfinispanTest {
public void testSCILoaded() throws Exception {
try (EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(true)) {
SerializationContextRegistry registry = TestingUtil.extractGlobalComponent(cm, SerializationContextRegistry.class);
assertTrue(registry.getUserCtx().canMarshall(ServiceLoadedClass.class));
assertFalse(registry.getGlobalCtx().canMarshall(ServiceLoadedClass.class));
assertFalse(registry.getPersistenceCtx().canMarshall(ServiceLoadedClass.class));
}
}
static class ServiceLoadedClass {
@ProtoField(1)
String field;
}
@AutoProtoSchemaBuilder(
includeClasses = ServiceLoadedClass.class,
schemaFileName = "test.core.protostream-service-loaded-class.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.test.marshall"
)
interface ServiceLoadedSci extends SerializationContextInitializer {
}
}
| 1,802
| 41.928571
| 124
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/AdvancedExternalizerQuickConfigTest.java
|
package org.infinispan.marshall;
import java.util.Map;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.testng.annotations.Test;
/**
* Tests configuration of user defined {@link AdvancedExternalizer} implementations
* using helpers methods in {@link GlobalConfigurationBuilder}.
*
* @author Galder Zamarreño
* @since 5.0
*/
@Test(groups = "functional", testName = "marshall.AdvancedExternalizerQuickConfigTest")
public class AdvancedExternalizerQuickConfigTest extends AdvancedExternalizerTest {
@Override
protected GlobalConfigurationBuilder createForeignExternalizerGlobalConfig() {
GlobalConfigurationBuilder builder = new GlobalConfigurationBuilder().clusteredDefault();
builder.serialization()
.addAdvancedExternalizer(1234, new IdViaConfigObj.Externalizer())
.addAdvancedExternalizer(new IdViaAnnotationObj.Externalizer())
.addAdvancedExternalizer(3456, new IdViaBothObj.Externalizer());
return builder;
}
public void testExternalizerConfigInfo() {
Map<Integer, AdvancedExternalizer<?>> advExts =
manager(0).getCacheManagerConfiguration().serialization().advancedExternalizers();
assert advExts.size() == 3;
AdvancedExternalizer<?> ext = advExts.get(1234);
assert ext != null;
assert ext.getClass() == IdViaConfigObj.Externalizer.class;
ext = advExts.get(5678);
assert ext != null;
assert ext.getClass() == IdViaAnnotationObj.Externalizer.class;
assert ext.getId() == 5678;
ext = advExts.get(3456);
assert ext != null;
assert ext.getClass() == IdViaBothObj.Externalizer.class;
}
@Override
protected String getCacheName() {
return "ForeignExternalizersQuickConfig";
}
}
| 1,841
| 35.117647
| 95
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/DefensiveCopyTest.java
|
package org.infinispan.marshall;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
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.TestDataSCI;
import org.infinispan.test.data.Person;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* Tests defensive copy logic.
*
* @author Galder Zamarreño
* @since 5.3
*/
@Test(groups = "functional", testName = "marshall.DefensiveCopyTest")
public class DefensiveCopyTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.memory().storageType(StorageType.BINARY);
return TestCacheManagerFactory.createCacheManager(TestDataSCI.INSTANCE, builder);
}
public void testOriginalReferenceSafety() {
Person key = new Person("Key1");
Person value = new Person("Mr Infinispan");
cache().put(key, value);
assertEquals(value, cache.get(key));
// Change referenced object
value.setName("Ms Hibernate");
// If defensive copies are working as expected,
// it should be same as before
assertEquals(new Person("Mr Infinispan"), cache.get(key));
key.setName("Key2");
assertNull(cache.get(key));
}
public void testSafetyAfterRetrieving() {
final Integer k = 2;
Person person = new Person("Mr Coe");
cache().put(k, person);
Person cachedPerson = this.<Integer, Person>cache().get(k);
assertEquals(person, cachedPerson);
cachedPerson.setName("Mr Digweed");
assertEquals(person, cache.get(k));
}
}
| 1,900
| 33.563636
| 87
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/MarshallerPickAfterCacheRestart.java
|
package org.infinispan.marshall;
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.configuration.cache.StorageType;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.Test;
/**
* Tests the marshaller is picked correctly when a cache is restarted.
*
* @author Galder Zamarreño
* @since 5.1
*/
@Test(groups = "functional", testName = "marshall.MarshallerPickAfterCacheRestart")
public class MarshallerPickAfterCacheRestart extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.memory().storageType(StorageType.BINARY)
.clustering()
.cacheMode(CacheMode.REPL_SYNC)
.stateTransfer().fetchInMemoryState(false);
createCluster(builder, 2);
}
public void testCacheRestart() throws Exception {
final Cache<Integer, String> cache0 = cache(0);
final Cache<Integer, String> cache1 = cache(1);
// Restart the cache
cache1.stop();
cache1.start();
cache1.put(1, "value1");
assertEquals("value1", cache0.get(1));
}
}
| 1,349
| 29
| 83
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/ConcurrentMarshallerTest.java
|
package org.infinispan.marshall;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Future;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* Add test that exercises concurrent behaviour of both
* {@link org.infinispan.interceptors.IsMarshallableInterceptor}
* and marshalling layer.
*
* @author Galder Zamarreño
* @since 5.1
*/
@Test(groups = "functional", testName = "marshall.ConcurrentMarshallerTest")
public class ConcurrentMarshallerTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(
CacheMode.REPL_ASYNC, false);
createClusteredCaches(2, "concurrentMarshaller", builder);
}
public void test000() throws Exception {
final Cache cache1 = cache(0,"concurrentMarshaller");
int nbWriters = 10;
final CyclicBarrier barrier = new CyclicBarrier(nbWriters + 1);
List<Future<Void>> futures = new ArrayList<Future<Void>>(nbWriters);
for (int i = 0; i < nbWriters; i++) {
log.debug("Schedule execution");
Future<Void> future = fork(
new CacheUpdater(barrier, cache1));
futures.add(future);
}
barrier.await(); // wait for all threads to be ready
barrier.await(); // wait for all threads to finish
log.debug("Threads finished, shutdown executor and check for exceptions");
for (Future<Void> future : futures) future.get();
}
static class CacheUpdater implements Callable<Void> {
static final Log log = LogFactory.getLog(CacheUpdater.class);
CyclicBarrier barrier;
Cache cache;
CacheUpdater(CyclicBarrier barrier, Cache cache) {
this.barrier = barrier;
this.cache = cache;
}
@Override
public Void call() throws Exception {
log.debug("Wait for all executions paths to be ready");
barrier.await();
try {
for (int i = 0; i < 10; i ++) {
String decimal = Integer.toString(i);
byte[] key = ("key-" + Thread.currentThread().getName() + decimal).getBytes();
byte[] value = ("value-" + Thread.currentThread().getName() + decimal).getBytes();
cache.put(key, value);
}
return null;
} finally {
log.debug("Wait for all execution paths to finish");
barrier.await();
}
}
}
}
| 2,862
| 31.168539
| 97
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/InvalidatedMarshalledValueTest.java
|
package org.infinispan.marshall;
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.configuration.cache.StorageType;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.data.CountMarshallingPojo;
import org.testng.annotations.Test;
/**
* Tests that invalidation and lazy deserialization works as expected.
*
* @author Galder Zamarreño
* @since 4.2
*/
@Test(groups = "functional", testName = "marshall.InvalidatedMarshalledValueTest")
public class InvalidatedMarshalledValueTest extends MultipleCacheManagersTest {
private static final String POJO_NAME = InvalidatedMarshalledValueTest.class.getName();
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder invlSync = getDefaultClusteredCacheConfig(CacheMode.INVALIDATION_SYNC, false);
invlSync.memory().storageType(StorageType.BINARY);
createClusteredCaches(2, "invlSync", TestDataSCI.INSTANCE, invlSync);
}
public void testModificationsOnSameCustomKey() {
CountMarshallingPojo.reset(POJO_NAME);
Cache<CountMarshallingPojo, String> cache1 = cache(0, "invlSync");
Cache<CountMarshallingPojo, String> cache2 = cache(1, "invlSync");
CountMarshallingPojo key = new CountMarshallingPojo(POJO_NAME, 1);
cache2.put(key, "1");
cache1.put(key, "2");
// Marshalling is done eagerly now, so no need for extra serialization checks
assertSerializationCounts(2, 0);
cache1.put(key, "3");
// +2 carried on here.
assertSerializationCounts(3, 0);
}
private void assertSerializationCounts(int expectedSerializationCount, int expectedDeserializationCount) {
assertEquals("Wrong marshall count", expectedSerializationCount, CountMarshallingPojo.getMarshallCount(
POJO_NAME));
assertEquals("Wrong unmarshall count", expectedDeserializationCount, CountMarshallingPojo.getUnmarshallCount(
POJO_NAME));
}
}
| 2,161
| 38.309091
| 115
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/AbstractSerializationContextInitializer.java
|
package org.infinispan.marshall;
import org.infinispan.protostream.FileDescriptorSource;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.SerializationContextInitializer;
public abstract class AbstractSerializationContextInitializer implements SerializationContextInitializer {
private final String fileName;
public AbstractSerializationContextInitializer(String fileName) {
this.fileName = fileName;
}
@Override
public String getProtoFileName() {
return fileName;
}
@Override
public String getProtoFile() {
return FileDescriptorSource.getResourceAsString(getClass(), "/" + fileName);
}
@Override
public void registerSchema(SerializationContext ctx) {
ctx.registerProtoFiles(FileDescriptorSource.fromString(getProtoFileName(), getProtoFile()));
}
@Override
public void registerMarshallers(SerializationContext serCtx) {
}
}
| 942
| 26.735294
| 106
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/VersionAwareMarshallerTest.java
|
package org.infinispan.marshall;
import static org.infinispan.test.TestingUtil.extractGlobalMarshaller;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
import java.io.ByteArrayInputStream;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commands.remote.ClusteredGetCommand;
import org.infinispan.commands.statetransfer.StateTransferStartCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.InvalidateCommand;
import org.infinispan.commands.write.InvalidateL1Command;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.marshall.MarshallingException;
import org.infinispan.commons.marshall.PojoWithSerializeWith;
import org.infinispan.commons.marshall.SerializeWith;
import org.infinispan.commons.marshall.StreamingMarshaller;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.commons.util.FastCopyHashMap;
import org.infinispan.commons.util.Immutables;
import org.infinispan.commons.util.IntSets;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.container.entries.ImmortalCacheEntry;
import org.infinispan.container.entries.ImmortalCacheValue;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.entries.MortalCacheEntry;
import org.infinispan.container.entries.MortalCacheValue;
import org.infinispan.container.entries.TransientCacheEntry;
import org.infinispan.container.entries.TransientCacheValue;
import org.infinispan.container.entries.TransientMortalCacheEntry;
import org.infinispan.container.entries.TransientMortalCacheValue;
import org.infinispan.context.Flag;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.metadata.EmbeddedMetadata;
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.remoting.responses.ExceptionResponse;
import org.infinispan.remoting.responses.UnsuccessfulResponse;
import org.infinispan.remoting.responses.UnsureResponse;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.jgroups.JGroupsAddress;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.data.BrokenMarshallingPojo;
import org.infinispan.test.data.Key;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.test.fwk.TestInternalCacheEntryFactory;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.transaction.xa.TransactionFactory;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.TimeoutException;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.UUID;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "marshall.VersionAwareMarshallerTest")
public class VersionAwareMarshallerTest extends AbstractInfinispanTest {
private static final Log log = LogFactory.getLog(VersionAwareMarshallerTest.class);
protected StreamingMarshaller marshaller;
private EmbeddedCacheManager cm;
private final TransactionFactory gtf = new TransactionFactory();
public VersionAwareMarshallerTest() {
gtf.init(false, false, true, false);
}
@BeforeClass
public void setUp() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.clustering().cacheMode(CacheMode.DIST_SYNC);
cm = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration(), builder);
marshaller = extractGlobalMarshaller(cm);
}
protected GlobalConfigurationBuilder globalConfiguration() {
// Use a clustered cache manager to be able to test global marshaller interaction too
GlobalConfigurationBuilder globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder();
globalBuilder.serialization().addAdvancedExternalizer(new PojoWithExternalAndInternal.Externalizer());
globalBuilder.serialization().addAdvancedExternalizer(new PojoWithExternalizer.Externalizer());
globalBuilder.serialization().addAdvancedExternalizer(new PojoWithMultiExternalizer.Externalizer());
globalBuilder.serialization().serialization().addContextInitializer(new VersionAwareMarshallerSCIImpl());
return globalBuilder;
}
@AfterClass
public void tearDown() {
cm.stop();
}
public void testJGroupsAddressMarshalling() throws Exception {
JGroupsAddress address = new JGroupsAddress(UUID.randomUUID());
marshallAndAssertEquality(address);
}
public void testGlobalTransactionMarshalling() throws Exception {
JGroupsAddress jGroupsAddress = new JGroupsAddress(UUID.randomUUID());
GlobalTransaction gtx = gtf.newGlobalTransaction(jGroupsAddress, false);
marshallAndAssertEquality(gtx);
}
public void testListMarshalling() throws Exception {
List<GlobalTransaction> l1 = new ArrayList<>();
List<GlobalTransaction> l2 = new LinkedList<>();
for (int i = 0; i < 10; i++) {
JGroupsAddress jGroupsAddress = new JGroupsAddress(new IpAddress("localhost", 1000 * i));
GlobalTransaction gtx = gtf.newGlobalTransaction(jGroupsAddress, false);
l1.add(gtx);
l2.add(gtx);
}
marshallAndAssertEquality(l1);
marshallAndAssertEquality(l2);
}
public void testMapMarshalling() throws Exception {
Map<Integer, GlobalTransaction> m1 = new HashMap<>();
Map<Integer, GlobalTransaction> m2 = new TreeMap<>();
Map<Integer, GlobalTransaction> m3 = new HashMap<>();
Map<Integer, GlobalTransaction> m4 = new FastCopyHashMap<>();
for (int i = 0; i < 10; i++) {
JGroupsAddress jGroupsAddress = new JGroupsAddress(UUID.randomUUID());
GlobalTransaction gtx = gtf.newGlobalTransaction(jGroupsAddress, false);
m1.put(1000 * i, gtx);
m2.put(1000 * i, gtx);
m4.put(1000 * i, gtx);
}
Map m5 = Immutables.immutableMapWrap(m3);
marshallAndAssertEquality(m1);
marshallAndAssertEquality(m2);
byte[] bytes = marshaller.objectToByteBuffer(m4);
Map<Integer, GlobalTransaction> m4Read = (Map<Integer, GlobalTransaction>) marshaller.objectFromByteBuffer(bytes);
for (Map.Entry<Integer, GlobalTransaction> entry : m4.entrySet()) {
assert m4Read.get(entry.getKey()).equals(entry.getValue()) : "Writen[" + entry.getValue() + "] and read[" + m4Read.get(entry.getKey()) + "] objects should be the same";
}
marshallAndAssertEquality(m5);
}
public void testSetMarshalling() throws Exception {
Set<Integer> s1 = new HashSet<>();
Set<Integer> s2 = new TreeSet<>();
for (int i = 0; i < 10; i++) {
Integer integ = 1000 * i;
s1.add(integ);
s2.add(integ);
}
marshallAndAssertEquality(s1);
marshallAndAssertEquality(s2);
}
public void testSingletonListMarshalling() throws Exception {
GlobalTransaction gtx = gtf.newGlobalTransaction(new JGroupsAddress(UUID.randomUUID()), false);
List<GlobalTransaction> l = Collections.singletonList(gtx);
marshallAndAssertEquality(l);
}
public void testImmutableResponseMarshalling() throws Exception {
marshallAndAssertEquality(UnsuccessfulResponse.EMPTY);
marshallAndAssertEquality(UnsureResponse.INSTANCE);
}
public void testReplicableCommandsMarshalling() throws Exception {
ByteString cacheName = ByteString.fromString(TestingUtil.getDefaultCacheName(cm));
ClusteredGetCommand c2 = new ClusteredGetCommand("key", cacheName, 0, EnumUtil.EMPTY_BIT_SET);
marshallAndAssertEquality(c2);
// SizeCommand does not have an empty constructor, so doesn't look to be one that is marshallable.
GetKeyValueCommand c4 = new GetKeyValueCommand("key", 0, EnumUtil.EMPTY_BIT_SET);
marshallAndAssertEquality(c4);
PutKeyValueCommand c5 = new PutKeyValueCommand("k", "v", false, false,
new EmbeddedMetadata.Builder().build(), 0, EnumUtil.EMPTY_BIT_SET, CommandInvocationId.generateId(null));
marshallAndAssertEquality(c5);
RemoveCommand c6 = new RemoveCommand("key", null, false, 0, EnumUtil.EMPTY_BIT_SET, CommandInvocationId.generateId(null));
marshallAndAssertEquality(c6);
// EvictCommand does not have an empty constructor, so doesn't look to be one that is marshallable.
InvalidateCommand c7 = new InvalidateCommand(EnumUtil.EMPTY_BIT_SET, CommandInvocationId.generateId(null), "key1", "key2");
marshallAndAssertEquality(c7);
InvalidateCommand c71 = new InvalidateL1Command(EnumUtil.EMPTY_BIT_SET, CommandInvocationId.generateId(null), "key1", "key2");
marshallAndAssertEquality(c71);
ReplaceCommand c8 = new ReplaceCommand("key", "oldvalue", "newvalue", false, new EmbeddedMetadata.Builder().build(), 0,
EnumUtil.EMPTY_BIT_SET, CommandInvocationId.generateId(null));
marshallAndAssertEquality(c8);
ClearCommand c9 = new ClearCommand();
marshallAndAssertEquality(c9);
Map<Integer, GlobalTransaction> m1 = new HashMap<>();
for (int i = 0; i < 10; i++) {
GlobalTransaction gtx = gtf.newGlobalTransaction(new JGroupsAddress(UUID.randomUUID()), false);
m1.put(1000 * i, gtx);
}
PutMapCommand c10 = new PutMapCommand(m1, new EmbeddedMetadata.Builder().build(), EnumUtil.EMPTY_BIT_SET, CommandInvocationId.generateId(null));
marshallAndAssertEquality(c10);
Address local = new JGroupsAddress(UUID.randomUUID());
GlobalTransaction gtx = gtf.newGlobalTransaction(local, false);
PrepareCommand c11 = new PrepareCommand(cacheName, gtx, Arrays.asList(c5, c6, c8, c10), true);
marshallAndAssertEquality(c11);
CommitCommand c12 = new CommitCommand(cacheName, gtx);
marshallAndAssertEquality(c12);
RollbackCommand c13 = new RollbackCommand(cacheName, gtx);
marshallAndAssertEquality(c13);
}
public void testStateTransferControlCommand() throws Exception {
ByteString cacheName = ByteString.fromString(TestingUtil.getDefaultCacheName(cm));
ImmortalCacheEntry entry1 = (ImmortalCacheEntry) TestInternalCacheEntryFactory.create("key", "value", System.currentTimeMillis() - 1000, -1, System.currentTimeMillis(), -1);
Collection<InternalCacheEntry> state = new ArrayList<>();
state.add(entry1);
Address a1 = new JGroupsAddress(UUID.randomUUID());
Address a2 = new JGroupsAddress(UUID.randomUUID());
Address a3 = new JGroupsAddress(UUID.randomUUID());
List<Address> oldAddresses = new ArrayList<>();
oldAddresses.add(a1);
oldAddresses.add(a2);
List<Address> newAddresses = new ArrayList<>();
newAddresses.add(a1);
newAddresses.add(a2);
newAddresses.add(a3);
CacheRpcCommand c14 = new StateTransferStartCommand(cacheName, 99, IntSets.mutableEmptySet());
byte[] bytes = marshaller.objectToByteBuffer(c14);
marshaller.objectFromByteBuffer(bytes);
bytes = marshaller.objectToByteBuffer(c14);
marshaller.objectFromByteBuffer(bytes);
bytes = marshaller.objectToByteBuffer(c14);
marshaller.objectFromByteBuffer(bytes);
}
public void testInternalCacheEntryMarshalling() throws Exception {
ImmortalCacheEntry entry1 = (ImmortalCacheEntry) TestInternalCacheEntryFactory.create("key", "value", System.currentTimeMillis() - 1000, -1, System.currentTimeMillis(), -1);
marshallAndAssertEquality(entry1);
MortalCacheEntry entry2 = (MortalCacheEntry) TestInternalCacheEntryFactory.create("key", "value", System.currentTimeMillis() - 1000, 200000, System.currentTimeMillis(), -1);
marshallAndAssertEquality(entry2);
TransientCacheEntry entry3 = (TransientCacheEntry) TestInternalCacheEntryFactory.create("key", "value", System.currentTimeMillis() - 1000, -1, System.currentTimeMillis(), 4000000);
marshallAndAssertEquality(entry3);
TransientMortalCacheEntry entry4 = (TransientMortalCacheEntry) TestInternalCacheEntryFactory.create("key", "value", System.currentTimeMillis() - 1000, 200000, System.currentTimeMillis(), 4000000);
marshallAndAssertEquality(entry4);
}
public void testInternalCacheValueMarshalling() throws Exception {
ImmortalCacheValue value1 = (ImmortalCacheValue) TestInternalCacheEntryFactory.createValue("value", System.currentTimeMillis() - 1000, -1, System.currentTimeMillis(), -1);
byte[] bytes = marshaller.objectToByteBuffer(value1);
ImmortalCacheValue rvalue1 = (ImmortalCacheValue) marshaller.objectFromByteBuffer(bytes);
assert rvalue1.getValue().equals(value1.getValue()) : "Writen[" + rvalue1.getValue() + "] and read[" + value1.getValue() + "] objects should be the same";
MortalCacheValue value2 = (MortalCacheValue) TestInternalCacheEntryFactory.createValue("value", System.currentTimeMillis() - 1000, 200000, System.currentTimeMillis(), -1);
bytes = marshaller.objectToByteBuffer(value2);
MortalCacheValue rvalue2 = (MortalCacheValue) marshaller.objectFromByteBuffer(bytes);
assert rvalue2.getValue().equals(value2.getValue()) : "Writen[" + rvalue2.getValue() + "] and read[" + value2.getValue() + "] objects should be the same";
TransientCacheValue value3 = (TransientCacheValue) TestInternalCacheEntryFactory.createValue("value", System.currentTimeMillis() - 1000, -1, System.currentTimeMillis(), 4000000);
bytes = marshaller.objectToByteBuffer(value3);
TransientCacheValue rvalue3 = (TransientCacheValue) marshaller.objectFromByteBuffer(bytes);
assert rvalue3.getValue().equals(value3.getValue()) : "Writen[" + rvalue3.getValue() + "] and read[" + value3.getValue() + "] objects should be the same";
TransientMortalCacheValue value4 = (TransientMortalCacheValue) TestInternalCacheEntryFactory.createValue("value", System.currentTimeMillis() - 1000, 200000, System.currentTimeMillis(), 4000000);
bytes = marshaller.objectToByteBuffer(value4);
TransientMortalCacheValue rvalue4 = (TransientMortalCacheValue) marshaller.objectFromByteBuffer(bytes);
assert rvalue4.getValue().equals(value4.getValue()) : "Writen[" + rvalue4.getValue() + "] and read[" + value4.getValue() + "] objects should be the same";
}
public void testLongPutKeyValueCommand() throws Exception {
PutKeyValueCommand c = new PutKeyValueCommand(
"SESSION_173", "@TSXMHVROYNOFCJVEUJQGBCENNQDEWSCYSOHECJOHEICBEIGJVTIBB@TVNCWLTQCGTEJ@NBJLTMVGXCHXTSVE@BCRYGWPRVLXOJXBRJDVNBVXPRTRLBMHPOUYQKDEPDSADUAWPFSIOCINPSSFGABDUXRMTMMJMRTGBGBOAMGVMTKUDUAJGCAHCYW@LAXMDSFYOSXJXLUAJGQKPTHUKDOXRWKEFIVRTH@VIMQBGYPKWMS@HPOESTPIJE@OTOTWUWIOBLYKQQPTNGWVLRRCWHNIMWDQNOO@JHHEVYVQEODMWKFKKKSWURVDLXPTFQYIHLIM@GSBFWMDQGDQIJONNEVHGQTLDBRBML@BEWGHOQHHEBRFUQSLB@@CILXEAVQQBTXSITMBXHMHORHLTJF@MKMHQGHTSENWILTAKCCPVSQIPBVRAFSSEXIOVCPDXHUBIBUPBSCGPRECXEPMQHRHDOHIHVBPNDKOVLPCLKAJMNOTSF@SRXYVUEMQRCXVIETXVHOVNGYERBNM@RIMGHC@FNTUXSJSKALGHAFHGTFEANQUMBPUYFDSGLUYRRFDJHCW@JBWOBGMGTITAICRC@TPVCRKRMFPUSRRAHI@XOYKVGPHEBQD@@APEKSBCTBKREWAQGKHTJ@IHJD@YFSRDQPA@HKKELIJGFDYFEXFCOTCQIHKCQBLVDFHMGOWIDOWMVBDSJQOFGOIAPURRHVBGEJWYBUGGVHE@PU@NMQFMYTNYJDWPIADNVNCNYCCCPGODLAO@YYLVITEMNNKIFSDXKORJYWMFGKNYFPUQIC@AIDR@IWXCVALQBDOXRWIBXLKYTWDNHHSCUROAU@HVNENDAOP@RPTRIGLLLUNDQIDXJDDNF@P@PA@FEIBQKSKFQITTHDYGQRJMWPRLQC@NJVNVSKGOGYXPYSQHKPALKLFWNAOSQFTLEPVOII@RPDNRCVRDUMMFIVSWGIASUBMTGQSDGB@TBBYECFBRBGILJFCJ@JIQIQRVJXWIPGNVXKYATSPJTIPGCMCNPOKNEHBNUIAEQFQTYVLGAR@RVWVA@RMPBX@LRLJUEBUWO@PKXNIP@FKIQSVWKNO@FOJWDSIOLXHXJFBQPPVKKP@YKXPOOMBTLXMEHPRLLSFSVGMPXXNBCYVVSPNGMFBJUDCVOVGXPKVNTOFKVJUJOSDHSCOQRXOKBVP@WCUUFGMJAUQ@GRAGXICFCFICBSNASUBPAFRIPUK@OXOCCNOGTTSFVQKBQNB@DWGVEFSGTAXAPLBJ@SYHUNXWXPMR@KPFAJCIXPDURELFYPMUSLTJSQNDHHKJTIWCGNEKJF@CUWYTWLPNHYPHXNOGLSICKEFDULIXXSIGFMCQGURSRTUJDKRXBUUXIDFECMPXQX@CVYLDABEMFKUGBTBNMNBPCKCHWRJKSOGJFXMFYLLPUVUHBCNULEFAXPVKVKQKYCEFRUYPBRBDBDOVYLIQMQBLTUK@PRDCYBOKJGVUADFJFAFFXKJTNAJTHISWOSMVAYLIOGIORQQWFAKNU@KHPM@BYKTFSLSRHBATQTKUWSFAQS@Y@QIKCUWQYTODBRCYYYIAFMDVRURKVYJXHNGVLSQQFCXKLNUPCTEJSWIJUBFELSBUHANELHSIWLVQSSAIJRUEDOHHX@CKEBPOJRLRHEPLENSCDGEWXRTVUCSPFSAJUXDJOIUWFGPKHBVRVDMUUCPUDKRKVAXPSOBOPKPRRLFCKTLH@VGWKERASJYU@JAVWNBJGQOVF@QPSGJVEPAV@NAD@@FQRYPQIOAURILWXCKINPMBNUHPUID@YDQBHWAVDPPWRFKKGWJQTI@@OPSQ@ROUGHFNHCJBDFCHRLRTEMTUBWVCNOPYXKSSQDCXTOLOIIOCXBTPAUYDICFIXPJRB@CHFNXUCXANXYKXAISDSSLJGQOLBYXWHG@@KPARPCKOXAYVPDGRW@LDCRQBNMJREHWDYMXHEXAJQKHBIRAVHJQIVGOIXNINYQMJBXKM@DXESMBHLKHVSFDLVPOSOVMLHPSHQYY@DNMCGGGAJMHPVDLBGJP@EVDGLYBMD@NWHEYTBPIBPUPYOPOJVV@IVJXJMHIWWSIRKUWSR@U@@TDVMG@GRXVLCNEIISEVIVPOMJHKOWMRMITYDUQASWJIKVNYUFQVDT@BHTOMFXVFRKAARLNOGX@ADWCKHOVEMIGBWXINCUXEMVHSJJQDU@INTHDJQPSAQNAYONDBBFYGBTNGUSJHRKLCPHQMNLDHUQJPLLCDVTYLXTHJCBUXCRDY@YI@IQDCLJBBJC@NXGANXFIWPPNFVTDJWQ@@BIYJONOFP@RHTQEYPVHPPUS@UUENSNNF@WVGTSAVKDSQNMHP@VJORGTVWXVBPWKQNRWLSQFSBMXQKWRYMXPAYREXYGONKEWJMBCSLB@KSHXMIWMSBDGQWPDMUGVNMEWKMJKQECIRRVXBPBLGAFTUFHYSHLF@TGYETMDXRFAXVEUBSTGLSMWJMXJWMDPPDAFGNBMTQEMBDLRASMUMU@QTCDCPEGODHESDQVEIQYBJJPFXDLWPUNFAREYCY@YDDSTMKWCANNPXF@@WLMEXRPUNTWNOX@YKFNNTGMXIBBDA@TYLPJFNFHPQKMSNCLBME@FBPOIYNSDFBLHITKIFEFNXXOJAAFMRTGPALOANXF@YPY@RYTVOW@AKNM@C@LJKGBJMUYGGTXRHQCPOLNOGPPS@YSKAJSTQHLRBXUACXJYBLJSEHDNMLLUBSOIHQUI@VUNF@XAVRXUCYNCBDDGUDNVRYP@TPFPKGVNPTEDOTTUUFKCHQ@WWASQXLCBHNRBVSD@NVYT@GJQYSQGYPJO@WSEYDVKCBWANAFUWLDXOQYCYP@BSJFCBTXGKUNWLWUCYL@TNOWGDFHQTWQVYLQBBRQVMGNDBVXEFXTMMVYSHNVTTQAJCHKULOAJUSGJRPHQFCROWE@OMFUVRKGCWED@IAQGRLADOJGQKLCL@FCKTSITGMJRCCMPLOS@ONPQWFUROXYAUJQXIYVDCYBPYHPYCXNCRKRKLATLWWXLBLNOPUJFUJEDOIRKS@MMYPXIJNXPFOQJCHSCBEBGDUQYXQAWEEJDOSINXYLDXUJCQECU@WQSACTDFLGELHPGDFVDXFSSFOSYDLHQFVJESNAVAHKTUPBTPLSFSHYKLEXJXGWESVQQUTUPU@QXRTIDQ@IXBBOYINNHPEMTPRVRNJPQJFACFXUBKXOFHQSPOTLCQ@PLWGEFNKYCYFMKWPFUP@GLHKNMASGIENCACUISTG@YNQCNSOSBKOIXORKSHEOXHSMJJRUICJTCK@PWFRBPLXU@MUEMPFGDLUJEKD@ROUFBLKATXUCHEAQHEYDLCFDIRJSAXTV@CYMPQNMLTMFAHPRBLNSCVFBJMKQLAHWYIOLRMTOY@@RNKTUXHFYUMHGKCCGNEOIOQCISJEHCEVTTWM@TLFRIFDREHFBTTDEJRUNTWAEETGSVDOR@@UQNKFERMBVFJBOAYHPOKMSMRIERDA@JXYSJ@ORER@MBAVWCVGFNA@FRRPQSIIOIUGAJKVQXGINUUKPJPLQRMHPUBETEEIMIBPM@PETR@XD@DOHGRIBVXKLXQWHUFMTWEDYWFWRLPGDS@TANUXGIDTRVXKVCVEXYRKXQCTI@WNSFRAHJJGG@NIPPAAOJXQRTCLBYKDA@FFGHNUIGBFKOQMEDUEFELFLNKPCHA@OXJJRYNPDFSXIFSJYTDMSSBHDPUSQQDAVD@JAAWJDSVTERAJBFEPVRWKMYAPISPWLDPSRE@UMRQLXERTWRDLQVMVCOM@NYPXFLWMWKALMQVNJ@HCTMMIOLRWBJHCYFLMM@IWXPSHRRUNICSSWHOQHUVJE@HKJAADLBTPVLDAKCHRSURJCAXYTMYKHQMWDAWWASUW@HWGBVPTRHJGDWOGHPCNWSXTNKWONQGEKDDWGCKWVSAD@YLCCENMCHALHVDYQW@NQGNCY@M@GGV@RIR@OUS@PQIJMCFEIMGPYBXYR@NSIAUEXT@MOCNWRMLYHUUAFJCCLLRNFGKLPPIIH@BYRME@UJAKIFHOV@ILP@BGXRNJBIBARSOIMTDSHMGPIGRJBGHYRYXPFUHVOOMCQFNLM@CNCBTGO@UKXBOICNVCRGHADYQVAMNSFRONJ@WITET@BSHMQLWYMVGMQJVSJOXOUJDSXYVVBQJSVGREQLIQKWC@BMDNONHXFYPQENSJINQYKHVCTUTG@QQYJKJURDCKJTUQAM@DWNXWRNILYVAAJ@IADBIXKEIHVXLXUVMGQPAQTWJCDMVDVYUDTXQTCYXDPHKBAGMTAMKEM@QNOQJBREXNWFCXNXRPGOGEIR@KQJIGXAWXLTNCX@ID@XNRNYGRF@QPNWEX@XH@XKSXLQTLQPFSHAHXJLHUTNQWFFAJYHBWIFVJELDPSPLRRDPPNXSBYBEREEELIWNVYXOXYJQAIGHALUAWNUSSNMBHBFLRMMTKEKNSINECUGWTDNMROXI@BJJXKSPIIIXOAJBFVSITQDXTODBGKEPJMWK@JOL@SWTCGSHCOPHECTPJFUXIHUOSVMUTNNSLLJDEOMAGIXEAAVILRMOJXVHHPNPUYYODMXYAYGHI@BUB@NLP@KNPCYFRWAFES@WISBACDSPELEVTJEBNRVENSXXEVDVC@RIDIDSBPQIQNNSRPS@HCJ@XPIOFDXHUBCNFQKHMUYLXW@LMFMALHLESSXCOULRWDTJIVKKTLGFE@HKGVKUGMVHWACQOTSVNWBNUUGTMSQEJ@DXJQQYPOWVRQNQKXSLOEAA@@FRDCGCCQWQ@IY@EATGQGQIETPIJHOIQRYWLTGUENQYDNQSBI@IAUDEWDKICHNUGNAIXNICMBK@CJGSASMTFKWOBSI@KULNENWXV@VNFOANM@OJHFVV@IYRMDB@LHSGXIJMMFCGJKTKDXSMY@FHDNY@VSDUORGWVFMVKJXOCCDLSLMHCSXFBTW@RQTFNRDJUIKRD@PWPY",
false, false, new EmbeddedMetadata.Builder().build(), 0, EnumUtil.EMPTY_BIT_SET,
CommandInvocationId.generateId(null));
marshallAndAssertEquality(c);
}
public void testExceptionResponse() throws Exception {
ExceptionResponse er = new ExceptionResponse(new TimeoutException());
byte[] bytes = marshaller.objectToByteBuffer(er);
ExceptionResponse rer = (ExceptionResponse) marshaller.objectFromByteBuffer(bytes);
assert rer.getException().getClass().equals(er.getException().getClass()) : "Writen[" + er.getException().getClass() + "] and read[" + rer.getException().getClass() + "] objects should be the same";
}
@Test(expectedExceptions = MarshallingException.class)
public void testNestedNonMarshallable() throws Exception {
PutKeyValueCommand cmd = new PutKeyValueCommand("k", new Object(), false, false,
new EmbeddedMetadata.Builder().build(), 0, EnumUtil.EMPTY_BIT_SET, CommandInvocationId.generateId(null));
marshaller.objectToByteBuffer(cmd);
}
@Test(expectedExceptions = MarshallingException.class)
public void testNonMarshallable() throws Exception {
marshaller.objectToByteBuffer(new Object());
}
public void testConcurrentHashMap() throws Exception {
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
map.put(1, "v1");
map.put(2, "v2");
map.put(3, "v3");
marshallAndAssertEquality(map);
}
public static class PojoWhichFailsOnUnmarshalling extends Pojo {
private static final long serialVersionUID = -5109779096242560884L;
public PojoWhichFailsOnUnmarshalling() {
super(0, false);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
throw new IOException("Injected failue!");
}
}
@Test(expectedExceptions = MarshallingException.class)
public void testErrorUnmarshalling() throws Exception {
BrokenMarshallingPojo bmp = new BrokenMarshallingPojo(false);
byte[] bytes = marshaller.objectToByteBuffer(bmp);
marshaller.objectFromByteBuffer(bytes);
}
public void testErrorUnmarshallInputStreamAvailable() throws Exception {
byte[] bytes = marshaller.objectToByteBuffer("23");
Object o = marshaller.objectFromInputStream(new ByteArrayInputStream(bytes){
@Override
public int available() {
return 0;
}
});
assertEquals("23", o);
}
public void testFlagMarshalling() throws Exception {
marshallAndAssertEquality(Arrays.asList(Flag.values()));
}
public void testSingleFlagMarshalling() throws Exception {
marshallAndAssertEquality(Flag.FORCE_SYNCHRONOUS);
}
public void testEnumSetSingleElementMarshalling() throws Exception {
marshallAndAssertEquality(EnumSet.of(Flag.FORCE_SYNCHRONOUS));
}
public void testEnumSetMultiElementMarshalling() throws Exception {
marshallAndAssertEquality(EnumSet.of(Flag.FORCE_SYNCHRONOUS, Flag.FORCE_ASYNCHRONOUS));
}
public void testIsMarshallableSerializableWithAnnotation() throws Exception {
PojoWithSerializeWith pojo = new PojoWithSerializeWith(17, "k1");
assertTrue(marshaller.isMarshallable(pojo));
}
public void testSerializableWithAnnotation() throws Exception {
marshallAndAssertEquality(new PojoWithSerializeWith(20, "k2"));
}
public void testListArray() throws Exception {
List<Integer>[] numbers = new List[]{Arrays.asList(1), Arrays.asList(2)};
marshallAndAssertArrayEquality(numbers);
}
public void testByteArray() throws Exception {
byte[] bytes = new byte[]{1, 2, 3};
marshallAndAssertByteArrayEquality(bytes);
}
public void testExternalAndInternalWithOffset() throws Exception {
PojoWithExternalAndInternal obj = new PojoWithExternalAndInternal(new Human().age(23), "value");
byte[] bytes = marshaller.objectToByteBuffer(obj);
bytes = prependBytes(new byte[]{1, 2, 3}, bytes);
Object readObj = marshaller.objectFromByteBuffer(bytes, 3, bytes.length);
assertEquals(obj, readObj);
}
public void testArrays() throws Exception {
marshallAndAssertArrayEquality(new Object[] { });
marshallAndAssertArrayEquality(new String[] { null, "foo" });
marshallAndAssertArrayEquality(new String[] { "foo", "bar" });
marshallAndAssertArrayEquality(new Object[] { 1.2, 3.4 });
marshallAndAssertArrayEquality(new Pojo[] { });
marshallAndAssertArrayEquality(new Pojo[] { null });
marshallAndAssertArrayEquality(new Pojo[] { null, null });
marshallAndAssertArrayEquality(new Pojo[] { new Pojo(1, false), new Pojo(2, true) });
marshallAndAssertArrayEquality(new Pojo[] { new Pojo(3, false), null });
marshallAndAssertArrayEquality(new Pojo[] { new Pojo(4, false), new PojoExtended(5, true) });
marshallAndAssertArrayEquality(new I[] { new Pojo(6, false), new Pojo(7, true) });
marshallAndAssertArrayEquality(new I[] { new Pojo(8, false), new PojoExtended(9, true) });
marshallAndAssertArrayEquality(new I[] { new Pojo(10, false), new PojoWithExternalizer(11, false) });
marshallAndAssertArrayEquality(new PojoWithExternalizer[] {
new PojoWithExternalizer(12, true), new PojoWithExternalizer(13, false) });
marshallAndAssertArrayEquality(new I[] { new PojoWithExternalizer(14, false), new PojoWithExternalizer(15, true)});
marshallAndAssertArrayEquality(new PojoWithMultiExternalizer[] {
new PojoWithMultiExternalizer(16, true), new PojoWithMultiExternalizer(17, false) });
marshallAndAssertArrayEquality(new I[] { new PojoWithMultiExternalizer(18, false), new PojoWithExternalizer(19, true)});
marshallAndAssertArrayEquality(new I[] { new PojoWithMultiExternalizer(20, false), new PojoWithMultiExternalizer(21, true)});
marshallAndAssertArrayEquality(new Object[] { new PojoWithMultiExternalizer(22, false), new PojoWithMultiExternalizer(23, true)});
marshallAndAssertArrayEquality(new Object[] { new PojoWithExternalizer(24, false), new PojoWithExternalizer(25, true)});
marshallAndAssertArrayEquality(new Object[] { new PojoAnnotated(26, false), "foo"});
marshallAndAssertArrayEquality(new Object[] { new PojoAnnotated(27, false), new PojoAnnotated(28, true)});
marshallAndAssertArrayEquality(new PojoAnnotated[] { new PojoAnnotated(27, false), new PojoAnnotated(28, true)});
marshallAndAssertArrayEquality(new PojoAnnotated[] { null, null });
}
public void testLongArrays() throws Exception {
for (int length : new int[] { 0xFF, 0x100, 0x101, 0x102, 0x100FF, 0x10100, 0x10101, 0x10102 }) {
String[] array = new String[length];
// test null
marshallAndAssertArrayEquality(array);
// test filled
Arrays.fill(array, "a");
marshallAndAssertArrayEquality(array);
}
}
byte[] prependBytes(byte[] bytes, byte[] src) {
byte[] res = new byte[bytes.length + src.length];
System.arraycopy(bytes, 0, res, 0, bytes.length);
System.arraycopy(src, 0, res, bytes.length, src.length);
return res;
}
protected void marshallAndAssertEquality(Object writeObj) throws Exception {
byte[] bytes = marshaller.objectToByteBuffer(writeObj);
log.debugf("Payload size for object=%s : %s", writeObj, bytes.length);
Object readObj = marshaller.objectFromByteBuffer(bytes);
assert readObj.equals(writeObj) : "Writen[" + writeObj + "] and read[" + readObj + "] objects should be the same";
}
protected void marshallAndAssertEquality(ReplicableCommand writeObj) throws Exception {
byte[] bytes = marshaller.objectToByteBuffer(writeObj);
log.debugf("Payload size for object=%s : %s", writeObj, bytes.length);
ReplicableCommand readObj = (ReplicableCommand) marshaller.objectFromByteBuffer(bytes);
assert readObj.getCommandId() == writeObj.getCommandId() : "Writen[" + writeObj.getCommandId() + "] and read[" + readObj.getCommandId() + "] objects should be the same";
assert readObj.equals(writeObj) : "Writen[" + writeObj + "] and read[" + readObj + "] objects should be the same";
}
protected void marshallAndAssertArrayEquality(Object[] writeObj) throws Exception {
byte[] bytes = marshaller.objectToByteBuffer(writeObj);
log.debugf("Payload size for %s[]=%s : %s", writeObj.getClass().getComponentType().getName(), Arrays.toString(writeObj), bytes.length);
Object[] readObj = (Object[]) marshaller.objectFromByteBuffer(bytes);
assertArrayEquals("Writen[" + Arrays.toString(writeObj) + "] and read["
+ Arrays.toString(readObj) + "] objects should be the same",
writeObj, readObj);
}
protected void marshallAndAssertByteArrayEquality(byte[] writeObj) throws Exception {
byte[] bytes = marshaller.objectToByteBuffer(writeObj);
log.debugf("Payload size for byte[]=%s : %s", Util.toHexString(writeObj), bytes.length);
byte[] readObj = (byte[]) marshaller.objectFromByteBuffer(bytes);
assertArrayEquals("Writen[" + Util.toHexString(writeObj)+ "] and read["
+ Util.toHexString(readObj)+ "] objects should be the same",
writeObj, readObj);
}
public interface I {
}
public static class Pojo implements I, Externalizable {
private static final long serialVersionUID = 9032309454840083326L;
@ProtoField(number = 1, defaultValue = "0")
int i;
@ProtoField(number = 2, defaultValue = "false")
boolean b;
public Pojo() {}
public Pojo(int i, boolean b) {
this.i = i;
this.b = b;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pojo pojo = (Pojo) o;
if (b != pojo.b) {
return false;
}
if (i != pojo.i) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result;
result = i;
result = 31 * result + (b ? 1 : 0);
return result;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(i);
out.writeBoolean(b);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
i = in.readInt();
b = in.readBoolean();
}
}
@SerializeWith(PojoAnnotated.Externalizer.class)
public static class PojoAnnotated extends Pojo {
public PojoAnnotated(int i, boolean b) {
super(i, b);
}
public static class Externalizer implements org.infinispan.commons.marshall.Externalizer<PojoAnnotated> {
@Override
public void writeObject(ObjectOutput output, PojoAnnotated object) throws IOException {
output.writeInt(object.i);
output.writeBoolean(object.b);
}
@Override
public PojoAnnotated readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new PojoAnnotated(input.readInt(), input.readBoolean());
}
}
}
public static class PojoExtended extends Pojo {
public PojoExtended() {}
public PojoExtended(int i, boolean b) {
super(i, b);
}
}
public static class PojoWithExternalizer extends Pojo {
public PojoWithExternalizer(int i, boolean b) {
super(i, b);
}
public static class Externalizer implements AdvancedExternalizer<PojoWithExternalizer> {
@Override
public Set<Class<? extends PojoWithExternalizer>> getTypeClasses() {
return Util.asSet(PojoWithExternalizer.class);
}
@Override
public Integer getId() {
return 1234;
}
@Override
public void writeObject(ObjectOutput output, PojoWithExternalizer object) throws IOException {
output.writeInt(object.i);
output.writeBoolean(object.b);
}
@Override
public PojoWithExternalizer readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new PojoWithExternalizer(input.readInt(), input.readBoolean());
}
}
}
public static class PojoWithMultiExternalizer extends Pojo {
public PojoWithMultiExternalizer(int i, boolean b) {
super(i, b);
}
public static class Externalizer implements AdvancedExternalizer<Object> {
@Override
public Set<Class<?>> getTypeClasses() {
return Util.asSet(PojoWithMultiExternalizer.class, Thread.class);
}
@Override
public Integer getId() {
return 4321;
}
@Override
public void writeObject(ObjectOutput output, Object o) throws IOException {
PojoWithMultiExternalizer pojo = (PojoWithMultiExternalizer) o;
output.writeInt(pojo.i);
output.writeBoolean(pojo.b);
}
@Override
public Object readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new PojoWithMultiExternalizer(input.readInt(), input.readBoolean());
}
}
}
public static class Human implements Serializable {
@ProtoField(number = 1, defaultValue = "0")
int age;
public Human() {}
public Human age(int age) {
this.age = age;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Human human = (Human) o;
return age == human.age;
}
@Override
public int hashCode() {
return age;
}
}
public static class HumanComparator implements Comparator<Human>, Serializable {
@Override
public int compare(Human o1, Human o2) {
if (o1.age < o2.age) return -1;
if (o1.age == o2.age) return 0;
return 1;
}
}
public static class PojoWithExternalAndInternal {
@ProtoField(1)
final Human human;
@ProtoField(2)
final String value;
@ProtoFactory
PojoWithExternalAndInternal(Human human, String value) {
this.human = human;
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PojoWithExternalAndInternal that = (PojoWithExternalAndInternal) o;
if (!human.equals(that.human)) return false;
return value.equals(that.value);
}
@Override
public int hashCode() {
int result = human.hashCode();
result = 31 * result + value.hashCode();
return result;
}
public static class Externalizer implements AdvancedExternalizer<PojoWithExternalAndInternal> {
@Override
public void writeObject(ObjectOutput out, PojoWithExternalAndInternal obj) throws IOException {
out.writeObject(obj.human);
out.writeObject(obj.value);
}
@Override
public PojoWithExternalAndInternal readObject(ObjectInput input) throws IOException, ClassNotFoundException {
Human human = (Human) input.readObject();
String value = (String) input.readObject();
return new PojoWithExternalAndInternal(human, value);
}
@Override
public Set<Class<? extends PojoWithExternalAndInternal>> getTypeClasses() {
return Collections.singleton(PojoWithExternalAndInternal.class);
}
@Override
public Integer getId() {
return 999;
}
}
}
@AutoProtoSchemaBuilder(
includeClasses = {
Key.class,
VersionAwareMarshallerTest.Human.class,
VersionAwareMarshallerTest.Pojo.class,
VersionAwareMarshallerTest.PojoExtended.class,
VersionAwareMarshallerTest.PojoWithExternalAndInternal.class
},
schemaFileName = "test.core.VersionAwareMarshallerTest.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.test.core.VersionAwareMarshallerTest",
service = false
)
interface VersionAwareMarshallerSCI extends SerializationContextInitializer {
}
}
| 37,856
| 47.659383
| 5,030
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/ProtostreamUserMarshallerTest.java
|
package org.infinispan.marshall;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.infinispan.commons.marshall.ImmutableProtoStreamMarshaller;
import org.infinispan.commons.marshall.MarshallingException;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.marshall.core.impl.DelegatingUserMarshaller;
import org.infinispan.marshall.persistence.PersistenceMarshaller;
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.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
/**
* A test to ensure that a {@link org.infinispan.commons.marshall.ProtoStreamMarshaller} instance is loaded as the
* user marshaller, when a {@link org.infinispan.protostream.SerializationContextInitializer} is configured.
*
* @author Ryan Emerson
* @since 10.0
*/
@Test(groups = "functional", testName = "marshall.ProtostreamUserMarshallerTest")
public class ProtostreamUserMarshallerTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
GlobalConfigurationBuilder globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder();
globalBuilder.serialization().addContextInitializers(new UserSCIImpl(), new AnotherUserSCIImpl());
createCluster(globalBuilder, new ConfigurationBuilder(), 2);
}
@Test(expectedExceptions = MarshallingException.class,
expectedExceptionsMessageRegExp = "No marshaller registered for object of Java type org\\.infinispan\\.marshall\\.ProtostreamUserMarshallerTest\\$NonMarshallablePojo : .*")
public void testMarshallingException() throws Exception {
PersistenceMarshaller pm = TestingUtil.extractPersistenceMarshaller(manager(0));
pm.objectToBuffer(new NonMarshallablePojo());
}
public void testPrimitivesAreMarshallable() throws Exception {
List<Object> objectsToTest = new ArrayList<>();
objectsToTest.add("String");
objectsToTest.add(Integer.MAX_VALUE);
objectsToTest.add(Long.MAX_VALUE);
objectsToTest.add(Double.MAX_VALUE);
objectsToTest.add(Float.MAX_VALUE);
objectsToTest.add(true);
objectsToTest.add(new byte[0]);
objectsToTest.add(Byte.MAX_VALUE);
objectsToTest.add(Short.MAX_VALUE);
objectsToTest.add('c');
objectsToTest.add(new Date());
objectsToTest.add(Instant.now());
PersistenceMarshaller pm = TestingUtil.extractPersistenceMarshaller(manager(0));
for (Object o : objectsToTest) {
assertTrue(pm.isMarshallable(o));
assertNotNull(pm.objectToBuffer(o));
}
}
public void testProtostreamMarshallerLoaded() {
PersistenceMarshaller pm = TestingUtil.extractPersistenceMarshaller(manager(0));
testIsMarshallableAndPut(pm, new ExampleUserPojo("A Pojo!"), new AnotherExampleUserPojo("And another one!"));
DelegatingUserMarshaller userMarshaller = (DelegatingUserMarshaller) pm.getUserMarshaller();
assertTrue(userMarshaller.getDelegate() instanceof ImmutableProtoStreamMarshaller);
}
private void testIsMarshallableAndPut(PersistenceMarshaller pm, Object... pojos) {
for (Object o : pojos) {
assertTrue(pm.isMarshallable(o));
String key = o.getClass().getSimpleName();
cache(0).put(key, o);
assertNotNull(cache(0).get(key));
}
}
static class ExampleUserPojo {
@ProtoField(1)
final String someString;
@ProtoFactory
ExampleUserPojo(String someString) {
this.someString = someString;
}
}
static class AnotherExampleUserPojo {
@ProtoField(1)
final String anotherString;
@ProtoFactory
AnotherExampleUserPojo(String anotherString) {
this.anotherString = anotherString;
}
}
static class NonMarshallablePojo {
int x;
}
@AutoProtoSchemaBuilder(
includeClasses = ExampleUserPojo.class,
schemaFileName = "test.core.protostream-user-marshall.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.test.marshall",
service = false
)
interface UserSCI extends SerializationContextInitializer {
}
@AutoProtoSchemaBuilder(
includeClasses = AnotherExampleUserPojo.class,
schemaFileName = "test.core.protostream-another-user-marshall.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.test.marshall",
service = false
)
interface AnotherUserSCI extends SerializationContextInitializer {
}
}
| 5,041
| 36.909774
| 181
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/TestObjectStreamMarshaller.java
|
package org.infinispan.marshall;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.marshall.BufferSizePredictor;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.marshall.StreamingMarshaller;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.persistence.PersistenceMarshaller;
import org.infinispan.marshall.persistence.impl.PersistenceMarshallerImpl;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* A dummy marshaller impl. Under the hood instantiates an {@link StreamingMarshaller}.
* N.B.: When an instance of this class is no longer needed please invoke TestObjectStreamMarshaller.stop on it.
*
* @author Manik Surtani
*/
@Scope(Scopes.GLOBAL)
public class TestObjectStreamMarshaller implements PersistenceMarshaller {
private static Log log = LogFactory.getLog(TestObjectStreamMarshaller.class);
private final PersistenceMarshallerImpl marshaller;
public final EmbeddedCacheManager cacheManager;
public TestObjectStreamMarshaller() {
this(null);
}
public TestObjectStreamMarshaller(SerializationContextInitializer sci) {
cacheManager = TestCacheManagerFactory.createCacheManager(sci, new ConfigurationBuilder());
marshaller = (PersistenceMarshallerImpl) cacheManager.getCache().getAdvancedCache().getComponentRegistry().getPersistenceMarshaller();
}
public ClassAllowList getAllowList() {
return cacheManager.getClassAllowList();
}
@Override
public byte[] objectToByteBuffer(Object obj, int estimatedSize) throws IOException, InterruptedException {
return marshaller.objectToByteBuffer(obj, estimatedSize);
}
@Override
public byte[] objectToByteBuffer(Object obj) throws IOException, InterruptedException {
return marshaller.objectToByteBuffer(obj);
}
@Override
public Object objectFromByteBuffer(byte[] buf) throws IOException, ClassNotFoundException {
return marshaller.objectFromByteBuffer(buf);
}
@Override
public ByteBuffer objectToBuffer(Object o) throws IOException, InterruptedException {
return marshaller.objectToBuffer(o);
}
@Override
public BufferSizePredictor getBufferSizePredictor(Object o) {
return marshaller.getBufferSizePredictor(o);
}
@Override
public Object objectFromByteBuffer(byte[] buf, int offset, int length) throws IOException, ClassNotFoundException {
return marshaller.objectFromByteBuffer(buf, offset, length);
}
@Override
public void writeObject(Object o, OutputStream out) throws IOException {
marshaller.writeObject(o, out);
}
@Override
public Object readObject(InputStream in) throws ClassNotFoundException, IOException {
return marshaller.readObject(in);
}
@Override
public boolean isMarshallable(Object o) {
return marshaller.isMarshallable(o);
}
@Override
@Stop
public void stop() {
log.trace("TestObjectStreamMarshaller.stop()");
TestingUtil.killCacheManagers(cacheManager);
}
@Override
public void start() {
}
@Override
public MediaType mediaType() {
return marshaller.mediaType();
}
@Override
public void register(SerializationContextInitializer initializer) {
marshaller.register(initializer);
}
@Override
public Marshaller getUserMarshaller() {
return marshaller.getUserMarshaller();
}
@Override
public int sizeEstimate(Object o) {
return marshaller.sizeEstimate(o);
}
}
| 4,133
| 30.8
| 140
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/MarshalledValuesFineGrainedTest.java
|
package org.infinispan.marshall;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import org.infinispan.commons.marshall.WrappedBytes;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.container.DataContainer;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.encoding.DataConversion;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.data.Key;
import org.infinispan.test.data.Person;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
/**
* Tests just enabling marshalled values on keys and not values, and vice versa.
*
* @author Manik Surtani
*/
@Test(groups = "functional", testName = "marshall.MarshalledValuesFineGrainedTest")
public class MarshalledValuesFineGrainedTest extends AbstractInfinispanTest {
EmbeddedCacheManager ecm;
final Key key = new Key("key");
final Person value = new Person("value");
@AfterMethod
public void cleanup() {
TestingUtil.killCacheManagers(ecm);
ecm = null;
}
public void testStoreAsBinaryOnBoth() {
ConfigurationBuilder c = new ConfigurationBuilder();
c.memory().storageType(StorageType.BINARY).build();
ecm = TestCacheManagerFactory.createCacheManager(TestDataSCI.INSTANCE, c);
ecm.getCache().put(key, value);
DataConversion keyDataConversion = ecm.getCache().getAdvancedCache().getKeyDataConversion();
DataConversion valueDataConversion = ecm.getCache().getAdvancedCache().getValueDataConversion();
DataContainer<?, ?> dc = ecm.getCache().getAdvancedCache().getDataContainer();
InternalCacheEntry entry = dc.iterator().next();
Object key = entry.getKey();
Object value = entry.getValue();
assertTrue(key instanceof WrappedBytes);
assertEquals(keyDataConversion.fromStorage(key), this.key);
assertTrue(value instanceof WrappedBytes);
assertEquals(valueDataConversion.fromStorage(value), this.value);
}
}
| 2,295
| 37.266667
| 102
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/AdvancedExternalizerTest.java
|
package org.infinispan.marshall;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Set;
import org.infinispan.Cache;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.CacheContainer;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* Tests configuration of user defined {@link AdvancedExternalizer} implementations
*
* @author Galder Zamarreño
* @since 5.0
*/
@Test(groups = "functional", testName = "marshall.AdvancedExternalizerTest")
public class AdvancedExternalizerTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
GlobalConfigurationBuilder globalCfg1 = createForeignExternalizerGlobalConfig();
GlobalConfigurationBuilder globalCfg2 = createForeignExternalizerGlobalConfig();
ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false);
CacheContainer cm1 = TestCacheManagerFactory.createClusteredCacheManager(globalCfg1, cfg);
CacheContainer cm2 = TestCacheManagerFactory.createClusteredCacheManager(globalCfg2, cfg);
registerCacheManager(cm1, cm2);
defineConfigurationOnAllManagers(getCacheName(), cfg);
waitForClusterToForm(getCacheName());
}
protected String getCacheName() {
return "ForeignExternalizers";
}
protected GlobalConfigurationBuilder createForeignExternalizerGlobalConfig() {
GlobalConfigurationBuilder builder = new GlobalConfigurationBuilder().clusteredDefault();
builder.serialization()
.addAdvancedExternalizer(1234, new IdViaConfigObj.Externalizer())
.addAdvancedExternalizer(new IdViaAnnotationObj.Externalizer())
.addAdvancedExternalizer(3456, new IdViaBothObj.Externalizer());
return builder;
}
public void testReplicatePojosWithUserDefinedExternalizers(Method m) {
Cache cache1 = manager(0).getCache(getCacheName());
Cache cache2 = manager(1).getCache(getCacheName());
IdViaConfigObj configObj = new IdViaConfigObj().setName("Galder");
String key = "k-" + m.getName() + "-viaConfig";
cache1.put(key, configObj);
assert configObj.name.equals(((IdViaConfigObj)cache2.get(key)).name);
IdViaAnnotationObj annotationObj = new IdViaAnnotationObj().setDate(new Date(System.currentTimeMillis()));
key = "k-" + m.getName() + "-viaAnnotation";
cache1.put(key, annotationObj);
assert annotationObj.date.equals(((IdViaAnnotationObj)cache2.get(key)).date);
IdViaBothObj bothObj = new IdViaBothObj().setAge(30);
key = "k-" + m.getName() + "-viaBoth";
cache1.put(key, bothObj);
assert bothObj.age == ((IdViaBothObj)cache2.get(key)).age;
}
public static class IdViaConfigObj {
String name;
public IdViaConfigObj setName(String name) {
this.name = name;
return this;
}
public static class Externalizer extends AbstractExternalizer<IdViaConfigObj> {
@Override
public void writeObject(ObjectOutput output, IdViaConfigObj object) throws IOException {
output.writeUTF(object.name);
}
@Override
public IdViaConfigObj readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new IdViaConfigObj().setName(input.readUTF());
}
@Override
public Set<Class<? extends IdViaConfigObj>> getTypeClasses() {
return Util.<Class<? extends IdViaConfigObj>>asSet(IdViaConfigObj.class);
}
}
}
public static class IdViaAnnotationObj {
Date date;
public IdViaAnnotationObj setDate(Date date) {
this.date = date;
return this;
}
public static class Externalizer extends AbstractExternalizer<IdViaAnnotationObj> {
@Override
public void writeObject(ObjectOutput output, IdViaAnnotationObj object) throws IOException {
output.writeObject(object.date);
}
@Override
public IdViaAnnotationObj readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new IdViaAnnotationObj().setDate((Date) input.readObject());
}
@Override
public Integer getId() {
return 5678;
}
@Override
public Set<Class<? extends IdViaAnnotationObj>> getTypeClasses() {
return Util.<Class<? extends IdViaAnnotationObj>>asSet(IdViaAnnotationObj.class);
}
}
}
public static class IdViaBothObj {
int age;
public IdViaBothObj setAge(int age) {
this.age = age;
return this;
}
public static class Externalizer extends AbstractExternalizer<IdViaBothObj> {
@Override
public void writeObject(ObjectOutput output, IdViaBothObj object) throws IOException {
output.writeInt(object.age);
}
@Override
public IdViaBothObj readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new IdViaBothObj().setAge(input.readInt());
}
@Override
public Integer getId() {
return 9012;
}
@Override
public Set<Class<? extends IdViaBothObj>> getTypeClasses() {
return Util.<Class<? extends IdViaBothObj>>asSet(IdViaBothObj.class);
}
}
}
}
| 5,890
| 35.364198
| 112
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/MarshalledValueSingleNodeTest.java
|
package org.infinispan.marshall;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.commons.marshall.MarshallingException;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "marshall.MarshalledValueSingleNodeTest")
public class MarshalledValueSingleNodeTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder c = getDefaultStandaloneCacheConfig(true);
c.invocationBatching().enable().memory().storageType(StorageType.BINARY);
EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(c);
cache = cm.getCache();
return cm;
}
@Test(expectedExceptions = MarshallingException.class)
public void testNonMarshallableValue() {
cache.put("Hello", new Object());
}
@Test(expectedExceptions = MarshallingException.class)
public void testNonMarshallableKey() {
cache.put(new Object(), "Hello");
}
}
| 1,233
| 35.294118
| 81
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/core/StoreAsBinaryTest.java
|
package org.infinispan.marshall.core;
import static org.infinispan.test.TestingUtil.createMapEntry;
import static org.infinispan.test.TestingUtil.extractComponent;
import static org.infinispan.test.TestingUtil.extractGlobalMarshaller;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.cache.impl.EncoderCache;
import org.infinispan.commons.marshall.MarshallingException;
import org.infinispan.commons.marshall.StreamingMarshaller;
import org.infinispan.commons.marshall.WrappedByteArray;
import org.infinispan.commons.marshall.WrappedBytes;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.commons.util.ObjectDuplicator;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.container.DataContainer;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.impl.InternalDataContainer;
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.event.CacheEntryCreatedEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.data.CountMarshallingPojo;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Tests implicit marshalled values
*
* @author Manik Surtani (<a href="mailto:manik AT jboss DOT org">manik AT jboss DOT org</a>)
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
@Test(groups = "functional", testName = "marshall.core.StoreAsBinaryTest")
public class StoreAsBinaryTest extends MultipleCacheManagersTest {
private static final Log log = LogFactory.getLog(StoreAsBinaryTest.class);
private static final String POJO_NAME = StoreAsBinaryTest.class.getName();
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder replSync = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false);
replSync.memory().storageType(StorageType.BINARY);
createClusteredCaches(2, "replSync", TestDataSCI.INSTANCE, replSync);
}
@Override
@AfterClass
protected void destroy() {
super.destroy();
}
@BeforeMethod
public void resetSerializationCounts() {
CountMarshallingPojo.reset(POJO_NAME);
}
public void testNonMarshallable() {
Cache<Object, Object> cache1 = cache(0, "replSync");
cache(1, "replSync");
Exceptions.expectException(MarshallingException.class, () -> cache1.put("Hello", new Object()));
Exceptions.expectException(MarshallingException.class, () -> cache1.put(new Object(), "Hello"));
}
public void testReleaseObjectValueReferences() {
Cache<String, CountMarshallingPojo> cache1 = cache(0, "replSync");
Cache<String, CountMarshallingPojo> cache2 = cache(1, "replSync");
assertTrue(cache1.isEmpty());
CountMarshallingPojo value = new CountMarshallingPojo(POJO_NAME, 1);
cache1.put("key", value);
assertTrue(cache1.containsKey("key"));
DataContainer<?, ?> dc1 = extractComponent(cache1, InternalDataContainer.class);
InternalCacheEntry<?, ?> ice = dc1.peek(boxKey(cache1, "key"));
Object o = ice.getValue();
assertTrue(o instanceof WrappedByteArray);
assertEquals(value, cache1.get("key"));
assertEquals(value, unboxValue(cache1, o));
// now on cache 2
DataContainer<?, ?> dc2 = TestingUtil.extractComponent(cache2, InternalDataContainer.class);
ice = dc2.peek(boxKey(cache2, "key"));
o = ice.getValue();
assertTrue(o instanceof WrappedByteArray);
assertEquals(value, cache2.get("key"));
assertEquals(value, unboxValue(cache2, o));
}
private Object boxKey(Cache<?, ?> cache, Object key) {
EncoderCache<?, ?> c = (EncoderCache<?, ?>) cache;
return c.keyToStorage(key);
}
private Object unboxKey(Cache<?, ?> cache, Object key) {
EncoderCache<?, ?> c = (EncoderCache<?, ?>) cache;
return c.keyFromStorage(key);
}
private Object unboxValue(Cache<?, ?> cache, Object value) {
EncoderCache<?, ?> c = (EncoderCache<?, ?>) cache;
return c.valueFromStorage(value);
}
public void testReleaseObjectKeyReferences() {
Cache<Object, String> cache1 = cache(0, "replSync");
Cache<Object, String> cache2 = cache(1, "replSync");
CountMarshallingPojo key = new CountMarshallingPojo(POJO_NAME, 1);
cache1.put(key, "value");
DataContainer<Object, String> dc1 = extractComponent(cache1, InternalDataContainer.class);
Object firstKeyStorage = dc1.iterator().next().getKey();
Object firstKey = cache1.getAdvancedCache().getKeyDataConversion().fromStorage(firstKeyStorage);
assertEquals(key, firstKey);
assertEquals("value", cache1.get(key));
// now on cache 2
DataContainer<Object, String> dc2 = extractComponent(cache2, InternalDataContainer.class);
firstKeyStorage = dc2.iterator().next().getKey();
firstKey = cache1.getAdvancedCache().getKeyDataConversion().fromStorage(firstKeyStorage);
assertEquals(key, firstKey);
assertEquals("value", cache2.get(key));
}
public void testKeySetValuesEntrySetCollectionReferences() {
Cache<Object, Object> cache1 = cache(0, "replSync");
Cache<Object, Object> cache2 = cache(1, "replSync");
CountMarshallingPojo key1 = new CountMarshallingPojo(POJO_NAME, 1);
CountMarshallingPojo value1 = new CountMarshallingPojo(POJO_NAME, 11);
CountMarshallingPojo key2 = new CountMarshallingPojo(POJO_NAME, 2);
CountMarshallingPojo value2 = new CountMarshallingPojo(POJO_NAME, 22);
String key3 = "3", value3 = "three";
cache1.put(key1, value1);
cache1.put(key2, value2);
cache1.put(key3, value3);
Set<Object> expKeys = new HashSet<>();
expKeys.add(key1);
expKeys.add(key2);
expKeys.add(key3);
Set<Object> expValues = new HashSet<>();
expValues.add(value1);
expValues.add(value2);
expValues.add(value3);
Set<Object> expKeyEntries = ObjectDuplicator.duplicateSet(expKeys);
Set<Object> expValueEntries = ObjectDuplicator.duplicateSet(expValues);
Set<Object> keys = cache2.keySet();
for (Object key : keys) assertTrue(expKeys.remove(key));
assertTrue("Did not see keys " + expKeys + " in iterator!", expKeys.isEmpty());
Collection<Object> values = cache2.values();
for (Object key : values) assertTrue(expValues.remove(key));
assertTrue("Did not see keys " + expValues + " in iterator!", expValues.isEmpty());
Set<Map.Entry<Object, Object>> entries = cache2.entrySet();
for (Map.Entry<Object, Object> entry : entries) {
assertTrue(expKeyEntries.remove(entry.getKey()));
assertTrue(expValueEntries.remove(entry.getValue()));
}
assertTrue("Did not see keys " + expKeyEntries + " in iterator!", expKeyEntries.isEmpty());
assertTrue("Did not see keys " + expValueEntries + " in iterator!", expValueEntries.isEmpty());
}
public void testUnsupportedKeyValueCollectionOperations() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
Set<Object> keys = cache(0, "replSync").keySet();
Collection<Object> values = cache(0, "replSync").values();
//noinspection unchecked
Collection<Object>[] collections = new Collection[]{keys, values};
Object newObj = "foo";
List<Object> newObjCol = new ArrayList<>();
newObjCol.add(newObj);
for (Collection<Object> col : collections) {
Exceptions.expectException(UnsupportedOperationException.class, () -> col.add(newObj));
Exceptions.expectException(UnsupportedOperationException.class, () -> col.addAll(newObjCol));
}
}
@Test(expectedExceptions = UnsupportedOperationException.class)
public void testAddMethodsForEntryCollection() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
Set<Map.Entry<Object, Object>> entries = cache(0, "replSync").entrySet();
entries.add(createMapEntry("4", "four"));
}
public void testRemoveMethodOfKeyValueEntryCollections() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
Set<Object> keys = cache(0, "replSync").keySet();
keys.remove(key1);
assertEquals(2, cache(0, "replSync").size());
Collection<Object> values = cache(0, "replSync").values();
values.remove(value2);
assertEquals(1, cache(0, "replSync").size());
Set<Map.Entry<Object, Object>> entries = cache(0, "replSync").entrySet();
entries.remove(TestingUtil.<Object, Object>createMapEntry(key3, value3));
assertEquals(0, cache(0, "replSync").size());
}
public void testClearMethodOfKeyCollection() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
Set<Object> keys = cache(0, "replSync").keySet();
keys.clear();
assertEquals(0, cache(0, "replSync").size());
}
public void testClearMethodOfValuesCollection() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
Collection<Object> values = cache(0, "replSync").values();
values.clear();
assertEquals(0, cache(0, "replSync").size());
}
public void testClearMethodOfEntryCollection() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
Set<Map.Entry<Object, Object>> entries = cache(0, "replSync").entrySet();
entries.clear();
assertEquals(0, cache(0, "replSync").size());
}
public void testRemoveAllMethodOfKeyCollection() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
List<String> keyCollection = new ArrayList<>(2);
keyCollection.add(key2);
keyCollection.add(key3);
Collection<Object> keys = cache(0, "replSync").keySet();
keys.removeAll(keyCollection);
assertEquals(1, cache(0, "replSync").size());
}
public void testRemoveAllMethodOfValuesCollection() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
List<String> valueCollection = new ArrayList<>(2);
valueCollection.add(value1);
valueCollection.add(value2);
Collection<Object> values = cache(0, "replSync").values();
values.removeAll(valueCollection);
assertEquals(1, cache(0, "replSync").size());
}
public void testRemoveAllMethodOfEntryCollection() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
List<Map.Entry<Object, Object>> entryCollection = new ArrayList<>(2);
entryCollection.add(createMapEntry(key1, value1));
entryCollection.add(createMapEntry(key3, value3));
Set<Map.Entry<Object, Object>> entries = cache(0, "replSync").entrySet();
entries.removeAll(entryCollection);
assertEquals(1, cache(0, "replSync").size());
}
public void testRetainAllMethodOfKeyCollection() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
List<String> keyCollection = new ArrayList<>(2);
keyCollection.add(key2);
keyCollection.add(key3);
keyCollection.add("6");
Collection<Object> keys = cache(0, "replSync").keySet();
keys.retainAll(keyCollection);
assertEquals(2, cache(0, "replSync").size());
}
public void testRetainAllMethodOfValuesCollection() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
List<String> valueCollection = new ArrayList<>(2);
valueCollection.add(value1);
valueCollection.add(value2);
valueCollection.add("5");
Collection<Object> values = cache(0, "replSync").values();
values.retainAll(valueCollection);
assertEquals(2, cache(0, "replSync").size());
}
public void testRetainAllMethodOfEntryCollection() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
List<Map.Entry<Object, Object>> entryCollection = new ArrayList<>(3);
entryCollection.add(createMapEntry(key1, value1));
entryCollection.add(createMapEntry(key3, value3));
entryCollection.add(createMapEntry("4", "5"));
Set<Map.Entry<Object, Object>> entries = cache(0, "replSync").entrySet();
entries.retainAll(entryCollection);
assertEquals(2, cache(0, "replSync").size());
}
public void testEntrySetValueFromEntryCollections() {
final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
Set<Map.Entry<Object, Object>> entries = cache(0, "replSync").entrySet();
String newString = "new-value";
for (Map.Entry<Object, Object> entry : entries) {
entry.setValue(newString);
}
assertEquals(3, cache(0, "replSync").size());
assertEquals(newString, cache(0, "replSync").get(key1));
assertEquals(newString, cache(0, "replSync").get(key2));
assertEquals(newString, cache(0, "replSync").get(key3));
}
public void testKeyValueEntryCollections() {
String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three";
Map<String, String> m = new HashMap<>();
m.put(key1, value1);
m.put(key2, value2);
m.put(key3, value3);
cache(0, "replSync").putAll(m);
assert 3 == cache(0, "replSync").size() && 3 == cache(0, "replSync").keySet().size() && 3 == cache(0, "replSync").values().size() && 3 == cache(0, "replSync").entrySet().size();
Set<Object> expKeys = new HashSet<>();
expKeys.add(key1);
expKeys.add(key2);
expKeys.add(key3);
Set<Object> expValues = new HashSet<>();
expValues.add(value1);
expValues.add(value2);
expValues.add(value3);
Set<Object> expKeyEntries = ObjectDuplicator.duplicateSet(expKeys);
Set<Object> expValueEntries = ObjectDuplicator.duplicateSet(expValues);
Set<Object> keys = cache(0, "replSync").keySet();
for (Object key : keys) {
assertTrue(expKeys.remove(key));
}
assertTrue("Did not see keys " + expKeys + " in iterator!", expKeys.isEmpty());
Collection<Object> values = cache(0, "replSync").values();
for (Object value : values) {
assertTrue(expValues.remove(value));
}
assertTrue("Did not see keys " + expValues + " in iterator!", expValues.isEmpty());
Set<Map.Entry<Object, Object>> entries = cache(0, "replSync").entrySet();
for (Map.Entry<Object, Object> entry : entries) {
assertTrue(expKeyEntries.remove(entry.getKey()));
assertTrue(expValueEntries.remove(entry.getValue()));
}
assertTrue("Did not see keys " + expKeyEntries + " in iterator!", expKeyEntries.isEmpty());
assertTrue("Did not see keys " + expValueEntries + " in iterator!", expValueEntries.isEmpty());
}
public void testEqualsAndHashCode() throws Exception {
StreamingMarshaller marshaller = extractGlobalMarshaller(manager(0));
CountMarshallingPojo pojo = new CountMarshallingPojo(POJO_NAME, 1);
WrappedBytes wb = new WrappedByteArray(marshaller.objectToByteBuffer(pojo));
WrappedBytes wb2 = new WrappedByteArray(marshaller.objectToByteBuffer(pojo));
assertEquals(wb2.hashCode(), wb.hashCode());
assertEquals(wb, wb2);
}
public void testComputeIfAbsentMethods() {
Cache<Object, Object> cache = cache(0, "replSync");
cache.computeIfAbsent("1", k -> k + "1", -1, TimeUnit.NANOSECONDS);
assertEquals(1, cache.size());
cache.computeIfAbsent("2", k -> k + "2", -1, TimeUnit.NANOSECONDS, -1, TimeUnit.NANOSECONDS);
assertEquals(2, cache.size());
}
/**
* Run this on a separate cache as it creates and stops stores, which might affect other tests.
*/
public void testStores() {
ConfigurationBuilder cacheCofig = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false);
cacheCofig.memory().storageType(StorageType.BINARY);
DummyInMemoryStoreConfigurationBuilder dimcs = new DummyInMemoryStoreConfigurationBuilder(cacheCofig.persistence());
dimcs.storeName(getClass().getSimpleName());
cacheCofig.persistence().addStore(dimcs);
defineConfigurationOnAllManagers("replSync2", cacheCofig);
waitForClusterToForm("replSync2");
Cache<Object, Object> cache1 = cache(0, "replSync2");
Cache<Object, Object> cache2 = cache(1, "replSync2");
CountMarshallingPojo pojo = new CountMarshallingPojo(POJO_NAME, 1);
cache1.put("key", pojo);
assertEquals(pojo, cache2.get("key"));
}
public void testCallbackValues() throws Exception {
Cache<Object, Object> cache1 = cache(0, "replSync");
cache(1, "replSync");
MockListener l = new MockListener();
cache1.addListener(l);
try {
CountMarshallingPojo pojo = new CountMarshallingPojo(POJO_NAME, 1);
cache1.put("key", pojo);
assertTrue("received " + l.newValue.getClass().getName(), l.newValue instanceof CountMarshallingPojo);
} finally {
cache1.removeListener(l);
}
}
public void testRemoteCallbackValues() throws Exception {
Cache<Object, Object> cache1 = cache(0, "replSync");
Cache<Object, Object> cache2 = cache(1, "replSync");
MockListener l = new MockListener();
cache2.addListener(l);
try {
CountMarshallingPojo pojo = new CountMarshallingPojo(POJO_NAME, 1);
cache1.put("key", pojo);
assertTrue(l.newValue instanceof CountMarshallingPojo);
} finally {
cache2.removeListener(l);
}
}
public void testEvictWithMarshalledValueKey() {
Cache<Object, Object> cache1 = cache(0, "replSync");
cache(1, "replSync");
CountMarshallingPojo pojo = new CountMarshallingPojo(POJO_NAME, 1);
cache1.put(pojo, pojo);
cache1.evict(pojo);
assertFalse(cache1.containsKey(pojo));
}
public void testModificationsOnSameCustomKey() {
Cache<Object, Object> cache1 = cache(0, "replSync");
Cache<Object, Object> cache2 = cache(1, "replSync");
CountMarshallingPojo key1 = new CountMarshallingPojo(POJO_NAME, 1);
log.trace("First put");
cache1.put(key1, "1");
log.trace("Second put");
CountMarshallingPojo key2 = new CountMarshallingPojo(POJO_NAME, 1);
assertEquals("1", cache2.put(key2, "2"));
}
public void testReturnValueDeserialization() {
Cache<String, CountMarshallingPojo> cache1 = cache(0, "replSync");
cache(1, "replSync");
CountMarshallingPojo v1 = new CountMarshallingPojo(POJO_NAME, 1);
cache1.put("1", v1);
CountMarshallingPojo previous = cache1.put("1", new CountMarshallingPojo(POJO_NAME, 2));
assertEquals(v1, previous);
}
public void testGetCacheEntryWithFlag() {
Cache<CountMarshallingPojo, String> cache1 = cache(0, "replSync");
cache(1, "replSync");
CountMarshallingPojo key1 = new CountMarshallingPojo(POJO_NAME, 1);
cache1.put(key1, "1");
assertEquals("1", cache1.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).getCacheEntry(key1).getValue());
}
@Listener
public static class MockListener {
Object newValue;
@CacheEntryModified
public void modified(CacheEntryModifiedEvent<Object, Object> e) {
if (!e.isPre()) newValue = e.getValue();
}
@CacheEntryCreated
public void created(CacheEntryCreatedEvent<Object, Object> e) {
if (!e.isPre()) newValue = e.getValue();
}
}
}
| 23,006
| 37.09106
| 183
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/core/PrimitivesTest.java
|
package org.infinispan.marshall.core;
import static java.util.Objects.deepEquals;
import static org.infinispan.commons.test.Exceptions.expectException;
import static org.infinispan.marshall.core.Primitives.ID_BOOLEAN_ARRAY;
import static org.infinispan.marshall.core.Primitives.ID_BOOLEAN_OBJ;
import static org.infinispan.marshall.core.Primitives.ID_BYTE_ARRAY;
import static org.infinispan.marshall.core.Primitives.ID_BYTE_OBJ;
import static org.infinispan.marshall.core.Primitives.ID_CHAR_ARRAY;
import static org.infinispan.marshall.core.Primitives.ID_CHAR_OBJ;
import static org.infinispan.marshall.core.Primitives.ID_DOUBLE_ARRAY;
import static org.infinispan.marshall.core.Primitives.ID_DOUBLE_OBJ;
import static org.infinispan.marshall.core.Primitives.ID_FLOAT_ARRAY;
import static org.infinispan.marshall.core.Primitives.ID_FLOAT_OBJ;
import static org.infinispan.marshall.core.Primitives.ID_INT_ARRAY;
import static org.infinispan.marshall.core.Primitives.ID_INT_OBJ;
import static org.infinispan.marshall.core.Primitives.ID_LONG_ARRAY;
import static org.infinispan.marshall.core.Primitives.ID_LONG_OBJ;
import static org.infinispan.marshall.core.Primitives.ID_SHORT_ARRAY;
import static org.infinispan.marshall.core.Primitives.ID_SHORT_OBJ;
import static org.infinispan.marshall.core.Primitives.ID_STRING;
import static org.infinispan.marshall.core.Primitives.readPrimitive;
import static org.infinispan.marshall.core.Primitives.writePrimitive;
import static org.testng.AssertJUnit.assertTrue;
import java.io.IOException;
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;
/**
* Created by karesti on 22/03/17.
*/
@Test(groups = "functional", testName = "marshall.PrimitivesTest")
public class PrimitivesTest extends AbstractInfinispanTest {
private EmbeddedCacheManager cm;
private GlobalMarshaller globalMarshaller;
@BeforeClass
public void setUp() {
cm = TestCacheManagerFactory.createCacheManager();
globalMarshaller = TestingUtil.extractGlobalMarshaller(cm);
}
@AfterClass
public void tearDown() {
if (cm != null) cm.stop();
}
public void testReadAndWrite() throws Exception {
assertReadAndWrite(new byte[]{0, 1}, ID_BYTE_ARRAY);
assertReadAndWrite("kaixo", ID_STRING);
assertReadAndWrite(true, ID_BOOLEAN_OBJ);
assertReadAndWrite((byte) 0, ID_BYTE_OBJ);
assertReadAndWrite('P', ID_CHAR_OBJ);
assertReadAndWrite(123d, ID_DOUBLE_OBJ);
assertReadAndWrite(123f, ID_FLOAT_OBJ);
assertReadAndWrite(123, ID_INT_OBJ);
assertReadAndWrite(123L, ID_LONG_OBJ);
assertReadAndWrite((short) 123, ID_SHORT_OBJ);
assertReadAndWrite(new boolean[]{true, false}, ID_BOOLEAN_ARRAY);
assertReadAndWrite(new char[]{'k', 'a', 'i', 'x', 'o'}, ID_CHAR_ARRAY);
assertReadAndWrite(new double[]{123d, 456d}, ID_DOUBLE_ARRAY);
assertReadAndWrite(new float[]{123f, 456f}, ID_FLOAT_ARRAY);
assertReadAndWrite(new int[]{123, 456}, ID_INT_ARRAY);
assertReadAndWrite(new long[]{123L, 456L}, ID_LONG_ARRAY);
assertReadAndWrite(new short[]{123, 456}, ID_SHORT_ARRAY);
expectException(IOException.class, "Unknown primitive type: diable",
() -> writePrimitive("diable", new BytesObjectOutput(10240, globalMarshaller), 666));
}
private void assertReadAndWrite(Object write, int id) throws IOException, ClassNotFoundException {
BytesObjectOutput out = new BytesObjectOutput(10240, globalMarshaller);
writePrimitive(write, out, id);
Object read = readPrimitive(BytesObjectInput.from(out.bytes, 0, globalMarshaller));
assertTrue(deepEquals(write, read));
}
public void testLargeArray() {
BytesObjectOutput out = new BytesObjectOutput(10240, globalMarshaller);
byte[] bytes = new byte[]{0};
out.write(bytes);
expectException(OutOfMemoryError.class, () -> out.write(bytes, 0, Integer.MAX_VALUE));
}
}
| 4,185
| 43.531915
| 101
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/core/ExternalizerConfigurationValidationTest.java
|
package org.infinispan.marshall.core;
import static org.infinispan.marshall.AdvancedExternalizerTest.IdViaAnnotationObj;
import static org.infinispan.marshall.AdvancedExternalizerTest.IdViaBothObj;
import static org.infinispan.marshall.AdvancedExternalizerTest.IdViaConfigObj;
import static org.testng.AssertJUnit.assertEquals;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Set;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.util.Util;
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.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Test the externalizer validation logic.
*
* Externalizers can only be used with jboss-marshalling, so we cannot test the actual functionality
* in the core module.
*/
@Test(groups = "functional", testName = "marshall.core.ExternalizerConfigurationValidationTest")
public class ExternalizerConfigurationValidationTest extends AbstractInfinispanTest {
private static final Log log = LogFactory.getLog(ExternalizerConfigurationValidationTest.class);
private EmbeddedCacheManager cm;
@BeforeClass
public void setUp() {
cm = TestCacheManagerFactory.createCacheManager();
}
@AfterClass
public void tearDown() {
if (cm != null) cm.stop();
}
public void testInternalDuplicateExternalizerId() throws Exception {
withExpectedInternalFailure(new DuplicateIdClass.Externalizer(), "Should have thrown a CacheException reporting the duplicate id");
}
public void testInternalExternalIdLimit() {
withExpectedInternalFailure(new TooHighIdClass.Externalizer(), "Should have thrown a CacheException indicating that the Id is too high");
}
@Test(expectedExceptions=CacheException.class)
public void testForeignExternalizerIdNegative() {
GlobalConfigurationBuilder global = createForeignExternalizerGlobalConfig(-1);
TestCacheManagerFactory.createCacheManager(global, new ConfigurationBuilder());
}
@Test(expectedExceptions=CacheConfigurationException.class)
public void testForeignExternalizerIdClash() {
createMultiForeignExternalizerGlobalConfig(3456, true);
}
@Test(expectedExceptions=CacheConfigurationException.class)
public void testForeignExternalizerIdClash2() {
createMultiForeignExternalizerGlobalConfig(5678, true);
}
@Test(expectedExceptions=CacheConfigurationException.class)
public void testForeignExternalizerWithoutId() {
createMultiForeignExternalizerGlobalConfig(9999, false);
}
public void testForeignExternalizerConfigIdWins() throws Exception {
GlobalConfigurationBuilder globalCfg = createForeignExternalizerGlobalConfig(3456);
EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(globalCfg, new ConfigurationBuilder());
try {
cm.getCache();
assertEquals(3456, findExternalizerId(new IdViaBothObj(), cm));
} finally {
cm.stop();
}
}
private int findExternalizerId(Object obj, EmbeddedCacheManager cm) {
GlobalMarshaller marshaller = TestingUtil.extractGlobalMarshaller(cm);
return ((AdvancedExternalizer<?>) marshaller.findExternalizerFor(obj)).getId();
}
public void testForeignExternalizerMultiClassTypesViaSameExternalizer() {
GlobalConfigurationBuilder builder = new GlobalConfigurationBuilder();
builder.serialization().addAdvancedExternalizer(new MultiIdViaClassExternalizer());
EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(builder, new ConfigurationBuilder());
try {
cm.getCache();
assert 767 == findExternalizerId(new IdViaConfigObj(), cm);
assert 767 == findExternalizerId(new IdViaAnnotationObj(), cm);
assert 767 == findExternalizerId(new IdViaBothObj(), cm);
} finally {
cm.stop();
}
}
public void testForeignExternalizerMultiClassNameTypesViaSameExternalizer() {
GlobalConfigurationBuilder builder = new GlobalConfigurationBuilder();
builder.serialization().addAdvancedExternalizer(868, new MultiIdViaClassNameExternalizer());
EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(builder, new ConfigurationBuilder());
try {
cm.getCache();
assert 868 == findExternalizerId(new IdViaConfigObj(), cm);
assert 868 == findExternalizerId(new IdViaAnnotationObj(), cm);
assert 868 == findExternalizerId(new IdViaBothObj(), cm);
} finally {
cm.stop();
}
}
private GlobalConfigurationBuilder createForeignExternalizerGlobalConfig(int id) {
GlobalConfigurationBuilder builder = new GlobalConfigurationBuilder();
builder.serialization().addAdvancedExternalizer(id, new IdViaBothObj.Externalizer());
return builder;
}
private GlobalConfigurationBuilder createMultiForeignExternalizerGlobalConfig(int id, boolean doSetId) {
GlobalConfigurationBuilder builder = new GlobalConfigurationBuilder();
if (doSetId)
builder.serialization().addAdvancedExternalizer(id, new IdViaConfigObj.Externalizer());
else
builder.serialization().addAdvancedExternalizer(new IdViaConfigObj.Externalizer());
builder.serialization().addAdvancedExternalizer(new IdViaAnnotationObj.Externalizer());
builder.serialization().addAdvancedExternalizer(3456, new IdViaBothObj.Externalizer());
return builder;
}
private void withExpectedInternalFailure(final AdvancedExternalizer<?> ext, String message) {
try {
GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder();
globalBuilder.serialization().addAdvancedExternalizer(ext).addAdvancedExternalizer(ext);
assert false : message;
} catch (CacheConfigurationException ce) {
log.trace("Expected exception", ce);
} finally {
cm.stop();
}
}
static class DuplicateIdClass {
public static class Externalizer extends AbstractExternalizer<DuplicateIdClass> {
@Override
public DuplicateIdClass readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return null;
}
@Override
public void writeObject(ObjectOutput output, DuplicateIdClass object) throws IOException {
}
@Override
public Integer getId() {
return Ids.MAPS;
}
@Override
public Set<Class<? extends DuplicateIdClass>> getTypeClasses() {
return Util.<Class<? extends DuplicateIdClass>>asSet(DuplicateIdClass.class);
}
}
}
static class TooHighIdClass {
public static class Externalizer extends AbstractExternalizer<TooHighIdClass> {
@Override
public TooHighIdClass readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return null;
}
@Override
public void writeObject(ObjectOutput output, TooHighIdClass object) throws IOException {
}
@Override
public Integer getId() {
return 255;
}
@Override
public Set<Class<? extends TooHighIdClass>> getTypeClasses() {
return Util.<Class<? extends TooHighIdClass>>asSet(TooHighIdClass.class);
}
}
}
static class MultiIdViaClassExternalizer extends AbstractExternalizer<Object> {
private final AdvancedExternalizer idViaConfigObjExt = new IdViaConfigObj.Externalizer();
private final AdvancedExternalizer idViaAnnotationObjExt = new IdViaAnnotationObj.Externalizer();
private final AdvancedExternalizer idViaBothObjExt = new IdViaBothObj.Externalizer();
@Override
public void writeObject(ObjectOutput output, Object object) throws IOException {
AdvancedExternalizer ext;
if (object instanceof IdViaConfigObj) {
output.write(0);
ext = idViaConfigObjExt;
} else if (object instanceof IdViaAnnotationObj) {
output.write(1);
ext = idViaAnnotationObjExt;
} else if (object instanceof IdViaBothObj){
output.write(2);
ext = idViaBothObjExt;
} else {
throw new CacheException(String.format(
"Object of type %s is not supported by externalizer %s",
object.getClass().getName(), this.getClass().getName()));
}
ext.writeObject(output, object);
}
@Override
public Object readObject(ObjectInput input) throws IOException, ClassNotFoundException {
int index = input.read();
AdvancedExternalizer ext;
switch (index) {
case 0:
ext = idViaConfigObjExt;
break;
case 1:
ext = idViaAnnotationObjExt;
break;
case 2:
ext = idViaBothObjExt;
break;
default:
throw new CacheException(String.format(
"Unknown index (%d) for externalizer %s",
index, this.getClass().getName()));
}
return ext.readObject(input);
}
@Override
public Integer getId() {
return 767;
}
@Override
public Set<Class<? extends Object>> getTypeClasses() {
return Util.asSet(IdViaConfigObj.class, IdViaAnnotationObj.class, IdViaBothObj.class);
}
}
static class MultiIdViaClassNameExternalizer extends MultiIdViaClassExternalizer {
@Override
public Integer getId() {
// Revert to default so that it can be retrieved from config
return null;
}
@Override
public Set<Class<? extends Object>> getTypeClasses() {
return Util.<Class<? extends Object>>asSet(
Util.loadClass("org.infinispan.marshall.AdvancedExternalizerTest$IdViaConfigObj", Thread.currentThread().getContextClassLoader()),
Util.loadClass("org.infinispan.marshall.AdvancedExternalizerTest$IdViaAnnotationObj", Thread.currentThread().getContextClassLoader()),
Util.loadClass("org.infinispan.marshall.AdvancedExternalizerTest$IdViaBothObj", Thread.currentThread().getContextClassLoader()));
}
}
}
| 10,928
| 38.597826
| 149
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/exts/DoubleSummaryStatisticsExternalizerTest.java
|
package org.infinispan.marshall.exts;
import java.io.IOException;
import java.util.DoubleSummaryStatistics;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "marshall.DoubleSummaryStatisticsExternalizerTest")
public class DoubleSummaryStatisticsExternalizerTest extends AbstractExternalizerTest<DoubleSummaryStatistics> {
public void testFinite() throws Exception {
DoubleSummaryStatistics stats = new DoubleSummaryStatistics();
stats.accept(10.0/3);
stats.accept(-0.1);
DoubleSummaryStatistics deserialized = deserialize(stats);
assertStatsAreEqual(stats, deserialized);
}
public void testPositiveNegativeInfinites() throws Exception {
// In JDK 10+, we expect the externalizer to pass inner state values through constructor, instead of via
// reflection. The state of this statistics instance however doesn't pass constructor validations, so
// deserialization of this instance fails in JDK 10+.
DoubleSummaryStatistics stats = new DoubleSummaryStatistics();
stats.accept(Double.POSITIVE_INFINITY);
stats.accept(Double.NEGATIVE_INFINITY);
try {
DoubleSummaryStatistics deserialized = deserialize(stats);
assertStatsAreEqual(stats, deserialized);
} catch (IOException e) {
if (SecurityActions.getConstructor(DoubleSummaryStatistics.class,
long.class, double.class, double.class, double.class) != null) {
// JDK 10+, ignore
} else {
throw e;
}
}
}
public void testNaN() throws Exception {
DoubleSummaryStatistics stats = new DoubleSummaryStatistics();
stats.accept(-1);
stats.accept(Double.NaN);
DoubleSummaryStatistics deserialized = deserialize(stats);
assertStatsAreEqual(stats, deserialized);
}
public void testInfinity() throws Exception {
DoubleSummaryStatistics stats = new DoubleSummaryStatistics();
stats.accept(Double.POSITIVE_INFINITY);
stats.accept(-1);
DoubleSummaryStatistics deserialized = deserialize(stats);
assertStatsAreEqual(stats, deserialized);
}
@Override
AbstractExternalizer<DoubleSummaryStatistics> createExternalizer() {
return new DoubleSummaryStatisticsExternalizer();
}
private void assertStatsAreEqual(DoubleSummaryStatistics original, DoubleSummaryStatistics deserialized) {
Assert.assertEquals(original.getCount(), deserialized.getCount());
Assert.assertEquals(original.getMin(), deserialized.getMin());
Assert.assertEquals(original.getMax(), deserialized.getMax());
Assert.assertEquals(original.getSum(), deserialized.getSum());
Assert.assertEquals(original.getAverage(), deserialized.getAverage());
}
}
| 2,964
| 38.533333
| 112
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/exts/IntSummaryStatisticsExternalizerTest.java
|
package org.infinispan.marshall.exts;
import java.util.IntSummaryStatistics;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.testng.annotations.Test;
import org.testng.Assert;
@Test(groups = "unit", testName = "marshall.IntSummaryStatisticsExternalizerTest")
public class IntSummaryStatisticsExternalizerTest extends AbstractExternalizerTest<IntSummaryStatistics> {
public void test() throws Exception {
IntSummaryStatistics stats = new IntSummaryStatistics();
stats.accept(1);
stats.accept(-Integer.MAX_VALUE);
IntSummaryStatistics deserialized = deserialize(stats);
assertStatsAreEqual(stats, deserialized);
}
@Override
AbstractExternalizer<IntSummaryStatistics> createExternalizer() {
return new IntSummaryStatisticsExternalizer();
}
private void assertStatsAreEqual(IntSummaryStatistics original, IntSummaryStatistics deserialized) {
Assert.assertEquals(original.getCount(), deserialized.getCount());
Assert.assertEquals(original.getMin(), deserialized.getMin());
Assert.assertEquals(original.getMax(), deserialized.getMax());
Assert.assertEquals(original.getSum(), deserialized.getSum());
Assert.assertEquals(original.getAverage(), deserialized.getAverage());
}
}
| 1,316
| 37.735294
| 106
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/exts/LongSummaryStatisticsExternalizerTest.java
|
package org.infinispan.marshall.exts;
import java.util.LongSummaryStatistics;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.testng.annotations.Test;
import org.testng.Assert;
@Test(groups = "unit", testName = "marshall.LongSummaryStatisticsExternalizerTest")
public class LongSummaryStatisticsExternalizerTest extends AbstractExternalizerTest<LongSummaryStatistics> {
public void test() throws Exception {
LongSummaryStatistics stats = new LongSummaryStatistics();
stats.accept(1);
stats.accept(-Long.MAX_VALUE);
LongSummaryStatistics deserialized = deserialize(stats);
assertStatsAreEqual(stats, deserialized);
}
@Override
AbstractExternalizer<LongSummaryStatistics> createExternalizer() {
return new LongSummaryStatisticsExternalizer();
}
private void assertStatsAreEqual(LongSummaryStatistics original, LongSummaryStatistics deserialized) {
Assert.assertEquals(original.getCount(), deserialized.getCount());
Assert.assertEquals(original.getMin(), deserialized.getMin());
Assert.assertEquals(original.getMax(), deserialized.getMax());
Assert.assertEquals(original.getSum(), deserialized.getSum());
Assert.assertEquals(original.getAverage(), deserialized.getAverage());
}
}
| 1,324
| 37.970588
| 108
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/exts/AbstractExternalizerTest.java
|
package org.infinispan.marshall.exts;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.infinispan.commons.marshall.AbstractExternalizer;
public abstract class AbstractExternalizerTest<T> {
protected AbstractExternalizer<T> externalizer;
public AbstractExternalizerTest() {
this.externalizer = createExternalizer();
}
protected T deserialize(T object) throws IOException, ClassNotFoundException {
byte[] buffer;
final int byteArrayLength = 8 * 6; // 8 bytes (size of long/double) * 6 fields
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(byteArrayLength)) {
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
externalizer.writeObject(oos, object);
}
buffer = baos.toByteArray();
}
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buffer));
return externalizer.readObject(ois);
}
abstract AbstractExternalizer<T> createExternalizer();
}
| 1,154
| 32.970588
| 88
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/exts/RemoteExceptionExternalizerTest.java
|
package org.infinispan.marshall.exts;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.core.GlobalMarshaller;
import org.infinispan.remoting.RemoteException;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.assertEquals;
@Test(groups = "unit", testName = "marshall.RemoteExceptionExternalizerTest")
public class RemoteExceptionExternalizerTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.createCacheManager();
}
public void testKnownThrowable() throws Exception {
GlobalMarshaller marshaller = TestingUtil.extractGlobalMarshaller(cacheManager);
Throwable cause = new IllegalStateException(IllegalStateException.class.getSimpleName());
cause.addSuppressed(new IllegalArgumentException(IllegalArgumentException.class.getSimpleName()));
cause.addSuppressed(new IllegalStateException(IllegalStateException.class.getSimpleName()));
cause.addSuppressed(new IllegalLifecycleStateException(IllegalLifecycleStateException.class.getSimpleName()));
RemoteException remoteException = new RemoteException(RemoteException.class.getSimpleName(), cause);
byte[] bytes = marshaller.objectToByteBuffer(remoteException);
remoteException = (RemoteException) marshaller.objectFromByteBuffer(bytes);
cause = remoteException.getCause();
assertEquals(cause.getMessage(), IllegalStateException.class.getSimpleName());
assertEquals(cause.getSuppressed()[0].getMessage(), IllegalArgumentException.class.getSimpleName());
assertEquals(cause.getSuppressed()[1].getMessage(), IllegalStateException.class.getSimpleName());
assertEquals(cause.getSuppressed()[2].getMessage(), IllegalLifecycleStateException.class.getSimpleName());
}
public void testGenericThrowable() throws Exception {
GlobalMarshaller marshaller = TestingUtil.extractGlobalMarshaller(cacheManager);
Throwable exception = new IllegalStateException(IllegalStateException.class.getSimpleName());
exception.addSuppressed(new IllegalArgumentException(IllegalArgumentException.class.getSimpleName()));
exception.addSuppressed(new IllegalStateException(IllegalStateException.class.getSimpleName()));
byte[] bytes = marshaller.objectToByteBuffer(exception);
exception = (IllegalStateException) marshaller.objectFromByteBuffer(bytes);
assertEquals(exception.getMessage(), IllegalStateException.class.getSimpleName());
assertEquals(exception.getSuppressed()[0].getMessage(), IllegalArgumentException.class.getSimpleName());
assertEquals(exception.getSuppressed()[1].getMessage(), IllegalStateException.class.getSimpleName());
}
}
| 3,049
| 53.464286
| 118
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/protostream/impl/ProtoStreamBackwardsCompatibilityTest.java
|
package org.infinispan.marshall.protostream.impl;
import static org.testng.AssertJUnit.assertEquals;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.UUID;
import org.infinispan.commons.util.Util;
import org.infinispan.protostream.MessageMarshaller;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.types.java.CommonTypesSchema;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "marshall.ProtoStreamBackwardsCompatibilityTest")
public class ProtoStreamBackwardsCompatibilityTest {
public void testOldEventLoggerUUIDBytesAreReadable() throws IOException {
// Initialize SerializationContext like it used to be in the server
SerializationContext oldServerCtx = ProtobufUtil.newSerializationContext();
PersistenceContextManualInitializer serverInitializer = new PersistenceContextManualInitializer();
serverInitializer.registerSchema(oldServerCtx);
serverInitializer.registerMarshallers(oldServerCtx);
// Initialise SerializationContext using the new core initializer
SerializationContext coreCtx = ProtobufUtil.newSerializationContext();
CommonTypesSchema sci = new CommonTypesSchema();
sci.registerSchema(coreCtx);
sci.registerMarshallers(coreCtx);
UUID uuid = Util.threadLocalRandomUUID();
byte[] oldBytes = ProtobufUtil.toWrappedByteArray(oldServerCtx, uuid);
UUID unmarshalled = ProtobufUtil.fromWrappedByteArray(coreCtx, oldBytes);
assertEquals(uuid, unmarshalled);
byte[] newBytes = ProtobufUtil.toWrappedByteArray(coreCtx, uuid);
unmarshalled = ProtobufUtil.fromWrappedByteArray(coreCtx, newBytes);
assertEquals(uuid, unmarshalled);
}
private static class PersistenceContextManualInitializer implements SerializationContextInitializer {
String type(String message) {
return String.format("org.infinispan.persistence.m.event_logger.%s", message);
}
private PersistenceContextManualInitializer() {
}
@Override
public String getProtoFileName() {
return "persistence.m.event_logger.proto";
}
@Override
public String getProtoFile() throws UncheckedIOException {
return "package org.infinispan.persistence.m.event_logger;\n" +
"\n" +
"/**\n" +
" * @TypeId(1005)\n" +
" * ProtoStreamTypeIds.SERVER_EVENT_UUID\n" +
" */\n" +
"message UUID {\n" +
" optional uint64 mostSigBits = 1;\n" +
" optional uint64 leastSigBits = 2;\n" +
"}\n";
}
@Override
public void registerSchema(SerializationContext serCtx) {
serCtx.registerProtoFiles(org.infinispan.protostream.FileDescriptorSource.fromString(getProtoFileName(), getProtoFile()));
}
@Override
public void registerMarshallers(SerializationContext serCtx) {
serCtx.registerMarshaller(new OldUUIDMarshaller(type(UUID.class.getSimpleName())));
}
}
private static class OldUUIDMarshaller implements MessageMarshaller<UUID> {
private final String typeName;
/**
* @param typeName so that marshaller can be used in multiple contexts
*/
public OldUUIDMarshaller(String typeName) {
this.typeName = typeName;
}
@Override
public UUID readFrom(ProtoStreamReader reader) throws IOException {
throw new IllegalStateException();
}
@Override
public void writeTo(MessageMarshaller.ProtoStreamWriter writer, UUID uuid) throws IOException {
writer.writeLong("mostSigBits", uuid.getMostSignificantBits());
writer.writeLong("leastSigBits", uuid.getLeastSignificantBits());
}
@Override
public Class<? extends UUID> getJavaClass() {
return UUID.class;
}
@Override
public String getTypeName() {
return typeName;
}
}
}
| 4,134
| 34.956522
| 131
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/marshall/persistence/impl/MarshalledEntryUtil.java
|
package org.infinispan.marshall.persistence.impl;
import org.infinispan.Cache;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.versioning.VersionGenerator;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.persistence.spi.MarshallableEntryFactory;
public class MarshalledEntryUtil {
public static <K,V> MarshallableEntry<K,V> create(K key, V value, Cache cache) {
return create(key, value, null, cache);
}
public static <K, V> MarshallableEntry<K, V> createWithVersion(K key, V value, Cache cache) {
ComponentRegistry registry = cache.getAdvancedCache().getComponentRegistry();
MarshallableEntryFactory<K, V> entryFactory = registry.getComponent(MarshallableEntryFactory.class);
VersionGenerator versionGenerator = registry.getVersionGenerator();
PrivateMetadata metadata = new PrivateMetadata.Builder().entryVersion(versionGenerator.generateNew()).build();
return entryFactory.create(key, value, null, metadata, -1, -1);
}
public static <K,V> MarshallableEntry<K,V> create(K key, V value, Metadata metadata, Cache cache) {
return create(key, value, metadata, -1, -1, cache);
}
public static <K,V> MarshallableEntry<K,V> create(K key, V value, Metadata metadata, long created, long lastUsed, Cache cache) {
MarshallableEntryFactory entryFactory = cache.getAdvancedCache().getComponentRegistry().getComponent(MarshallableEntryFactory.class);
return entryFactory.create(key, value, metadata, null, created, lastUsed);
}
public static <K,V> MarshallableEntry<K,V> create(K key, Marshaller m) {
return create(key, null, m);
}
public static <K,V> MarshallableEntry<K,V> create(K key, V value, Marshaller m) {
return create(key, value, null, -1, -1, m);
}
public static <K,V> MarshallableEntry<K,V> create(K key, V value, Metadata metadata, long created, long lastUsed, Marshaller m) {
return new MarshallableEntryImpl<>(key, value, metadata, null, created, lastUsed, m);
}
public static <K, V> MarshallableEntry<K, V> create(InternalCacheEntry<K, V> ice, Marshaller m) {
return new MarshallableEntryImpl<>(ice.getKey(), ice.getValue(), ice.getMetadata(), ice.getInternalMetadata(), ice.getCreated(), ice.getLastUsed(), m);
}
}
| 2,527
| 47.615385
| 157
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/metadata/InternalMetadataTest.java
|
package org.infinispan.metadata;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.util.concurrent.TimeUnit;
import org.infinispan.container.entries.AbstractInternalCacheEntry;
import org.infinispan.container.entries.InternalCacheValue;
import org.infinispan.container.versioning.EntryVersion;
import org.infinispan.metadata.impl.InternalMetadataImpl;
import org.testng.annotations.Test;
/**
* Tests the InternalMetadataImpl to check if it will not create a chain of InternalMetadataImpl
*
* @author Pedro Ruivo
* @since 6.0
*/
@Test(groups = "unit", testName = "metadata.InternalMetadataTest")
public class InternalMetadataTest {
public void testWithMetadata() {
TestMetadata metadata = new TestMetadata(1, 2);
InternalMetadataImpl internalMetadata = new InternalMetadataImpl(metadata, 3, 4);
assertInternalMetadataValues(internalMetadata, 1, 2, 3, 4);
assertInternalMetadataActual(internalMetadata);
InternalMetadataImpl internalMetadata2 = new InternalMetadataImpl(internalMetadata, 5, 6);
assertInternalMetadataValues(internalMetadata2, 1, 2, 5, 6);
assertInternalMetadataActual(internalMetadata2);
}
public void testWithInternalCacheEntry() {
TestMetadata metadata = new TestMetadata(1, 2);
InternalMetadataImpl internalMetadata = new InternalMetadataImpl(metadata, 3, 4);
assertInternalMetadataValues(internalMetadata, 1, 2, 3, 4);
assertInternalMetadataActual(internalMetadata);
TestInternalCacheEntry cacheEntry = new TestInternalCacheEntry(internalMetadata, 5, 6);
InternalMetadataImpl internalMetadata2 = new InternalMetadataImpl(cacheEntry);
assertInternalMetadataValues(internalMetadata2, 1, 2, 5, 6);
assertInternalMetadataActual(internalMetadata2);
}
public void testWithInternalCacheEntry2() {
TestMetadata metadata = new TestMetadata(1, 2);
TestInternalCacheEntry cacheEntry = new TestInternalCacheEntry(metadata, 3, 4);
InternalMetadataImpl internalMetadata = new InternalMetadataImpl(cacheEntry);
assertInternalMetadataValues(internalMetadata, 1, 2, 3, 4);
assertInternalMetadataActual(internalMetadata);
}
private void assertInternalMetadataActual(InternalMetadataImpl metadata) {
assertFalse("'actual' field must not be an InternalMetadataImpl", metadata.actual() instanceof InternalMetadataImpl);
}
private void assertInternalMetadataValues(InternalMetadata metadata, long lifespan, long maxIdle, long created,
long lastUsed) {
assertEquals("Wrong lifespan value.", lifespan, metadata.lifespan());
assertEquals("Wrong maxIdle value.", maxIdle, metadata.maxIdle());
assertEquals("Wrong created value.", created, metadata.created());
assertEquals("Wrong lastUsed value.", lastUsed, metadata.lastUsed());
}
private class TestMetadata implements Metadata, Metadata.Builder {
private final long lifespan;
private final long maxIdle;
private TestMetadata(long lifespan, long maxIdle) {
this.lifespan = lifespan;
this.maxIdle = maxIdle;
}
@Override
public long lifespan() {
return lifespan;
}
@Override
public long maxIdle() {
return maxIdle;
}
@Override
public EntryVersion version() {
return null; // ignore
}
@Override
public Builder builder() {
return this; // ignore
}
@Override
public Builder lifespan(long time, TimeUnit unit) {
return new TestMetadata(unit.toMillis(time), maxIdle);
}
@Override
public Builder lifespan(long time) {
return lifespan(time, TimeUnit.MILLISECONDS);
}
@Override
public Builder maxIdle(long time, TimeUnit unit) {
return new TestMetadata(lifespan, unit.toMillis(time));
}
@Override
public Builder maxIdle(long time) {
return maxIdle(time, TimeUnit.MILLISECONDS);
}
@Override
public Builder version(EntryVersion version) {
return this;
}
@Override
public Metadata build() {
return this;
}
@Override
public Builder merge(Metadata metadata) {
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestMetadata that = (TestMetadata) o;
return lifespan == that.lifespan && maxIdle == that.maxIdle;
}
@Override
public int hashCode() {
int result = (int) (lifespan ^ (lifespan >>> 32));
result = 31 * result + (int) (maxIdle ^ (maxIdle >>> 32));
return result;
}
@Override
public String toString() {
return "TestMetadata{" +
"lifespan=" + lifespan +
", maxIdle=" + maxIdle +
'}';
}
}
//Dummy class
private class TestInternalCacheEntry extends AbstractInternalCacheEntry {
private final Metadata metadata;
private final long created;
private final long lastUsed;
private TestInternalCacheEntry(Metadata metadata, long created, long lastUsed) {
super(null, null, null);
this.metadata = metadata;
this.created = created;
this.lastUsed = lastUsed;
}
@Override
public boolean isExpired(long now) {
return false;
}
@Override
public boolean canExpire() {
return false;
}
@Override
public long getCreated() {
return created;
}
@Override
public long getLastUsed() {
return lastUsed;
}
@Override
public long getExpiryTime() {
return 0;
}
@Override
public void touch(long currentTimeMillis) {
}
@Override
public void reincarnate(long now) {
}
@Override
public InternalCacheValue<?> toInternalCacheValue() {
return null;
}
@Override
public long getLifespan() {
return metadata.lifespan();
}
@Override
public long getMaxIdle() {
return metadata.maxIdle();
}
@Override
public Metadata getMetadata() {
return metadata;
}
}
}
| 6,453
| 27.431718
| 123
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalWriteSkewInMemoryTest.java
|
package org.infinispan.functional;
import static org.infinispan.commons.test.Exceptions.assertException;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Collections;
import java.util.concurrent.CompletionException;
import java.util.stream.Stream;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.Transaction;
import javax.transaction.xa.XAException;
import org.infinispan.Cache;
import org.infinispan.remoting.RemoteException;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.WriteSkewException;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "functional.FunctionalWriteSkewInMemoryTest")
public class FunctionalWriteSkewInMemoryTest extends FunctionalTxInMemoryTest {
public FunctionalWriteSkewInMemoryTest() {
transactional(true).lockingMode(LockingMode.OPTIMISTIC).isolationLevel(IsolationLevel.REPEATABLE_READ);
}
@Override
protected String parameters() {
return null;
}
@DataProvider(name = "readCombos")
public static Object[][] readCombos() {
return Stream.of(Boolean.TRUE, Boolean.FALSE).flatMap(
isOwner -> Stream.of(ReadOp.values()).flatMap(
op1 -> Stream.of(ReadOp.values()).map(
op2 -> new Object[]{isOwner, op1, op2})))
.filter(args -> ((ReadOp) args[1]).isFunctional() || ((ReadOp) args[2]).isFunctional())
.toArray(Object[][]::new);
}
@Test(dataProvider = "readCombos")
public void testWriteSkew(boolean isOwner, ReadOp op1, ReadOp op2) throws Throwable {
Object key = getKey(isOwner, DIST);
cache(0, DIST).put(key, "value0");
tm.begin();
assertEquals("value0", op1.action.eval(cache(0, DIST), key, ro, rw));
Transaction transaction = tm.suspend();
cache(0, DIST).put(key, "value1");
tm.resume(transaction);
try {
assertEquals("value0", op2.action.eval(cache(0, DIST), key, ro, rw));
} catch (CompletionException e) {
assertException(WriteSkewException.class, e.getCause());
// this is fine; either we read the old value, or we can't read it and we throw
tm.rollback();
} catch (WriteSkewException e) {
// synchronous get is invoked using synchronous API, without wrapping into CompletionExceptions
assert op2 == ReadOp.GET;
}
if (tm.getStatus() == Status.STATUS_ACTIVE) {
try {
tm.commit();
} catch (RollbackException e) {
Throwable[] suppressed = e.getSuppressed();
assertTrue(suppressed != null && suppressed.length == 1);
assertEquals(XAException.class, suppressed[0].getClass());
Throwable cause = suppressed[0].getCause();
while (cause instanceof RemoteException) {
cause = cause.getCause();
}
assertNotNull(cause);
assertEquals(WriteSkewException.class, cause.getClass());
}
}
}
enum ReadOp {
READ(true, (cache, key, ro, rw) -> ro.eval(key, EntryView.ReadEntryView::get).join()),
READ_MANY(true, (cache, key, ro, rw) -> ro.evalMany(Collections.singleton(key), EntryView.ReadEntryView::get).findAny().get()),
READ_WRITE_KEY(true, (cache, key, ro, rw) -> rw.eval(key, EntryView.ReadEntryView::get).join()),
READ_WRITE_KEY_VALUE(true, (cache, key, ro, rw) -> rw.eval(key, null, (value, v) -> v.get()).join()),
READ_WRITE_MANY(true, (cache, key, ro, rw) -> rw.evalMany(Collections.singleton(key), EntryView.ReadEntryView::get).findAny().get()),
READ_WRITE_MANY_ENTRIES(true, (cache, key, ro, rw) -> rw.evalMany(Collections.singletonMap(key, null), (value, v) -> v.get()).findAny().get()),
GET(false, (cache, key, ro, rw) -> cache.get(key))
;
final Performer action;
final boolean functional;
ReadOp(boolean functional, Performer action) {
this.functional = functional;
this.action = action;
}
public boolean isFunctional() {
return functional;
}
@FunctionalInterface
private interface Performer {
Object eval(Cache cache, Object key, FunctionalMap.ReadOnlyMap<Object, String> ro, FunctionalMap.ReadWriteMap<Object, String> rw) throws Throwable;
}
}
}
| 4,580
| 39.184211
| 156
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalListenerAssertions.java
|
package org.infinispan.functional;
import static org.infinispan.functional.FunctionalListenerAssertions.TestType.CREATE;
import static org.infinispan.functional.FunctionalListenerAssertions.TestType.MODIFY;
import static org.infinispan.functional.FunctionalListenerAssertions.TestType.REMOVE;
import static org.infinispan.functional.FunctionalListenerAssertions.TestType.WRITE;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;
import java.util.stream.IntStream;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.functional.decorators.FunctionalListeners;
public class FunctionalListenerAssertions<K, V> implements AutoCloseable {
public enum TestType {
CREATE, MODIFY, REMOVE, WRITE;
private InternalTestType lambdaType() {
switch (this) {
case CREATE: return InternalTestType.LAMBDA_CREATE;
case MODIFY: return InternalTestType.LAMBDA_MODIFY;
case REMOVE: return InternalTestType.LAMBDA_REMOVE;
case WRITE: return InternalTestType.LAMBDA_WRITE;
}
return null;
}
private InternalTestType listenerType() {
switch (this) {
case CREATE: return InternalTestType.LISTENER_CREATE;
case MODIFY: return InternalTestType.LISTENER_MODIFY;
case REMOVE: return InternalTestType.LISTENER_REMOVE;
case WRITE: return InternalTestType.LISTENER_WRITE;
}
return null;
}
}
private enum InternalTestType {
LAMBDA_CREATE, LAMBDA_MODIFY, LAMBDA_REMOVE,
LISTENER_CREATE, LISTENER_MODIFY, LISTENER_REMOVE,
LAMBDA_WRITE, LISTENER_WRITE
}
final FunctionalListeners<K, V> listeners;
final Runnable runnable;
final List<TestEvent<V>> recorded = new ArrayList<>();
final List<AutoCloseable> closeables = new ArrayList<>();
@SuppressWarnings("unchecked")
public static <K, V> FunctionalListenerAssertions<K, V> create(
ConcurrentMap<K, V> map, Runnable r) {
return new FunctionalListenerAssertions<>((FunctionalListeners<K, V>) map, r);
}
public static <K, V> FunctionalListenerAssertions<K, V> create(
FunctionalListeners<K, V> listeners, Runnable r) {
return new FunctionalListenerAssertions<>(listeners, r);
}
private FunctionalListenerAssertions(FunctionalListeners<K, V> listeners, Runnable runnable) {
this.listeners = listeners;
this.runnable = runnable;
Listeners.ReadWriteListeners<K, V> rw = this.listeners.readWriteListeners();
closeables.add(rw.onCreate(c -> recorded.add(
TestEvent.create(InternalTestType.LAMBDA_CREATE, c.get()))));
closeables.add(rw.onModify((b, a) -> recorded.add(
TestEvent.create(InternalTestType.LAMBDA_MODIFY, a.get(), b.get()))));
closeables.add(rw.onRemove(r -> recorded.add(
TestEvent.create(InternalTestType.LAMBDA_REMOVE, null, r.get()))));
closeables.add(rw.add(new Listeners.ReadWriteListeners.ReadWriteListener<K, V>() {
@Override
public void onCreate(ReadEntryView<K, V> created) {
recorded.add(TestEvent.create(InternalTestType.LISTENER_CREATE, created.get()));
}
@Override
public void onModify(ReadEntryView<K, V> before, ReadEntryView<K, V> after) {
recorded.add(TestEvent.create(InternalTestType.LISTENER_MODIFY, after.get(), before.get()));
}
@Override
public void onRemove(ReadEntryView<K, V> removed) {
recorded.add(TestEvent.create(InternalTestType.LISTENER_REMOVE, null, removed.get()));
}
}));
Listeners.WriteListeners<K, V> wo = this.listeners.writeOnlyListeners();
closeables.add(wo.onWrite(w -> recorded.add(
TestEvent.create(InternalTestType.LAMBDA_WRITE, w.find().orElse(null)))));
closeables.add(wo.add(w -> recorded.add(
TestEvent.create(InternalTestType.LISTENER_WRITE, w.find().orElse(null)))));
}
@Override
public void close() {
closeables.forEach(ac -> {
try {
ac.close();
} catch (Exception e) {
throw new AssertionError(e);
}
});
}
public void assertOrderedEvents(Collection<TestEvent<V>> expected) {
runnable.run();
assertEquals(expected, recorded);
}
public void assertUnorderedEvents(Collection<TestEvent<V>> expected) {
runnable.run();
assertEquals(recorded.toString(), expected.size(), recorded.size());
expected.forEach(e -> assertTrue(String.format("Value %s not in %s", e, recorded),
recorded.remove(e)));
assertEquals(0, recorded.size());
}
private static <K, V> void withAssertions(ConcurrentMap<K, V> map, Runnable r,
Consumer<FunctionalListenerAssertions<K, V>> c) {
try(FunctionalListenerAssertions<K, V> a = FunctionalListenerAssertions.create(map, r)) {
c.accept(a);
}
}
private static <K, V> void withAssertions(FunctionalListeners<K, V> listeners, Runnable r,
Consumer<FunctionalListenerAssertions<K, V>> c) {
try(FunctionalListenerAssertions<K, V> a = FunctionalListenerAssertions.create(listeners, r)) {
c.accept(a);
}
}
public static <K, V> void assertOrderedEvents(ConcurrentMap<K, V> map,
Runnable r, Collection<TestEvent<V>> expected) {
withAssertions(map, r, a -> a.assertOrderedEvents(expected));
}
public static <K, V> void assertOrderedEvents(FunctionalListeners<K, V> listeners,
Runnable r, Collection<TestEvent<V>> expected) {
withAssertions(listeners, r, a -> a.assertOrderedEvents(expected));
}
public static <K, V> void assertUnorderedEvents(ConcurrentMap<K, V> map,
Runnable r, Collection<TestEvent<V>> expected) {
withAssertions(map, r, a -> a.assertUnorderedEvents(expected));
}
public static <K, V> void assertUnorderedEvents(FunctionalListeners<K, V> listeners,
Runnable r, Collection<TestEvent<V>> expected) {
withAssertions(listeners, r, a -> a.assertUnorderedEvents(expected));
}
public static <K, V> void assertNoEvents(ConcurrentMap<K, V> map, Runnable r) {
withAssertions(map, r, a -> a.assertOrderedEvents(new ArrayList<>()));
}
public static <K, V> void assertNoEvents(FunctionalListeners<K, V> listeners, Runnable r) {
withAssertions(listeners, r, a -> a.assertOrderedEvents(new ArrayList<>()));
}
public static Collection<TestEvent<String>> create(String... values) {
List<TestEvent<String>> all = new ArrayList<>();
for (String value : values) all.addAll(TestEvent.create(CREATE, value));
for (String value : values) all.addAll(TestEvent.create(WRITE, value));
return all;
}
public static Collection<TestEvent<String>> createModify(String createdValue, String modifiedValue) {
List<TestEvent<String>> all = new ArrayList<>();
all.addAll(TestEvent.create(CREATE, createdValue));
all.addAll(TestEvent.create(WRITE, createdValue));
all.addAll(TestEvent.create(MODIFY, modifiedValue, createdValue));
all.addAll(TestEvent.create(WRITE, modifiedValue));
return all;
}
public static Collection<TestEvent<String>> createRemove(String value) {
List<TestEvent<String>> all = new ArrayList<>();
all.addAll(TestEvent.create(CREATE, value));
all.addAll(TestEvent.create(WRITE, value));
all.addAll(TestEvent.create(REMOVE, null, value));
all.addAll(TestEvent.create(WRITE, null));
return all;
}
public static Collection<TestEvent<String>> createAllRemoveAll(String... values) {
List<TestEvent<String>> all = new ArrayList<>();
for (String s : values) {
all.addAll(TestEvent.create(CREATE, s));
all.addAll(TestEvent.create(WRITE, s));
}
for (String s : values) {
all.addAll(TestEvent.create(REMOVE, null, s));
all.addAll(TestEvent.create(WRITE, null));
}
return all;
}
public static Collection<TestEvent<String>> createThenRemove(String... values) {
List<TestEvent<String>> all = new ArrayList<>();
for (String s : values) {
all.addAll(TestEvent.create(CREATE, s));
all.addAll(TestEvent.create(WRITE, s));
all.addAll(TestEvent.create(REMOVE, null, s));
all.addAll(TestEvent.create(WRITE, null));
}
return all;
}
public static Collection<TestEvent<String>> write(String... values) {
List<TestEvent<String>> all = new ArrayList<>();
for (String value : values) all.addAll(TestEvent.create(WRITE, value));
return all;
}
public static Collection<TestEvent<String>> writeModify(List<String> written, List<String> modified) {
List<TestEvent<String>> all = new ArrayList<>();
for (String value : written) all.addAll(TestEvent.create(WRITE, value));
IntStream.range(0, modified.size()).forEach(i -> {
all.addAll(TestEvent.create(MODIFY, modified.get(i), written.get(i)));
all.addAll(TestEvent.create(WRITE, modified.get(i)));
}
);
return all;
}
public static Collection<TestEvent<String>> createModifyRemove(String created, String modified) {
List<TestEvent<String>> all = new ArrayList<>();
all.addAll(TestEvent.create(CREATE, created));
all.addAll(TestEvent.create(WRITE, created));
all.addAll(TestEvent.create(MODIFY, modified, created));
all.addAll(TestEvent.create(WRITE, modified));
all.addAll(TestEvent.create(REMOVE, null, modified));
all.addAll(TestEvent.create(WRITE, null));
return all;
}
public static Collection<TestEvent<String>> createModifyRemove(List<String> created, List<String> modified) {
List<TestEvent<String>> all = new ArrayList<>();
created.forEach(s -> all.addAll(TestEvent.create(CREATE, s)));
created.forEach(s -> all.addAll(TestEvent.create(WRITE, s)));
modified.forEach(s -> all.addAll(TestEvent.create(WRITE, s)));
modified.forEach(s -> all.addAll(TestEvent.create(REMOVE, null, s)));
modified.forEach(s -> all.addAll(TestEvent.create(WRITE, null)));
return all;
}
public static Collection<TestEvent<String>> writeValueNull(String... values) {
List<TestEvent<String>> all = new ArrayList<>();
for (String s : values) all.addAll(TestEvent.create(WRITE, s));
for (String s : values) all.addAll(TestEvent.create(WRITE, null));
return all;
}
public static Collection<TestEvent<String>> writeRemove(String... values) {
List<TestEvent<String>> all = new ArrayList<>();
for (String s : values) all.addAll(TestEvent.create(WRITE, s));
for (String s : values) all.addAll(TestEvent.create(REMOVE, null, s));
for (String s : values) all.addAll(TestEvent.create(WRITE, null));
return all;
}
public static final class TestEvent<V> {
final InternalTestType type;
final Optional<V> prev;
final V value;
public static <V> Collection<TestEvent<V>> create(TestType type, V value) {
return Arrays.asList(TestEvent.create(type.lambdaType(), value),
TestEvent.create(type.listenerType(), value));
}
public static <V> Collection<TestEvent<V>> create(TestType type, V value, V prev) {
return Arrays.asList(TestEvent.create(type.lambdaType(), value, prev),
TestEvent.create(type.listenerType(), value, prev));
}
private static <V> TestEvent<V> create(InternalTestType type, V value) {
return new TestEvent<>(type, Optional.empty(), value);
}
private static <V> TestEvent<V> create(InternalTestType type, V value, V prev) {
return new TestEvent<>(type, Optional.of(prev), value);
}
private TestEvent(InternalTestType type, Optional<V> prev, V value) {
this.type = type;
this.prev = prev;
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestEvent<?> testEvent = (TestEvent<?>) o;
if (type != testEvent.type) return false;
if (!prev.equals(testEvent.prev)) return false;
return !(value != null ? !value.equals(testEvent.value) : testEvent.value != null);
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + prev.hashCode();
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "TestEvent{" +
"type=" + type +
", prev=" + prev +
", value=" + value +
'}';
}
}
}
| 13,081
| 38.403614
| 112
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalCachestoreTest.java
|
package org.infinispan.functional;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.infinispan.Cache;
import org.infinispan.persistence.dummy.DummyInMemoryStore;
import org.infinispan.persistence.manager.PersistenceManager;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
/**
* @author Radim Vansa <rvansa@redhat.com> and Krzysztof Sobolewski <Krzysztof.Sobolewski@atende.pl>
*/
@Test(groups = "functional", testName = "functional.FunctionalCachestoreTest")
public class FunctionalCachestoreTest extends AbstractFunctionalOpTest {
@Override
public Object[] factory() {
return new Object[] {
new FunctionalCachestoreTest().persistence(true).passivation(false),
new FunctionalCachestoreTest().persistence(true).passivation(true)
};
}
@Override
protected String parameters() {
return "[passivation=" + passivation + "]";
}
@Test(dataProvider = "owningModeAndWriteMethod")
public void testWriteLoad(boolean isSourceOwner, WriteMethod method) throws Exception {
Object key = getKey(isSourceOwner, DIST);
List<Cache<Object, Object>> owners = caches(DIST).stream()
.filter(cache -> cache.getAdvancedCache().getDistributionManager().getCacheTopology().isReadOwner(key))
.collect(Collectors.toList());
method.eval(key, wo, rw,
view -> { assertFalse(view.find().isPresent()); return null; },
(view, nil) -> view.set("value"), getClass());
assertInvocations(2);
caches(DIST).forEach(cache -> assertEquals(cache.get(key), "value", getAddress(cache).toString()));
// Staggered gets could arrive after evict command and that would reload the entry into DC
advanceGenerationsAndAwait(10, TimeUnit.SECONDS);
caches(DIST).forEach(cache -> cache.evict(key));
caches(DIST).forEach(cache -> assertFalse(cache.getAdvancedCache().getDataContainer().containsKey(key), getAddress(cache).toString()));
owners.forEach(cache -> {
DummyInMemoryStore store = getStore(cache);
assertTrue(store.contains(key), getAddress(cache).toString());
});
resetInvocationCount();
method.eval(key, wo, rw,
view -> {
assertTrue(view.find().isPresent());
assertEquals(view.get(), "value");
return null;
},
(view, nil) -> {}, getClass());
if (method.isMany) {
assertInvocations(2);
} else {
assertInvocations(1);
}
}
public DummyInMemoryStore getStore(Cache cache) {
Set<DummyInMemoryStore> stores = TestingUtil.extractComponent(cache, PersistenceManager.class).getStores(DummyInMemoryStore.class);
return stores.iterator().next();
}
@Test(dataProvider = "writeMethods")
public void testWriteLoadLocal(WriteMethod method) {
Integer key = 1;
method.eval(key, lwo, lrw,
view -> { assertFalse(view.find().isPresent()); return null; },
(view, nil) -> view.set("value"), getClass());
assertInvocations(1);
Cache<Integer, String> cache = cacheManagers.get(0).getCache();
assertEquals(cache.get(key), "value");
cache.evict(key);
assertFalse(cache.getAdvancedCache().getDataContainer().containsKey(key));
DummyInMemoryStore store = getStore(cache);
assertTrue(store.contains(key));
method.eval(key, lwo, lrw,
view -> {
assertTrue(view.find().isPresent());
assertEquals(view.get(), "value");
return null;
},
(view, nil) -> {}, getClass());
assertInvocations(2);
}
@Test(dataProvider = "owningModeAndReadMethod")
public void testReadLoad(boolean isSourceOwner, ReadMethod method) {
Object key = getKey(isSourceOwner, DIST);
List<Cache<Object, Object>> owners = caches(DIST).stream()
.filter(cache -> cache.getAdvancedCache().getDistributionManager().getCacheTopology().isReadOwner(key))
.collect(Collectors.toList());
assertTrue(method.eval(key, ro, view -> { assertFalse(view.find().isPresent()); return true; }));
// we can't add from read-only cache, so we put manually:
cache(0, DIST).put(key, "value");
caches(DIST).forEach(cache -> assertEquals(cache.get(key), "value", getAddress(cache).toString()));
caches(DIST).forEach(cache -> cache.evict(key));
caches(DIST).forEach(cache -> assertFalse(cache.getAdvancedCache().getDataContainer().containsKey(key), getAddress(cache).toString()));
owners.forEach(cache -> {
Set<DummyInMemoryStore> stores = cache.getAdvancedCache().getComponentRegistry().getComponent(PersistenceManager.class).getStores(DummyInMemoryStore.class);
DummyInMemoryStore store = stores.iterator().next();
assertTrue(store.contains(key), getAddress(cache).toString());
});
assertEquals(method.eval(key, ro,
view -> {
assertTrue(view.find().isPresent());
assertEquals(view.get(), "value");
return "OK";
}), "OK");
}
}
| 5,361
| 37.3
| 165
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalListenersTest.java
|
package org.infinispan.functional;
import static org.infinispan.marshall.core.MarshallableFunctions.removeConsumer;
import static org.infinispan.marshall.core.MarshallableFunctions.removeReturnPrevOrNull;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueConsumer;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueReturnPrevOrNull;
import static org.infinispan.functional.FunctionalTestUtils.rw;
import static org.infinispan.functional.FunctionalTestUtils.supplyIntKey;
import static org.infinispan.functional.FunctionalTestUtils.wo;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.functional.FunctionalMap.ReadWriteMap;
import org.infinispan.functional.FunctionalMap.WriteOnlyMap;
import org.infinispan.functional.Listeners.ReadWriteListeners.ReadWriteListener;
import org.infinispan.functional.Listeners.WriteListeners.WriteListener;
import org.infinispan.functional.TestFunctionalInterfaces.SetConstantOnReadWrite;
import org.infinispan.functional.TestFunctionalInterfaces.SetConstantOnWriteOnly;
import org.testng.annotations.Test;
/**
* Test suite for verifying functional map listener functionality.
*/
@Test(groups = "functional", testName = "functional.FunctionalListenersTest")
public class FunctionalListenersTest extends AbstractFunctionalTest {
public void testLocalLambdaReadWriteListeners() throws Exception {
doLambdaReadWriteListeners(supplyIntKey(), wo(fmapL1), rw(fmapL2), true);
}
public void testReplLambdaReadWriteListeners() throws Exception {
doLambdaReadWriteListeners(supplyKeyForCache(0, REPL), wo(fmapR1), rw(fmapR2), true);
doLambdaReadWriteListeners(supplyKeyForCache(1, REPL), wo(fmapR1), rw(fmapR2), true);
}
@Test
public void testDistLambdaReadWriteListeners() throws Exception {
doLambdaReadWriteListeners(supplyKeyForCache(0, DIST), wo(fmapD1), rw(fmapD2), false);
doLambdaReadWriteListeners(supplyKeyForCache(1, DIST), wo(fmapD1), rw(fmapD2), true);
}
private <K> void doLambdaReadWriteListeners(Supplier<K> keySupplier,
WriteOnlyMap<K, String> woMap, ReadWriteMap<K, String> rwMap, boolean isOwner) throws Exception {
K key1 = keySupplier.get();
List<CountDownLatch> latches = new ArrayList<>();
latches.addAll(Arrays.asList(new CountDownLatch(1), new CountDownLatch(1), new CountDownLatch(1)));
AutoCloseable onCreate = rwMap.listeners().onCreate(created -> {
assertEquals("created", created.get());
latches.get(0).countDown();
});
AutoCloseable onModify = rwMap.listeners().onModify((before, after) -> {
assertEquals("created", before.get());
assertEquals("modified", after.get());
latches.get(1).countDown();
});
AutoCloseable onRemove = rwMap.listeners().onRemove(removed -> {
assertEquals("modified", removed.get());
latches.get(2).countDown();
});
awaitNoEvent(woMap.eval(key1, "created", setValueConsumer()), latches.get(0));
awaitNoEvent(woMap.eval(key1, "modified", setValueConsumer()), latches.get(1));
awaitNoEvent(woMap.eval(key1, removeConsumer()), latches.get(2));
K key2 = keySupplier.get();
awaitEventIfOwner(isOwner, rwMap.eval(key2, "created", setValueReturnPrevOrNull()), latches.get(0));
awaitEventIfOwner(isOwner, rwMap.eval(key2, "modified", setValueReturnPrevOrNull()), latches.get(1));
awaitEventIfOwner(isOwner, rwMap.eval(key2, removeReturnPrevOrNull()), latches.get(2));
launderLatches(latches, 3);
K key3 = keySupplier.get();
awaitEventIfOwner(isOwner, rwMap.eval(key3, new SetConstantOnReadWrite<>("created")), latches.get(0));
awaitEventIfOwner(isOwner, rwMap.eval(key3, new SetConstantOnReadWrite<>("modified")), latches.get(1));
awaitEventIfOwner(isOwner, rwMap.eval(key3, removeReturnPrevOrNull()), latches.get(2));
// TODO: Test other evals....
onCreate.close();
onModify.close();
onRemove.close();
launderLatches(latches, 3);
K key4 = keySupplier.get();
awaitNoEvent(woMap.eval(key4, "tres", setValueConsumer()), latches.get(0));
awaitNoEvent(woMap.eval(key4, "three", setValueConsumer()), latches.get(1));
awaitNoEvent(woMap.eval(key4, removeConsumer()), latches.get(2));
K key5 = keySupplier.get();
awaitNoEvent(rwMap.eval(key5, "cuatro", setValueReturnPrevOrNull()), latches.get(0));
awaitNoEvent(rwMap.eval(key5, "four", setValueReturnPrevOrNull()), latches.get(1));
awaitNoEvent(rwMap.eval(key5, removeReturnPrevOrNull()), latches.get(2));
}
public void testLocalLambdaWriteListeners() throws Exception {
doLambdaWriteListeners(supplyIntKey(), wo(fmapL1), true);
}
@Test
public void testReplLambdaWriteListeners() throws Exception {
doLambdaWriteListeners(supplyKeyForCache(0, REPL), wo(fmapR1), true);
doLambdaWriteListeners(supplyKeyForCache(1, REPL), wo(fmapR2), true);
}
@Test
public void testDistLambdaWriteListeners() throws Exception {
doLambdaWriteListeners(supplyKeyForCache(0, DIST), wo(fmapD1), true);
doLambdaWriteListeners(supplyKeyForCache(0, DIST), wo(fmapD2), false);
}
private <K> void doLambdaWriteListeners(Supplier<K> keySupplier,
WriteOnlyMap<K, String> wo, boolean isOwner) throws Exception {
K key1 = keySupplier.get(), key2 = keySupplier.get();
List<CountDownLatch> latches = launderLatches(new ArrayList<>(), 1);
AutoCloseable onWrite = wo.listeners().onWrite(read -> {
assertEquals("write", read.get());
latches.get(0).countDown();
});
awaitEventIfOwnerAndLaunderLatch(isOwner, wo.eval(key1, new SetConstantOnWriteOnly("write")), latches);
awaitEventIfOwnerAndLaunderLatch(isOwner, wo.eval(key1, new SetConstantOnWriteOnly("write")), latches);
onWrite.close();
awaitNoEvent(wo.eval(key2, new SetConstantOnWriteOnly("write")), latches.get(0));
awaitNoEvent(wo.eval(key2, new SetConstantOnWriteOnly("write")), latches.get(0));
// TODO: Test other eval methods :)
AutoCloseable onWriteRemove = wo.listeners().onWrite(read -> {
assertFalse(read.find().isPresent());
latches.get(0).countDown();
});
awaitEventIfOwnerAndLaunderLatch(isOwner, wo.eval(key1, removeConsumer()), latches);
onWriteRemove.close();
awaitNoEvent(wo.eval(key2, removeConsumer()), latches.get(0));
}
// @Test
// public void testObjectReadWriteListeners() throws Exception {
// TrackingReadWriteListener<Integer, String> listener = new TrackingReadWriteListener<>();
// AutoCloseable closeable = readWriteMap.listeners().add(listener);
//
// awaitNoEvent(writeOnlyMap.eval(1, writeView -> writeView.set("created")), listener.latch);
// awaitNoEvent(writeOnlyMap.eval(1, writeView -> writeView.set("modified")), listener.latch);
// awaitNoEvent(writeOnlyMap.eval(1, WriteEntryView::remove), listener.latch);
//
// awaitEvent(readWriteMap.eval(2, rwView -> rwView.set("created")), listener.latch);
// awaitEvent(readWriteMap.eval(2, rwView -> rwView.set("modified")), listener.latch);
// awaitEvent(readWriteMap.eval(2, ReadWriteEntryView::remove), listener.latch);
//
// closeable.close();
// awaitNoEvent(writeOnlyMap.eval(3, writeView -> writeView.set("tres")), listener.latch);
// awaitNoEvent(writeOnlyMap.eval(3, writeView -> writeView.set("three")), listener.latch);
// awaitNoEvent(writeOnlyMap.eval(3, WriteEntryView::remove), listener.latch);
//
// awaitNoEvent(readWriteMap.eval(4, rwView -> rwView.set("cuatro")), listener.latch);
// awaitNoEvent(readWriteMap.eval(4, rwView -> rwView.set("four")), listener.latch);
// awaitNoEvent(readWriteMap.eval(4, ReadWriteEntryView::remove), listener.latch);
// }
//
// @Test
// public void testObjectWriteListeners() throws Exception {
// TrackingWriteListener<Integer, String> writeListener = new TrackingWriteListener<>();
// AutoCloseable writeListenerCloseable = writeOnlyMap.listeners().add(writeListener);
//
// awaitEvent(writeOnlyMap.eval(1, writeView -> writeView.set("write")), writeListener.latch);
// awaitEvent(writeOnlyMap.eval(1, writeView -> writeView.set("write")), writeListener.latch);
// writeListenerCloseable.close();
// awaitNoEvent(writeOnlyMap.eval(2, writeView -> writeView.set("write")), writeListener.latch);
// awaitNoEvent(writeOnlyMap.eval(2, writeView -> writeView.set("write")), writeListener.latch);
//
// TrackingRemoveOnWriteListener<Integer, String> writeRemoveListener = new TrackingRemoveOnWriteListener<>();
// AutoCloseable writeRemoveListenerCloseable = writeOnlyMap.listeners().add(writeRemoveListener);
//
// awaitEvent(writeOnlyMap.eval(1, WriteEntryView::remove), writeRemoveListener.latch);
// writeRemoveListenerCloseable.close();
// awaitNoEvent(writeOnlyMap.eval(2, WriteEntryView::remove), writeRemoveListener.latch);
// }
private static List<CountDownLatch> launderLatches(List<CountDownLatch> latches, int numLatches) {
latches.clear();
for (int i = 0; i < numLatches; i++)
latches.add(new CountDownLatch(1));
return latches;
}
public static <T> T awaitEvent(CompletableFuture<T> cf, CountDownLatch eventLatch) {
try {
T t = cf.get();
assertTrue(eventLatch.await(500, TimeUnit.MILLISECONDS));
return t;
} catch (InterruptedException | ExecutionException e) {
throw new Error(e);
}
}
public static <T> T awaitNoEvent(CompletableFuture<T> cf, CountDownLatch eventLatch) {
try {
T t = cf.get();
assertFalse(eventLatch.await(50, TimeUnit.MILLISECONDS));
return t;
} catch (InterruptedException | ExecutionException e) {
throw new Error(e);
}
}
public static <T> T awaitEventIfOwner(boolean isOwner, CompletableFuture<T> cf, CountDownLatch eventLatch) {
return isOwner ? awaitEvent(cf, eventLatch) : awaitNoEvent(cf, eventLatch);
}
public static <T> T awaitEventAndLaunderLatch(CompletableFuture<T> cf, List<CountDownLatch> latches) {
T t = awaitEvent(cf, latches.get(0));
launderLatches(latches, 1);
return t;
}
public static <T> T awaitEventIfOwnerAndLaunderLatch(boolean isOwner,
CompletableFuture<T> cf, List<CountDownLatch> latches) {
if (isOwner) {
T t = awaitEvent(cf, latches.get(0));
launderLatches(latches, 1);
return t;
}
return awaitNoEvent(cf, latches.get(0));
}
private static final class TrackingReadWriteListener<K, V> implements ReadWriteListener<K, V> {
CountDownLatch latch = new CountDownLatch(1);
@Override
public void onCreate(ReadEntryView<K, V> created) {
assertEquals("created", created.get());
latchCountAndLaunder();
}
@Override
public void onModify(ReadEntryView<K, V> before, ReadEntryView<K, V> after) {
assertEquals("created", before.get());
assertEquals("modified", after.get());
latchCountAndLaunder();
}
@Override
public void onRemove(ReadEntryView<K, V> removed) {
assertEquals("modified", removed.get());
latchCountAndLaunder();
}
private void latchCountAndLaunder() {
latch.countDown();
latch = new CountDownLatch(1);
}
}
public static final class TrackingWriteListener<K, V> implements WriteListener<K, V> {
CountDownLatch latch = new CountDownLatch(1);
@Override
public void onWrite(ReadEntryView<K, V> write) {
assertEquals("write", write.get());
latchCountAndLaunder();
}
private void latchCountAndLaunder() {
latch.countDown();
latch = new CountDownLatch(1);
}
}
public static final class TrackingRemoveOnWriteListener<K, V> implements WriteListener<K, V> {
CountDownLatch latch = new CountDownLatch(1);
@Override
public void onWrite(ReadEntryView<K, V> write) {
assertFalse(write.find().isPresent());
latchCountAndLaunder();
}
private void latchCountAndLaunder() {
latch.countDown();
latch = new CountDownLatch(1);
}
}
}
| 12,836
| 41.79
| 115
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/AbstractFunctionalTest.java
|
package org.infinispan.functional;
import org.infinispan.AdvancedCache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
abstract class AbstractFunctionalTest extends MultipleCacheManagersTest {
static final String DIST = "dist";
static final String REPL = "repl";
// Create local caches as default in a cluster of 2
int numNodes = 2;
int numDistOwners = 1;
boolean isSync = true;
boolean persistence = true;
boolean passivation = false;
FunctionalMapImpl<Integer, String> fmapL1;
FunctionalMapImpl<Integer, String> fmapL2;
FunctionalMapImpl<Object, String> fmapD1;
FunctionalMapImpl<Object, String> fmapD2;
// TODO: we should not create all those maps in tests where we don't use them
FunctionalMapImpl<Object, String> fmapR1;
FunctionalMapImpl<Object, String> fmapR2;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder localBuilder = new ConfigurationBuilder();
configureCache(localBuilder);
createClusteredCaches(numNodes, TestDataSCI.INSTANCE, localBuilder);
// Create distributed caches
ConfigurationBuilder distBuilder = new ConfigurationBuilder();
distBuilder.clustering().cacheMode(isSync ? CacheMode.DIST_SYNC : CacheMode.DIST_ASYNC).hash().numOwners(numDistOwners);
configureCache(distBuilder);
cacheManagers.stream().forEach(cm -> cm.defineConfiguration(DIST, distBuilder.build()));
// Create replicated caches
ConfigurationBuilder replBuilder = new ConfigurationBuilder();
replBuilder.clustering().cacheMode(isSync ? CacheMode.REPL_SYNC : CacheMode.REPL_ASYNC);
configureCache(replBuilder);
cacheManagers.stream().forEach(cm -> cm.defineConfiguration(REPL, replBuilder.build()));
// Wait for cluster to form
waitForClusterToForm(DIST, REPL);
}
protected void configureCache(ConfigurationBuilder builder) {
builder.statistics().available(false);
if (transactional != null) {
builder.transaction().transactionMode(transactionMode());
if (lockingMode != null) {
builder.transaction().lockingMode(lockingMode);
}
}
if (isolationLevel != null) {
builder.locking().isolationLevel(isolationLevel);
}
if (persistence) {
builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class);
builder.persistence().passivation(passivation);
}
}
protected AbstractFunctionalTest persistence(boolean enabled) {
persistence = enabled;
return this;
}
protected AbstractFunctionalTest passivation(boolean enabled) {
passivation = enabled;
return this;
}
@Override
@BeforeClass(alwaysRun = true)
public void createBeforeClass() throws Throwable {
super.createBeforeClass();
if (cleanupAfterTest()) initMaps();
}
@Override
@BeforeMethod(alwaysRun = true)
public void createBeforeMethod() throws Throwable {
super.createBeforeMethod();
if (cleanupAfterMethod()) initMaps();
}
protected void initMaps() {
fmapL1 = FunctionalMapImpl.create(getAdvancedCache(cacheManagers.get(0), null));
fmapL2 = FunctionalMapImpl.create(getAdvancedCache(cacheManagers.get(0), null));
fmapD1 = FunctionalMapImpl.create(getAdvancedCache(cacheManagers.get(0), DIST));
fmapD2 = FunctionalMapImpl.create(getAdvancedCache(cacheManagers.get(1), DIST));
fmapR1 = FunctionalMapImpl.create(getAdvancedCache(cacheManagers.get(0), REPL));
fmapR2 = FunctionalMapImpl.create(getAdvancedCache(cacheManagers.get(1), REPL));
}
protected <K, V> AdvancedCache<K, V> getAdvancedCache(EmbeddedCacheManager cm, String cacheName) {
return (AdvancedCache<K, V>) (cacheName == null ? cm.getCache() : cm.getCache(cacheName));
}
}
| 4,274
| 37.513514
| 126
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalSimpleTutorialTest.java
|
package org.infinispan.functional;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.infinispan.AdvancedCache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.functional.FunctionalMap.ReadOnlyMap;
import org.infinispan.functional.FunctionalMap.ReadWriteMap;
import org.infinispan.functional.FunctionalMap.WriteOnlyMap;
import org.infinispan.functional.MetaParam.MetaLifespan;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadOnlyMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.functional.impl.WriteOnlyMapImpl;
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 = "functional.FunctionalSimpleTutorialTest")
public class FunctionalSimpleTutorialTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder());
}
public void testSimpleTutorial() throws Exception {
AdvancedCache<String, String> cache = cacheManager.<String, String>getCache().getAdvancedCache();
FunctionalMapImpl<String, String> functionalMap = FunctionalMapImpl.create(cache);
WriteOnlyMap<String, String> writeOnlyMap = WriteOnlyMapImpl.create(functionalMap);
ReadOnlyMap<String, String> readOnlyMap = ReadOnlyMapImpl.create(functionalMap);
// Execute two parallel write-only operation to store key/value pairs
CompletableFuture<Void> writeFuture1 = writeOnlyMap.eval("key1", "value1",
(v, writeView) -> writeView.set(v));
CompletableFuture<Void> writeFuture2 = writeOnlyMap.eval("key2", "value2",
(v, writeView) -> writeView.set(v));
// When each write-only operation completes, execute a read-only operation to retrieve the value
CompletableFuture<String> readFuture1 =
writeFuture1.thenCompose(r -> readOnlyMap.eval("key1", ReadEntryView::get));
CompletableFuture<String> readFuture2 =
writeFuture2.thenCompose(r -> readOnlyMap.eval("key2", ReadEntryView::get));
// When the read-only operation completes, print it out
printf("Created entries: %n");
CompletableFuture<Void> end = readFuture1.thenAcceptBoth(readFuture2, (v1, v2) ->
printf("key1 = %s%nkey2 = %s%n", v1, v2));
// Wait for this read/write combination to finish
end.get();
// Create a read-write map
ReadWriteMap<String, String> readWriteMap = ReadWriteMapImpl.create(functionalMap);
// Use read-write multi-key based operation to write new values
// together with lifespan and return previous values
Map<String, String> data = new HashMap<>();
data.put("key1", "newValue1");
data.put("key2", "newValue2");
Traversable<String> previousValues = readWriteMap.evalMany(data, (v, readWriteView) -> {
String prev = readWriteView.find().orElse(null);
readWriteView.set(v, new MetaLifespan(Duration.ofHours(1).toMillis()));
return prev;
});
// Use read-only multi-key operation to read current values for multiple keys
Traversable<ReadEntryView<String, String>> entryViews =
readOnlyMap.evalMany(data.keySet(), readOnlyView -> readOnlyView);
printf("Updated entries: %n");
entryViews.forEach(view -> printf("%s%n", view));
// Finally, print out the previous entry values
printf("Previous entry values: %n");
previousValues.forEach(prev -> printf("%s%n", prev));
}
private void printf(String format, Object ... args) {
log.infof(format, args);
}
}
| 3,975
| 44.181818
| 103
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalMapEventsTest.java
|
package org.infinispan.functional;
import static org.infinispan.functional.FunctionalListenerAssertions.TestEvent;
import static org.infinispan.functional.FunctionalListenerAssertions.assertNoEvents;
import static org.infinispan.functional.FunctionalListenerAssertions.assertOrderedEvents;
import static org.infinispan.functional.FunctionalListenerAssertions.assertUnorderedEvents;
import static org.infinispan.functional.FunctionalListenerAssertions.create;
import static org.infinispan.functional.FunctionalListenerAssertions.createModify;
import static org.infinispan.functional.FunctionalListenerAssertions.write;
import static org.infinispan.functional.FunctionalListenerAssertions.writeModify;
import static org.infinispan.functional.FunctionalListenerAssertions.writeRemove;
import static org.infinispan.functional.FunctionalTestUtils.rw;
import static org.infinispan.functional.FunctionalTestUtils.wo;
import java.util.Arrays;
import java.util.Collection;
import org.infinispan.functional.decorators.FunctionalListeners;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "functional.FunctionalMapEventsTest")
public class FunctionalMapEventsTest extends FunctionalMapTest {
LocalFunctionalListeners<Integer> localL2;
LocalFunctionalListeners<Object> replL2;
LocalFunctionalListeners<Object> distL2;
@BeforeClass
@Override
public void createBeforeClass() throws Throwable {
super.createBeforeClass();
localL2 = new LocalFunctionalListeners<>(fmapL2);
replL2 = new LocalFunctionalListeners<>(fmapR2);
distL2 = new LocalFunctionalListeners<>(fmapD2);
}
@Override
public void testLocalWriteConstantAndReadGetsValue() {
assertOrderedEvents(localL2, super::testLocalWriteConstantAndReadGetsValue, write("one"));
}
@Override
public void testReplWriteConstantAndReadGetsValueOnNonOwner() {
assertOrderedEvents(replL2, super::testReplWriteConstantAndReadGetsValueOnNonOwner, write("one"));
}
@Override
public void testReplWriteConstantAndReadGetsValueOnOwner() {
assertOrderedEvents(replL2, super::testReplWriteConstantAndReadGetsValueOnOwner, write("one"));
}
@Override
public void testDistWriteConstantAndReadGetsValueOnNonOwner() {
assertNoEvents(distL2, super::testDistWriteConstantAndReadGetsValueOnNonOwner);
}
@Override
public void testDistWriteConstantAndReadGetsValueOnOwner() {
assertOrderedEvents(distL2, super::testDistWriteConstantAndReadGetsValueOnOwner, write("one"));
}
@Override
public void testLocalWriteValueAndReadValueAndMetadata() {
assertOrderedEvents(localL2, super::testLocalWriteValueAndReadValueAndMetadata, write("one"));
}
@Override
public void testReplWriteValueAndReadValueAndMetadataOnNonOwner() {
assertOrderedEvents(replL2, super::testReplWriteValueAndReadValueAndMetadataOnNonOwner, write("one"));
}
@Override
public void testReplWriteValueAndReadValueAndMetadataOnOwner() {
assertOrderedEvents(replL2, super::testReplWriteValueAndReadValueAndMetadataOnOwner, write("one"));
}
@Override
public void testDistWriteValueAndReadValueAndMetadataOnNonOwner() {
assertNoEvents(distL2, super::testDistWriteValueAndReadValueAndMetadataOnNonOwner);
}
@Override
public void testDistWriteValueAndReadValueAndMetadataOnOwner() {
assertOrderedEvents(distL2, super::testDistWriteValueAndReadValueAndMetadataOnOwner, write("one"));
}
@Override
public void testLocalReadWriteGetsEmpty() {
assertNoEvents(localL2, super::testLocalReadWriteGetsEmpty);
}
@Override
public void testReplReadWriteGetsEmptyOnNonOwner() {
assertNoEvents(replL2, super::testReplReadWriteGetsEmptyOnNonOwner);
}
@Override
public void testReplReadWriteGetsEmptyOnOwner() {
assertNoEvents(replL2, super::testReplReadWriteGetsEmptyOnOwner);
}
@Override
public void testDistReadWriteGetsEmptyOnNonOwner() {
assertNoEvents(distL2, super::testDistReadWriteGetsEmptyOnNonOwner);
}
@Override
public void testDistReadWriteGetsEmptyOnOwner() {
assertNoEvents(distL2, super::testDistReadWriteGetsEmptyOnOwner);
}
@Override
public void testLocalReadWriteValuesReturnPrevious() {
assertOrderedEvents(localL2, super::testLocalReadWriteValuesReturnPrevious, create("one"));
}
@Override
public void testReplReadWriteValuesReturnPreviousOnNonOwner() {
assertOrderedEvents(replL2, super::testReplReadWriteValuesReturnPreviousOnNonOwner, create("one"));
}
@Override
public void testReplReadWriteValuesReturnPreviousOnOwner() {
assertOrderedEvents(replL2, super::testReplReadWriteValuesReturnPreviousOnOwner, create("one"));
}
@Override
public void testDistReadWriteValuesReturnPreviousOnNonOwner() {
assertNoEvents(distL2, super::testDistReadWriteValuesReturnPreviousOnNonOwner);
}
@Override
public void testDistReadWriteValuesReturnPreviousOnOwner() {
assertOrderedEvents(distL2, super::testDistReadWriteValuesReturnPreviousOnOwner, create("one"));
}
@Override
public void testLocalReadWriteForConditionalParamBasedReplace() {
Collection<TestEvent<String>> events = createUpdateCreate();
assertOrderedEvents(localL2, super::testLocalReadWriteForConditionalParamBasedReplace, events);
}
@Override
public void testReplReadWriteForConditionalParamBasedReplaceOnNonOwner() {
assertOrderedEvents(replL2, super::testReplReadWriteForConditionalParamBasedReplaceOnNonOwner, createUpdateCreate());
}
@Override
public void testReplReadWriteForConditionalParamBasedReplaceOnOwner() {
assertOrderedEvents(replL2, super::testReplReadWriteForConditionalParamBasedReplaceOnOwner, createUpdateCreate());
}
@Override
public void testDistReadWriteForConditionalParamBasedReplaceOnNonOwner() {
assertNoEvents(distL2, super::testDistReadWriteForConditionalParamBasedReplaceOnNonOwner);
}
@Override
public void testDistReadWriteForConditionalParamBasedReplaceOnOwner() {
assertOrderedEvents(distL2, super::testDistReadWriteForConditionalParamBasedReplaceOnOwner, createUpdateCreate());
}
@Override
public void testLocalReadOnlyEvalManyEmpty() {
assertNoEvents(localL2, super::testLocalReadOnlyEvalManyEmpty);
}
@Override
public void testReplReadOnlyEvalManyEmptyOnNonOwner() {
assertNoEvents(replL2, super::testReplReadOnlyEvalManyEmptyOnNonOwner);
}
@Override
public void testReplReadOnlyEvalManyEmptyOnOwner() {
assertNoEvents(replL2, super::testReplReadOnlyEvalManyEmptyOnOwner);
}
@Override
public void testDistReadOnlyEvalManyEmptyOnNonOwner() {
assertNoEvents(distL2, super::testDistReadOnlyEvalManyEmptyOnNonOwner);
}
@Override
public void testDistReadOnlyEvalManyEmptyOnOwner() {
assertNoEvents(distL2, super::testDistReadOnlyEvalManyEmptyOnOwner);
}
@Override
public void testLocalUpdateSubsetAndReturnPrevs() {
assertUnorderedEvents(localL2, super::testLocalUpdateSubsetAndReturnPrevs,
writeModify(Arrays.asList("one", "two", "three"), Arrays.asList("bat", "bi", "hiru")));
}
@Override
public void testReplUpdateSubsetAndReturnPrevsOnNonOwner() {
assertUnorderedEvents(replL2, super::testReplUpdateSubsetAndReturnPrevsOnNonOwner,
writeModify(Arrays.asList("one", "two", "three"), Arrays.asList("bat", "bi", "hiru")));
}
@Override
public void testReplUpdateSubsetAndReturnPrevsOnOwner() {
assertUnorderedEvents(replL2, super::testReplUpdateSubsetAndReturnPrevsOnOwner,
writeModify(Arrays.asList("one", "two", "three"), Arrays.asList("bat", "bi", "hiru")));
}
@Override
public void testDistUpdateSubsetAndReturnPrevsOnNonOwner() {
assertNoEvents(distL2, super::testDistUpdateSubsetAndReturnPrevsOnNonOwner);
}
@Override
public void testDistUpdateSubsetAndReturnPrevsOnOwner() {
assertUnorderedEvents(distL2, super::testDistUpdateSubsetAndReturnPrevsOnOwner,
writeModify(Arrays.asList("one", "two", "three"), Arrays.asList("bat", "bi", "hiru")));
}
@Override
public void testLocalReadWriteToRemoveAllAndReturnPrevs() {
assertUnorderedEvents(localL2, super::testLocalReadWriteToRemoveAllAndReturnPrevs,
writeRemove("one", "two", "three"));
}
@Override
public void testReplReadWriteToRemoveAllAndReturnPrevsOnNonOwner() {
assertUnorderedEvents(replL2, super::testReplReadWriteToRemoveAllAndReturnPrevsOnNonOwner,
writeRemove("one", "two", "three"));
}
@Override
public void testReplReadWriteToRemoveAllAndReturnPrevsOnOwner() {
assertUnorderedEvents(replL2, super::testReplReadWriteToRemoveAllAndReturnPrevsOnOwner,
writeRemove("one", "two", "three"));
}
@Override
public void testDistReadWriteToRemoveAllAndReturnPrevsOnNonOwner() {
assertNoEvents(distL2, super::testDistReadWriteToRemoveAllAndReturnPrevsOnNonOwner);
}
@Override
public void testDistReadWriteToRemoveAllAndReturnPrevsOnOwner() {
assertUnorderedEvents(distL2, super::testDistReadWriteToRemoveAllAndReturnPrevsOnOwner,
writeRemove("one", "two", "three"));
}
static Collection<TestEvent<String>> createUpdateCreate() {
Collection<TestEvent<String>> events = createModify("one", "uno");
events.addAll(create("one"));
return events;
}
private static final class LocalFunctionalListeners<K> implements FunctionalListeners<K, String> {
private final FunctionalMapImpl<K, String> fmap;
private LocalFunctionalListeners(FunctionalMapImpl<K, String> fmap) {
this.fmap = fmap;
}
@Override
public Listeners.ReadWriteListeners<K, String> readWriteListeners() {
return rw(fmap).listeners();
}
@Override
public Listeners.WriteListeners<K, String> writeOnlyListeners() {
return wo(fmap).listeners();
}
}
}
| 10,127
| 36.098901
| 123
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalStorageTypeTest.java
|
package org.infinispan.functional;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "functional.FunctionalStorageTypeTest")
public class FunctionalStorageTypeTest extends FunctionalMapTest {
@Override
protected void configureCache(ConfigurationBuilder builder) {
builder.memory().storageType(storageType);
super.configureCache(builder);
}
public Object[] factory() {
return new Object[]{
new FunctionalStorageTypeTest().storageType(StorageType.OFF_HEAP),
new FunctionalStorageTypeTest().storageType(StorageType.BINARY),
new FunctionalStorageTypeTest().storageType(StorageType.OBJECT),
};
}
}
| 816
| 34.521739
| 79
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/AbstractFunctionalOpTest.java
|
package org.infinispan.functional;
import static org.infinispan.commons.test.Exceptions.expectExceptionNonStrict;
import static org.testng.Assert.assertEquals;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.functional.TxReadOnlyKeyCommand;
import org.infinispan.commands.functional.TxReadOnlyManyCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.context.InvocationContext;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.functional.EntryView.WriteEntryView;
import org.infinispan.functional.FunctionalMap.ReadWriteMap;
import org.infinispan.functional.FunctionalMap.WriteOnlyMap;
import org.infinispan.functional.impl.ReadOnlyMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.functional.impl.WriteOnlyMapImpl;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.interceptors.impl.CallInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.CountingRequestRepository;
import org.infinispan.util.function.SerializableBiConsumer;
import org.infinispan.util.function.SerializableFunction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* @author Radim Vansa <rvansa@redhat.com> and Krzysztof Sobolewski <Krzysztof.Sobolewski@atende.pl>
*/
@Test(groups = "functional", testName = "functional.AbstractFunctionalOpTest")
public abstract class AbstractFunctionalOpTest extends AbstractFunctionalTest {
static ConcurrentMap<Class<? extends AbstractFunctionalOpTest>, AtomicInteger> invocationCounts = new ConcurrentHashMap<>();
FunctionalMap.ReadOnlyMap<Object, String> ro;
FunctionalMap.ReadOnlyMap<Integer, String> lro;
WriteOnlyMap<Object, String> wo;
ReadWriteMap<Object, String> rw;
AdvancedCache<Object, String> cache;
WriteOnlyMap<Integer, String> lwo;
ReadWriteMap<Integer, String> lrw;
List<CountingRequestRepository> countingRequestRepositories;
public AbstractFunctionalOpTest() {
numNodes = 4;
numDistOwners = 2;
}
@DataProvider(name = "writeMethods")
public static Object[][] writeMethods() {
return Stream.of(WriteMethod.values()).map(m -> new Object[]{m}).toArray(Object[][]::new);
}
@DataProvider(name = "owningModeAndWriteMethod")
public static Object[][] owningModeAndWriteMethod() {
return Stream.of(Boolean.TRUE, Boolean.FALSE)
.flatMap(isSourceOwner -> Stream.of(WriteMethod.values())
.map(method -> new Object[]{isSourceOwner, method}))
.toArray(Object[][]::new);
}
@DataProvider(name = "readMethods")
public static Object[][] methods() {
return Stream.of(ReadMethod.values()).map(m -> new Object[] { m }).toArray(Object[][]::new);
}
@DataProvider(name = "owningModeAndReadMethod")
public static Object[][] owningModeAndMethod() {
return Stream.of(Boolean.TRUE, Boolean.FALSE)
.flatMap(isSourceOwner -> Stream.of(ReadMethod.values())
.map(method -> new Object[] { isSourceOwner, method }))
.toArray(Object[][]::new);
}
@DataProvider(name = "owningModeAndReadWrites")
public static Object[][] owningModeAndReadWrites() {
return Stream.of(Boolean.TRUE, Boolean.FALSE)
.flatMap(isSourceOwner -> Stream.of(WriteMethod.values()).filter(m -> m.doesRead)
.map(method -> new Object[]{isSourceOwner, method}))
.toArray(Object[][]::new);
}
static Address getAddress(Cache<Object, Object> cache) {
return cache.getAdvancedCache().getRpcManager().getAddress();
}
@BeforeMethod
public void resetInvocationCount() {
AtomicInteger counter = invocationCounts.get(getClass());
if (counter != null) counter.set(0);
}
@Override
protected void initMaps() {
super.initMaps();
this.ro = ReadOnlyMapImpl.create(fmapD1);
this.lro = ReadOnlyMapImpl.create(fmapL1);
this.wo = WriteOnlyMapImpl.create(fmapD1);
this.rw = ReadWriteMapImpl.create(fmapD1);
this.cache = cacheManagers.get(0).<Object, String>getCache(DIST).getAdvancedCache();
this.lwo = WriteOnlyMapImpl.create(fmapL1);
this.lrw = ReadWriteMapImpl.create(fmapL1);
}
@Override
protected void createCacheManagers() throws Throwable {
super.createCacheManagers();
countingRequestRepositories = cacheManagers.stream()
.map(CountingRequestRepository::replaceDispatcher)
.collect(Collectors.toList());
for (EmbeddedCacheManager manager : managers()) {
for (String cacheName : manager.getCacheNames()) {
TestingUtil.extractInterceptorChain(manager.getCache(cacheName))
.addInterceptorBefore(new CommandCachingInterceptor(), CallInterceptor.class);
}
}
}
protected void advanceGenerationsAndAwait(long timeout, TimeUnit timeUnit) throws Exception {
long now = System.currentTimeMillis();
long deadline = now + timeUnit.toMillis(timeout);
for (CountingRequestRepository card : countingRequestRepositories) {
card.advanceGenerationAndAwait(deadline - now, TimeUnit.MILLISECONDS);
now = System.currentTimeMillis();
}
}
protected Object getKey(boolean isOwner, String cacheName) {
Object key;
if (isOwner) {
// this is simple: find a key that is local to the originating node
key = getKeyForCache(0, cacheName);
} else {
// this is more complicated: we need a key that is *not* local to the originating node
key = IntStream.iterate(0, i -> i + 1)
.mapToObj(i -> "key" + i)
.filter(k -> !advancedCache(0, cacheName).getDistributionManager().getCacheTopology().isReadOwner(k))
.findAny()
.get();
}
return key;
}
protected void assertInvocations(int expected) {
AtomicInteger counter = invocationCounts.get(getClass());
assertEquals(counter == null ? 0 : counter.get(), expected);
}
// we don't want to increment the invocation count if it's the non-modifying invocation during transactional read-writes
private static boolean isModifying() {
VisitableCommand current = CommandCachingInterceptor.getCurrent();
return !(current instanceof TxReadOnlyKeyCommand || current instanceof TxReadOnlyManyCommand);
}
private static void incrementInvocationCount(Class<? extends AbstractFunctionalOpTest> clazz) {
invocationCounts.computeIfAbsent(clazz, k -> new AtomicInteger()).incrementAndGet();
}
protected <K> void testReadOnMissingValue(K key, FunctionalMap.ReadOnlyMap<K, String> ro, ReadMethod method) {
assertEquals(ro.eval(key, view -> view.find().isPresent()).join(), Boolean.FALSE);
expectExceptionNonStrict(CompletionException.class, CacheException.class, NoSuchElementException.class, () ->
method.eval(key, ro, view -> view.get())
);
}
enum WriteMethod {
WO_EVAL(false, (key, wo, rw, read, write, clazz) ->
wo.eval(key, view -> {
if (isModifying()) {
incrementInvocationCount(clazz);
}
write.accept(view, null);
}).join(), false),
WO_EVAL_VALUE(false, (key, wo, rw, read, write, clazz) ->
wo.eval(key, null, (v, view) -> {
if (isModifying()) {
incrementInvocationCount(clazz);
}
write.accept(view, null);
}).join(), false),
WO_EVAL_MANY(false, (key, wo, rw, read, write, clazz) ->
wo.evalMany(Collections.singleton(key), view -> {
if (isModifying()) {
incrementInvocationCount(clazz);
}
write.accept(view, null);
}).join(), true),
WO_EVAL_MANY_ENTRIES(false, (key, wo, rw, read, write, clazz) ->
wo.evalMany(Collections.singletonMap(key, null), (v, view) -> {
if (isModifying()) {
incrementInvocationCount(clazz);
}
write.accept(view, null);
}).join(), true),
RW_EVAL(true, (key, wo, rw, read, write, clazz) ->
rw.eval(key, view -> {
if (isModifying()) {
incrementInvocationCount(clazz);
}
Object ret = read.apply(view);
write.accept(view, ret);
return ret;
}).join(), false),
RW_EVAL_VALUE(true, (key, wo, rw, read, write, clazz) ->
rw.eval(key, null, (v, view) -> {
if (isModifying()) {
incrementInvocationCount(clazz);
}
Object ret = read.apply(view);
write.accept(view, ret);
return ret;
}).join(), false),
RW_EVAL_MANY(true, (key, wo, rw, read, write, clazz) ->
rw.evalMany(Collections.singleton(key), view -> {
if (isModifying()) {
incrementInvocationCount(clazz);
}
Object ret = read.apply(view);
write.accept(view, ret);
return ret;
}).filter(Objects::nonNull).findAny().orElse(null), true),
RW_EVAL_MANY_ENTRIES(true, (key, wo, rw, read, write, clazz) ->
rw.evalMany(Collections.singletonMap(key, null), (v, view) -> {
if (isModifying()) {
incrementInvocationCount(clazz);
}
Object ret = read.apply(view);
write.accept(view, ret);
return ret;
}).filter(Objects::nonNull).findAny().orElse(null), true),;
private final Performer action;
final boolean doesRead;
final boolean isMany;
<K, R> WriteMethod(boolean doesRead, Performer<K, R> action, boolean isMany) {
this.doesRead = doesRead;
this.action = action;
this.isMany = isMany;
}
public <K, R> R eval(K key,
WriteOnlyMap<K, String> wo, ReadWriteMap<K, String> rw,
SerializableFunction<ReadEntryView<K, String>, R> read,
SerializableBiConsumer<WriteEntryView<K, String>, R> write,
Class<? extends AbstractFunctionalOpTest> clazz) {
return ((Performer<K, R>) action).eval(key, wo, rw, read, write, clazz);
}
public <K, R> R eval(K key,
WriteOnlyMap<K, String> wo, ReadWriteMap<K, String> rw,
Function<ReadEntryView<K, String>, R> read,
SerializableBiConsumer<WriteEntryView<K, String>, R> write,
Class<? extends AbstractFunctionalOpTest> clazz) {
return ((Performer<K, R>) action).eval(key, wo, rw, read, write, clazz);
}
@FunctionalInterface
private interface Performer<K, R> {
R eval(K key,
WriteOnlyMap<K, String> wo, ReadWriteMap<K, String> rw,
Function<ReadEntryView<K, String>, R> read,
BiConsumer<WriteEntryView<K, String>, R> write,
Class<? extends AbstractFunctionalOpTest> clazz);
}
}
enum ReadMethod {
RO_EVAL((key, ro, read) -> ro.eval(key, read).join()),
RO_EVAL_MANY((key, ro, read) -> ro.evalMany(Collections.singleton(key), read).filter(Objects::nonNull).findAny().orElse(null)),
;
private final Performer action;
ReadMethod(Performer action) {
this.action = action;
}
public <K, R> R eval(K key, FunctionalMap.ReadOnlyMap<K, String> ro,
SerializableFunction<ReadEntryView<K, String>, R> read) {
return ((Performer<K, R>) action).eval(key, ro, read);
}
public <K, R> R eval(K key, FunctionalMap.ReadOnlyMap<K, String> ro,
Function<ReadEntryView<K, String>, R> read) {
return ((Performer<K, R>) action).eval(key, ro, read);
}
@FunctionalInterface
private interface Performer<K, R> {
R eval(K key,
FunctionalMap.ReadOnlyMap<K, String> ro,
Function<ReadEntryView<K, String>, R> read);
}
}
protected static class CommandCachingInterceptor extends BaseCustomAsyncInterceptor {
private static final ThreadLocal<VisitableCommand> current = new ThreadLocal<>();
public static VisitableCommand getCurrent() {
return current.get();
}
@Override
protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
current.set(command);
return invokeNextAndFinally(ctx, command, (rCtx, rCommand, rv, t) -> current.remove());
}
}
}
| 13,943
| 41.126888
| 133
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalTestUtils.java
|
package org.infinispan.functional;
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.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.functional.EntryView.ReadWriteEntryView;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadOnlyMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.functional.impl.WriteOnlyMapImpl;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.CompletionStages;
public final class FunctionalTestUtils {
public static final int MAX_WAIT_SECS = 30;
private static final Random R = new Random();
public static <K> FunctionalMap.ReadOnlyMap<K, String> ro(FunctionalMapImpl<K, String> fmap) {
return ReadOnlyMapImpl.create(fmap);
}
public static <K> FunctionalMap.WriteOnlyMap<K, String> wo(FunctionalMapImpl<K, String> fmap) {
return WriteOnlyMapImpl.create(fmap);
}
public static <K> FunctionalMap.ReadWriteMap<K, String> rw(FunctionalMapImpl<K, String> fmap) {
return ReadWriteMapImpl.create(fmap);
}
public static <K, V> FunctionalMap.ReadOnlyMap<K, V> ro(AdvancedCache<K, V> cache) {
FunctionalMapImpl<K, V> impl = FunctionalMapImpl.create(cache);
return ReadOnlyMapImpl.create(impl);
}
public static <K, V> FunctionalMap.ReadWriteMap<K, V> rw(Cache<K, V> cache) {
FunctionalMapImpl<K, V> impl = FunctionalMapImpl.create(cache.getAdvancedCache());
return ReadWriteMapImpl.create(impl);
}
public static <K, V> FunctionalMap.WriteOnlyMap<K, V> wo(Cache<K, V> cache) {
FunctionalMapImpl<K, V> impl = FunctionalMapImpl.create(cache.getAdvancedCache());
return WriteOnlyMapImpl.create(impl);
}
static Supplier<Integer> supplyIntKey() {
return () -> R.nextInt(Integer.MAX_VALUE);
}
public static <T> T await(CompletableFuture<T> cf) {
return CompletionStages.join(cf);
}
public static <T> T await(CompletionStage<T> cf) {
try {
return cf.toCompletableFuture().get(MAX_WAIT_SECS, TimeUnit.SECONDS);
} catch (TimeoutException | InterruptedException | ExecutionException e) {
throw new Error(e);
}
}
public static <T> List<T> await(List<CompletableFuture<T>> cf) {
return await(CompletableFutures.sequence(cf));
}
public static <K> void assertReadOnlyViewEmpty(K k, ReadEntryView<K, ?> ro) {
assertEquals(k, ro.key());
assertFalse(ro.find().isPresent());
}
public static <K, V> void assertReadOnlyViewEquals(K k, V expected, ReadEntryView<K, V> ro) {
assertEquals(k, ro.key());
assertTrue(ro.find().isPresent());
assertEquals(expected, ro.find().get());
assertEquals(expected, ro.get());
}
public static <K> void assertReadWriteViewEmpty(K k, ReadWriteEntryView<K, ?> rw) {
assertEquals(k, rw.key());
assertFalse(rw.find().isPresent());
}
public static <K, V> void assertReadWriteViewEquals(K k, V expected, ReadWriteEntryView<K, V> rw) {
assertEquals(k, rw.key());
assertTrue(rw.find().isPresent());
assertEquals(expected, rw.find().get());
assertEquals(expected, rw.get());
try {
rw.set(null);
fail("Expected IllegalStateException since entry view cannot be modified outside lambda");
} catch (IllegalStateException e) {
// Expected
}
}
private FunctionalTestUtils() {
// Do not instantiate
}
}
| 4,042
| 34.464912
| 102
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalConcurrentMapTest.java
|
package org.infinispan.functional;
import static org.infinispan.functional.FunctionalTestUtils.supplyIntKey;
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.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Supplier;
import org.infinispan.functional.decorators.FunctionalConcurrentMap;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Test suite for verifying that the concurrent map implementation
* based on functional map behaves in the correct way.
*/
@Test(groups = "functional", testName = "functional.FunctionalConcurrentMapTest")
public class FunctionalConcurrentMapTest extends AbstractFunctionalTest {
ConcurrentMap<Integer, String> local1;
ConcurrentMap<Integer, String> local2;
ConcurrentMap<Object, String> dist1;
ConcurrentMap<Object, String> dist2;
ConcurrentMap<Object, String> repl1;
ConcurrentMap<Object, String> repl2;
@BeforeClass
@Override
public void createBeforeClass() throws Throwable {
super.createBeforeClass();
local1 = FunctionalConcurrentMap.create(cacheManagers.get(0).<Integer, String>getCache().getAdvancedCache());
local2 = FunctionalConcurrentMap.create(cacheManagers.get(0).<Integer, String>getCache().getAdvancedCache());
dist1 = FunctionalConcurrentMap.create(cacheManagers.get(0).<Object, String>getCache(DIST).getAdvancedCache());
dist2 = FunctionalConcurrentMap.create(cacheManagers.get(1).<Object, String>getCache(DIST).getAdvancedCache());
repl1 = FunctionalConcurrentMap.create(cacheManagers.get(0).<Object, String>getCache(REPL).getAdvancedCache());
repl2 = FunctionalConcurrentMap.create(cacheManagers.get(1).<Object, String>getCache(REPL).getAdvancedCache());
}
public void testLocalEmptyGetThenPut() {
doEmptyGetThenPut(supplyIntKey(), local1, local2);
}
public void testReplEmptyGetThenPutOnNonOwner() {
doEmptyGetThenPut(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplEmptyGetThenPutOnOwner() {
doEmptyGetThenPut(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistEmptyGetThenPutOnNonOwner() {
doEmptyGetThenPut(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistEmptyGetThenPutOnOwner() {
doEmptyGetThenPut(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doEmptyGetThenPut(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key = keySupplier.get();
assertEquals(null, readMap.get(key));
assertEquals(null, writeMap.put(key, "one"));
assertEquals("one", readMap.get(key));
}
public void testLocalPutGet() {
doPutGet(supplyIntKey(), local1, local2);
}
public void testReplPutGetOnNonOwner() {
doPutGet(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testReplPutGetOnOwner() {
doPutGet(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testDistPutGetOnNonOwner() {
doPutGet(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistPutGetOnOwner() {
doPutGet(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doPutGet(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key = keySupplier.get();
assertEquals(null, writeMap.put(key, "one"));
assertEquals("one", readMap.get(key));
}
public void testLocalPutUpdate() {
doPutUpdate(supplyIntKey(), local1, local2);
}
public void testReplPutUpdateOnNonOwner() {
doPutUpdate(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplPutUpdateOnOwner() {
doPutUpdate(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testDistPutUpdateOnNonOwner() {
doPutUpdate(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistPutUpdateOnOwner() {
doPutUpdate(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doPutUpdate(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key = keySupplier.get();
assertEquals(null, writeMap.put(key, "one"));
assertEquals("one", writeMap.put(key, "uno"));
assertEquals("uno", readMap.get(key));
}
public void testLocalGetAndRemove() {
doGetAndRemove(supplyIntKey(), local1, local2);
}
public void testReplGetAndRemoveOnNonOwner() {
doGetAndRemove(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplGetAndRemoveOnOwner() {
doGetAndRemove(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistGetAndRemoveOnNonOwner() {
doGetAndRemove(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistGetAndRemoveOnOwner() {
doGetAndRemove(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doGetAndRemove(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key = keySupplier.get();
assertEquals(null, writeMap.put(key, "one"));
assertEquals("one", readMap.get(key));
assertEquals("one", writeMap.remove(key));
assertEquals(null, readMap.get(key));
}
public void testLocalContainsKey() {
doContainsKey(supplyIntKey(), local1, local2);
}
public void testReplContainsKeyOnNonOwner() {
doContainsKey(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplContainsKeyOnOwner() {
doContainsKey(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistContainsKeyOnNonOwner() {
doContainsKey(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistContainsKeyOnOwner() {
doContainsKey(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doContainsKey(Supplier<K> keySupplier,
ConcurrentMap<K, String> map1,
ConcurrentMap<K, String> map2) {
K key = keySupplier.get();
assertEquals(false, map1.containsKey(key));
assertEquals(null, map2.put(key, "one"));
assertEquals(true, map1.containsKey(key));
}
public void testLocalContainsValue() {
doContainsValue(supplyIntKey(), "one", local1, local2);
}
public void testReplContainsValueOnNonOwner() {
doContainsValue(supplyKeyForCache(0, REPL), "one", repl1, repl2);
}
public void testReplContainsValueOnOwner() {
doContainsValue(supplyKeyForCache(1, REPL), "one", repl1, repl2);
}
public void testDistContainsValueOnNonOwner() {
doContainsValue(supplyKeyForCache(0, DIST), "one", dist1, dist2);
}
public void testDistContainsValueOnOwner() {
doContainsValue(supplyKeyForCache(1, DIST), "one", dist1, dist2);
}
private <K> void doContainsValue(Supplier<K> keySupplier, String value,
ConcurrentMap<K, String> map1,
ConcurrentMap<K, String> map2) {
K key = keySupplier.get();
assertEquals(false, map1.containsValue(value));
assertEquals(null, map2.put(key, value));
assertEquals(true, map1.containsValue(value));
assertEquals(false, map1.containsValue("xxx"));
}
public void testLocalSize() {
doSize(supplyIntKey(), local1, local2);
}
public void testReplSizeOnNonOwner() {
doSize(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplSizeOnOwner() {
doSize(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistSizeOnNonOwner() {
doSize(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistSizeOnOwner() {
doSize(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doSize(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key1 = keySupplier.get(), key2 = keySupplier.get();
assertEquals(0, readMap.size());
assertEquals(null, writeMap.put(key1, "one"));
assertEquals(1, readMap.size());
assertEquals(null, writeMap.put(key2, "two"));
assertEquals(2, readMap.size());
assertEquals("one", writeMap.remove(key1));
assertEquals(1, writeMap.size());
assertEquals("two", writeMap.remove(key2));
assertEquals(0, writeMap.size());
}
public void testLocalEmpty() {
doEmpty(supplyIntKey(), local1, local2);
}
public void testReplEmptyOnNonOwner() {
doEmpty(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplEmptyOnOwner() {
doEmpty(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistEmptyOnNonOwner() {
doEmpty(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistEmptyOnOwner() {
doEmpty(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doEmpty(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key = keySupplier.get();
assertEquals(true, readMap.isEmpty());
assertEquals(null, writeMap.put(key, "one"));
assertEquals("one", readMap.get(key));
assertEquals(false, readMap.isEmpty());
assertEquals("one", writeMap.remove(key));
assertEquals(true, readMap.isEmpty());
}
public void testLocalPutAll() {
doPutAll(supplyIntKey(), local1, local2);
}
public void testReplPutAllOnNonOwner() {
doPutAll(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplPutAllOnOwner() {
doPutAll(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistPutAllOnNonOwner() {
doPutAll(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistPutAllOnOwner() {
doPutAll(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doPutAll(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key1 = keySupplier.get(), key2 = keySupplier.get(), key3 = keySupplier.get();
assertEquals(true, readMap.isEmpty());
Map<K, String> data = new HashMap<>();
data.put(key1, "one");
data.put(key2, "two");
data.put(key3, "two");
writeMap.putAll(data);
assertEquals("one", readMap.get(key1));
assertEquals("two", readMap.get(key2));
assertEquals("two", readMap.get(key3));
assertEquals("one", writeMap.remove(key1));
assertEquals("two", writeMap.remove(key2));
assertEquals("two", writeMap.remove(key3));
}
public void testLocalClear() {
doClear(supplyIntKey(), local1, local2);
}
public void testReplClearOnNonOwner() {
doClear(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplClearOnOwner() {
doClear(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistClearOnNonOwner() {
doClear(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistClearOnOwner() {
doClear(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doClear(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key1 = keySupplier.get(), key2 = keySupplier.get(), key3 = keySupplier.get();
assertEquals(true, readMap.isEmpty());
Map<K, String> data = new HashMap<>();
data.put(key1, "one");
data.put(key2, "two");
data.put(key3, "two");
writeMap.putAll(data);
assertEquals("one", readMap.get(key1));
assertEquals("two", readMap.get(key2));
assertEquals("two", readMap.get(key3));
writeMap.clear();
assertEquals(null, readMap.get(key1));
assertEquals(null, readMap.get(key2));
assertEquals(null, readMap.get(key3));
}
public void testLocalKeyValueAndEntrySets() {
doKeyValueAndEntrySets(supplyIntKey(), local1, local2);
}
public void testReplKeyValueAndEntrySetsOnNonOwner() {
doKeyValueAndEntrySets(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplKeyValueAndEntrySetsOnOwner() {
doKeyValueAndEntrySets(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistKeyValueAndEntrySetsOnNonOwner() {
doKeyValueAndEntrySets(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistKeyValueAndEntrySetsOnOwner() {
doKeyValueAndEntrySets(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doKeyValueAndEntrySets(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key1 = keySupplier.get(), key2 = keySupplier.get(), key3 = keySupplier.get();
assertEquals(true, readMap.isEmpty());
writeMap.put(key1, "one");
writeMap.put(key2, "two");
writeMap.put(key3, "two");
Set<K> keys = readMap.keySet();
assertEquals(3, keys.size());
Set<K> expectedKeys = new HashSet<>(Arrays.asList(key1, key2, key3));
keys.forEach(expectedKeys::remove);
assertEquals(true, expectedKeys.isEmpty());
assertEquals(false, readMap.isEmpty());
Collection<String> values = readMap.values();
assertEquals(3, values.size());
Set<String> expectedValues = new HashSet<>(Arrays.asList("one", "two"));
values.forEach(expectedValues::remove);
assertEquals(true, expectedValues.isEmpty());
Set<Map.Entry<K, String>> entries = readMap.entrySet();
assertEquals(3, entries.size());
entries.forEach(e -> {
if (e.getKey().equals(key1)) e.setValue("uno");
else if (e.getKey().equals(key2)) e.setValue("dos");
else e.setValue("dos");
});
assertEquals("uno", writeMap.remove(key1));
assertEquals("dos", writeMap.remove(key2));
assertEquals("dos", writeMap.remove(key3));
}
public void testLocalPutIfAbsent() {
doPutIfAbsent(supplyIntKey(), local1, local2);
}
public void testReplPutIfAbsentOnNonOwner() {
doPutIfAbsent(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplPutIfAbsentOnOwner() {
doPutIfAbsent(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistPutIfAbsentOnNonOwner() {
doPutIfAbsent(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistPutIfAbsentOnOwner() {
doPutIfAbsent(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doPutIfAbsent(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key = keySupplier.get();
assertEquals(null, readMap.get(key));
assertEquals(null, writeMap.putIfAbsent(key, "one"));
assertEquals("one", readMap.get(key));
assertEquals("one", writeMap.putIfAbsent(key, "uno"));
assertEquals("one", readMap.get(key));
assertEquals("one", writeMap.remove(key));
assertEquals(null, readMap.get(key));
}
public void testLocalConditionalRemove() {
doConditionalRemove(supplyIntKey(), local1, local2);
}
public void testReplConditionalRemoveOnNonOwner() {
doConditionalRemove(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplConditionalRemoveOnOwner() {
doConditionalRemove(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistConditionalRemoveOnNonOwner() {
doConditionalRemove(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistConditionalRemoveOnOwner() {
doConditionalRemove(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doConditionalRemove(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key = keySupplier.get();
assertEquals(null, readMap.get(key));
assertFalse(writeMap.remove(key, "xxx"));
assertEquals(null, writeMap.put(key, "one"));
assertEquals("one", readMap.get(key));
assertFalse(writeMap.remove(key, "xxx"));
assertEquals("one", readMap.get(key));
assertTrue(writeMap.remove(key, "one"));
assertEquals(null, readMap.get(key));
}
public void testLocalReplace() {
doReplace(supplyIntKey(), local1, local2);
}
public void testReplReplaceOnNonOwner() {
doReplace(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplReplaceOnOwner() {
doReplace(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistReplaceOnNonOwner() {
doReplace(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistReplaceOnOwner() {
doReplace(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doReplace(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key = keySupplier.get();
assertEquals(null, readMap.get(key));
assertEquals(null, writeMap.replace(key, "xxx"));
assertEquals(null, writeMap.put(key, "one"));
assertEquals("one", readMap.get(key));
assertEquals("one", writeMap.replace(key, "uno"));
assertEquals("uno", readMap.get(key));
assertEquals("uno", writeMap.remove(key));
assertEquals(null, readMap.get(key));
}
public void testLocalReplaceWithValue() {
doReplaceWithValue(supplyIntKey(), local1, local2);
}
public void testReplReplaceWithValueOnNonOwner() {
doReplaceWithValue(supplyKeyForCache(0, REPL), repl1, repl2);
}
public void testReplReplaceWithValueOnOwner() {
doReplaceWithValue(supplyKeyForCache(1, REPL), repl1, repl2);
}
public void testDistReplaceWithValueOnNonOwner() {
doReplaceWithValue(supplyKeyForCache(0, DIST), dist1, dist2);
}
public void testDistReplaceWithValueOnOwner() {
doReplaceWithValue(supplyKeyForCache(1, DIST), dist1, dist2);
}
private <K> void doReplaceWithValue(Supplier<K> keySupplier,
ConcurrentMap<K, String> readMap,
ConcurrentMap<K, String> writeMap) {
K key = keySupplier.get();
assertEquals(null, readMap.get(key));
assertFalse(writeMap.replace(key, "xxx", "uno"));
assertEquals(null, writeMap.put(key, "one"));
assertEquals("one", readMap.get(key));
assertFalse(writeMap.replace(key, "xxx", "uno"));
assertEquals("one", readMap.get(key));
assertTrue(writeMap.replace(key, "one", "uno"));
assertEquals("uno", readMap.get(key));
assertEquals("uno", writeMap.remove(key));
assertEquals(null, readMap.get(key));
}
}
| 18,780
| 32.477718
| 117
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalInMemoryTest.java
|
package org.infinispan.functional;
import static org.infinispan.commons.test.Exceptions.assertException;
import static org.infinispan.commons.test.Exceptions.assertExceptionNonStrict;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.NoSuchElementException;
import java.util.concurrent.CompletionException;
import jakarta.transaction.RollbackException;
import javax.transaction.xa.XAException;
import org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.functional.impl.ReadOnlyMapImpl;
import org.infinispan.remoting.RemoteException;
import org.infinispan.test.TestException;
import org.testng.annotations.Test;
/**
* @author Radim Vansa <rvansa@redhat.com> and Krzysztof Sobolewski <Krzysztof.Sobolewski@atende.pl>
*/
@Test(groups = "functional", testName = "functional.FunctionalInMemoryTest")
public class FunctionalInMemoryTest extends AbstractFunctionalOpTest {
public FunctionalInMemoryTest() {
persistence = false;
}
// Expected invocations; many-commands always execute everywhere
// Mode | O | P | B | Sum
// Non-tx orig == owner | 1 | = | 1 | 2
// Non-tx orig != owner | 0 | 1 | 1 | 2
// Non-tx orig == owner RO | 1 | = | 0 | 1
// Non-tx orig != owner RO | 0 | 1 | 0 | 1
// TX orig == owner RO | 1 | = | 0 | 1
// TX orig == owner RW | 1 | = | 1 | 2
// TX orig == owner WO | 1 | = | 1 | 2
// TX orig == owner WOnoop | 1 | = | 0 | 1
// TX orig != owner RO | 0 | 1 | 0 | 1
// TX orig != owner RW | 0 | 1 | 1 | 2
// TX orig != owner WO | 1 | 1 | 1 | 3 // The write-only command creates the value in context
// TX orig != owner WOnoop | 1 | = | 0 | 1 // The write-only command creates the value in context
@Test(dataProvider = "owningModeAndWriteMethod")
public void testWriteLoad(boolean isOwner, WriteMethod method) {
Object key = getKey(isOwner, DIST);
method.eval(key, wo, rw,
view -> { assertFalse(view.find().isPresent()); return null; },
(view, nil) -> view.set("value"), getClass());
assertInvocations(Boolean.TRUE.equals(transactional) && !isOwner && !method.doesRead ? 3 : 2);
caches(DIST).forEach(cache -> assertEquals(cache.get(key), "value", getAddress(cache).toString()));
caches(DIST).forEach(cache -> {
if (cache.getAdvancedCache().getDistributionManager().getCacheTopology().isReadOwner(key)) {
assertTrue(cacheContainsKey(key, cache), getAddress(cache).toString());
} else {
assertFalse(cacheContainsKey(key, cache), getAddress(cache).toString());
}
});
resetInvocationCount();
// this does not write anything
method.eval(key, wo, rw,
view -> {
assertTrue(view.find().isPresent());
assertEquals(view.get(), "value");
return null;
},
(view, nil) -> {}, getClass());
// TODO ISPN-8676: routing optimization for no-write many commands not implemented
if (method.isMany) {
assertInvocations(Boolean.TRUE.equals(transactional) && !isOwner && !method.doesRead ? 3 : 2);
} else {
assertInvocations(Boolean.TRUE.equals(transactional) && !isOwner && method.doesRead? 2 : 1);
}
}
@Test(dataProvider = "writeMethods")
public void testWriteLoadLocal(WriteMethod method) {
Integer key = 1;
method.eval(key, lwo, lrw,
view -> { assertFalse(view.find().isPresent()); return null; },
(view, nil) -> view.set("value"), getClass());
assertInvocations(1);
assertEquals(cacheManagers.get(0).getCache().get(key), "value");
method.eval(key, lwo, lrw,
view -> {
assertTrue(view.find().isPresent());
assertEquals(view.get(), "value");
return null;
},
(view, nil) -> {}, getClass());
assertInvocations(2);
}
@Test(dataProvider = "owningModeAndWriteMethod")
public void testExceptionPropagation(boolean isOwner, WriteMethod method) {
Object key = getKey(isOwner, DIST);
try {
method.eval(key, wo, rw,
view -> null,
(view, nil) -> {
throw new TestException();
}, getClass());
fail("Should throw CompletionException:CacheException:[RemoteException:]*TestException");
} catch (CacheException | CompletionException e) { // catches RemoteExceptions, too
Throwable t = e;
if (Boolean.TRUE.equals(transactional) && t.getCause() instanceof RollbackException) {
Throwable[] suppressed = t.getCause().getSuppressed();
if (suppressed != null && suppressed.length > 0) {
t = suppressed[0];
assertEquals(XAException.class, t.getClass());
t = t.getCause();
}
}
assertException(CompletionException.class, t);
t = t.getCause();
assertExceptionNonStrict(CacheException.class, t);
while (t.getCause() instanceof RemoteException && t != t.getCause()) {
t = t.getCause();
}
assertException(TestException.class, t.getCause());
}
}
@Test(dataProvider = "owningModeAndReadWrites")
public void testWriteOnMissingValue(boolean isOwner, WriteMethod method) {
Object key = getKey(isOwner, DIST);
try {
method.eval(key, null, rw,
view -> view.get(),
(view, nil) -> {}, getClass());
fail("Should throw CompletionException:CacheException:[RemoteException:]*NoSuchElementException");
} catch (CompletionException e) { // catches RemoteExceptions, too
Throwable t = e;
assertException(CompletionException.class, t);
t = t.getCause();
assertExceptionNonStrict(CacheException.class, t);
while (t.getCause() instanceof RemoteException && t != t.getCause()) {
t = t.getCause();
}
assertException(NoSuchElementException.class, t.getCause());
}
}
@Test(dataProvider = "owningModeAndReadMethod")
public void testReadLoad(boolean isOwner, ReadMethod method) {
Object key = getKey(isOwner, DIST);
assertTrue(method.eval(key, ro, view -> { assertFalse(view.find().isPresent()); return true; }));
// we can't add from read-only cache, so we put manually:
cache(0, DIST).put(key, "value");
caches(DIST).forEach(cache -> assertEquals(cache.get(key), "value", getAddress(cache).toString()));
caches(DIST).forEach(cache -> {
if (cache.getAdvancedCache().getDistributionManager().getCacheTopology().isReadOwner(key)) {
assertTrue(cacheContainsKey(key, cache), getAddress(cache).toString());
} else {
assertFalse(cacheContainsKey(key, cache), getAddress(cache).toString());
}
});
assertEquals(method.eval(key, ro,
view -> {
assertTrue(view.find().isPresent());
assertEquals(view.get(), "value");
return "OK";
}), "OK");
}
@Test(dataProvider = "readMethods")
public void testReadLoadLocal(ReadMethod method) {
Integer key = 1;
assertTrue(method.eval(key, lro,
view -> { assertFalse(view.find().isPresent()); return true; }));
// we can't add from read-only cache, so we put manually:
Cache<Integer, String> cache = cacheManagers.get(0).getCache();
cache.put(key, "value");
assertEquals(cache.get(key), "value");
assertEquals(method.eval(key, lro,
view -> {
assertTrue(view.find().isPresent());
assertEquals(view.get(), "value");
return "OK";
}), "OK");
}
@Test(dataProvider = "owningModeAndReadMethod")
public void testReadOnMissingValue(boolean isOwner, ReadMethod method) {
testReadOnMissingValue(getKey(isOwner, DIST), ro, method);
}
@Test(dataProvider = "readMethods")
public void testOnMissingValueLocal(ReadMethod method) {
testReadOnMissingValue(0, ReadOnlyMapImpl.create(fmapL1), method);
}
protected boolean cacheContainsKey(Object key, Cache<Object, Object> cache) {
return cache.getAdvancedCache().getDataContainer().containsKey(key);
}
}
| 8,531
| 38.137615
| 112
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalConcurrentMapEventsTest.java
|
package org.infinispan.functional;
import static org.infinispan.functional.FunctionalListenerAssertions.assertNoEvents;
import static org.infinispan.functional.FunctionalListenerAssertions.assertOrderedEvents;
import static org.infinispan.functional.FunctionalListenerAssertions.assertUnorderedEvents;
import static org.infinispan.functional.FunctionalListenerAssertions.create;
import static org.infinispan.functional.FunctionalListenerAssertions.createAllRemoveAll;
import static org.infinispan.functional.FunctionalListenerAssertions.createModify;
import static org.infinispan.functional.FunctionalListenerAssertions.createModifyRemove;
import static org.infinispan.functional.FunctionalListenerAssertions.createRemove;
import static org.infinispan.functional.FunctionalListenerAssertions.write;
import static org.infinispan.functional.FunctionalListenerAssertions.writeRemove;
import java.util.Arrays;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "functional.FunctionalConcurrentMapEventsTest")
public class FunctionalConcurrentMapEventsTest extends FunctionalConcurrentMapTest {
public void testLocalEmptyGetThenPut() {
assertOrderedEvents(local2, super::testLocalEmptyGetThenPut, create("one"));
}
@Override
public void testReplEmptyGetThenPutOnNonOwner() {
assertOrderedEvents(repl2, super::testReplEmptyGetThenPutOnNonOwner, create("one"));
}
@Override
public void testReplEmptyGetThenPutOnOwner() {
assertOrderedEvents(repl2, super::testReplEmptyGetThenPutOnOwner, create("one"));
}
@Override
public void testDistEmptyGetThenPutOnNonOwner() {
assertNoEvents(dist2, super::testDistEmptyGetThenPutOnNonOwner);
}
@Override
public void testDistEmptyGetThenPutOnOwner() {
assertOrderedEvents(dist2, super::testDistEmptyGetThenPutOnOwner, create("one"));
}
@Override
public void testLocalPutGet() {
assertOrderedEvents(local2, super::testLocalPutGet, create("one"));
}
@Override
public void testReplPutGetOnNonOwner() {
assertOrderedEvents(repl2, super::testReplPutGetOnNonOwner, create("one"));
}
@Override
public void testReplPutGetOnOwner() {
assertOrderedEvents(repl2, super::testReplPutGetOnOwner, create("one"));
}
@Override
public void testDistPutGetOnNonOwner() {
assertNoEvents(dist2, super::testDistPutGetOnNonOwner);
}
@Override
public void testDistPutGetOnOwner() {
assertOrderedEvents(dist2, super::testDistPutGetOnOwner, create("one"));
}
@Override
public void testLocalPutUpdate() {
assertOrderedEvents(local2, super::testLocalPutUpdate, createModify("one", "uno"));
}
@Override
public void testReplPutUpdateOnNonOwner() {
assertOrderedEvents(repl2, super::testReplPutUpdateOnNonOwner, createModify("one", "uno"));
}
@Override
public void testReplPutUpdateOnOwner() {
assertOrderedEvents(repl2, super::testReplPutUpdateOnOwner, createModify("one", "uno"));
}
@Override
public void testDistPutUpdateOnNonOwner() {
assertNoEvents(dist2, super::testDistPutUpdateOnNonOwner);
}
@Override
public void testDistPutUpdateOnOwner() {
assertOrderedEvents(dist2, super::testDistPutUpdateOnOwner, createModify("one", "uno"));
}
@Override
public void testLocalGetAndRemove() {
assertOrderedEvents(local2, super::testLocalGetAndRemove, createRemove("one"));
}
@Override
public void testReplGetAndRemoveOnNonOwner() {
assertOrderedEvents(repl2, super::testReplGetAndRemoveOnNonOwner, createRemove("one"));
}
@Override
public void testReplGetAndRemoveOnOwner() {
assertOrderedEvents(repl2, super::testReplGetAndRemoveOnOwner, createRemove("one"));
}
@Override
public void testDistGetAndRemoveOnNonOwner() {
assertNoEvents(dist2, super::testDistGetAndRemoveOnNonOwner);
}
@Override
public void testDistGetAndRemoveOnOwner() {
assertOrderedEvents(dist2, super::testDistGetAndRemoveOnOwner, createRemove("one"));
}
@Override
public void testLocalContainsKey() {
assertOrderedEvents(local2, super::testLocalContainsKey, create("one"));
}
@Override
public void testReplContainsKeyOnNonOwner() {
assertOrderedEvents(repl2, super::testReplContainsKeyOnNonOwner, create("one"));
}
@Override
public void testReplContainsKeyOnOwner() {
assertOrderedEvents(repl2, super::testReplContainsKeyOnOwner, create("one"));
}
@Override
public void testDistContainsKeyOnNonOwner() {
assertNoEvents(dist2, super::testDistContainsKeyOnNonOwner);
}
@Override
public void testDistContainsKeyOnOwner() {
assertOrderedEvents(dist2, super::testDistContainsKeyOnOwner, create("one"));
}
@Override
public void testLocalContainsValue() {
assertOrderedEvents(local2, super::testLocalContainsValue, create("one"));
}
@Override
public void testReplContainsValueOnNonOwner() {
assertOrderedEvents(repl2, super::testReplContainsValueOnNonOwner, create("one"));
}
@Override
public void testReplContainsValueOnOwner() {
assertOrderedEvents(repl2, super::testReplContainsValueOnOwner, create("one"));
}
@Override
public void testDistContainsValueOnNonOwner() {
assertNoEvents(dist2, super::testDistContainsValueOnNonOwner);
}
@Override
public void testDistContainsValueOnOwner() {
assertOrderedEvents(dist2, super::testDistContainsValueOnOwner, create("one"));
}
@Override
public void testLocalSize() {
assertOrderedEvents(local2, super::testLocalSize, createAllRemoveAll("one", "two"));
}
@Override
public void testReplSizeOnNonOwner() {
assertOrderedEvents(repl2, super::testReplSizeOnNonOwner, createAllRemoveAll("one", "two"));
}
@Override
public void testReplSizeOnOwner() {
assertOrderedEvents(repl2, super::testReplSizeOnOwner, createAllRemoveAll("one", "two"));
}
@Override
public void testDistSizeOnNonOwner() {
assertNoEvents(dist2, super::testDistSizeOnNonOwner);
}
@Override
public void testDistSizeOnOwner() {
assertOrderedEvents(dist2, super::testDistSizeOnOwner, createAllRemoveAll("one", "two"));
}
@Override
public void testLocalEmpty() {
assertOrderedEvents(local2, super::testLocalEmpty, createRemove("one"));
}
@Override
public void testReplEmptyOnNonOwner() {
assertOrderedEvents(repl2, super::testReplEmptyOnNonOwner, createRemove("one"));
}
@Override
public void testReplEmptyOnOwner() {
assertOrderedEvents(repl2, super::testReplEmptyOnOwner, createRemove("one"));
}
@Override
public void testDistEmptyOnNonOwner() {
assertNoEvents(dist2, super::testDistEmptyOnNonOwner);
}
@Override
public void testDistEmptyOnOwner() {
assertOrderedEvents(dist2, super::testDistEmptyOnOwner, createRemove("one"));
}
@Override
public void testLocalPutAll() {
assertUnorderedEvents(local2, super::testLocalPutAll, writeRemove("one", "two", "two"));
}
@Override
public void testReplPutAllOnNonOwner() {
assertUnorderedEvents(repl2, super::testReplPutAllOnNonOwner, writeRemove("one", "two", "two"));
}
@Override
public void testReplPutAllOnOwner() {
assertUnorderedEvents(repl2, super::testReplPutAllOnOwner, writeRemove("one", "two", "two"));
}
@Override
public void testDistPutAllOnNonOwner() {
assertNoEvents(dist2, super::testDistPutAllOnNonOwner);
}
@Override
public void testDistPutAllOnOwner() {
assertUnorderedEvents(dist2, super::testDistPutAllOnOwner, writeRemove("one", "two", "two"));
}
@Override
public void testLocalClear() {
assertUnorderedEvents(local2, super::testLocalClear, write("one", "two", "two"));
}
@Override
public void testReplClearOnNonOwner() {
assertUnorderedEvents(repl2, super::testReplClearOnNonOwner, write("one", "two", "two"));
}
@Override
public void testReplClearOnOwner() {
assertUnorderedEvents(repl2, super::testReplClearOnOwner, write("one", "two", "two"));
}
@Override
public void testDistClearOnNonOwner() {
assertNoEvents(dist2, super::testDistClearOnNonOwner);
}
@Override
public void testDistClearOnOwner() {
assertUnorderedEvents(dist2, super::testDistClearOnOwner, write("one", "two", "two"));
}
@Override
public void testLocalKeyValueAndEntrySets() {
assertUnorderedEvents(local2, super::testLocalKeyValueAndEntrySets,
createModifyRemove(Arrays.asList("one", "two", "two"), Arrays.asList("uno", "dos", "dos")));
}
@Override
public void testReplKeyValueAndEntrySetsOnNonOwner() {
assertUnorderedEvents(repl2, super::testReplKeyValueAndEntrySetsOnNonOwner,
createModifyRemove(Arrays.asList("one", "two", "two"), Arrays.asList("uno", "dos", "dos")));
}
@Override
public void testReplKeyValueAndEntrySetsOnOwner() {
assertUnorderedEvents(repl2, super::testReplKeyValueAndEntrySetsOnOwner,
createModifyRemove(Arrays.asList("one", "two", "two"), Arrays.asList("uno", "dos", "dos")));
}
@Override
public void testDistKeyValueAndEntrySetsOnNonOwner() {
assertNoEvents(dist2, super::testDistKeyValueAndEntrySetsOnNonOwner);
}
@Override
public void testDistKeyValueAndEntrySetsOnOwner() {
assertUnorderedEvents(dist2, super::testDistKeyValueAndEntrySetsOnOwner,
createModifyRemove(Arrays.asList("one", "two", "two"), Arrays.asList("uno", "dos", "dos")));
}
@Override
public void testLocalPutIfAbsent() {
assertOrderedEvents(local2, super::testLocalPutIfAbsent, createRemove("one"));
}
@Override
public void testReplPutIfAbsentOnNonOwner() {
assertOrderedEvents(repl2, super::testReplPutIfAbsentOnNonOwner, createRemove("one"));
}
@Override
public void testReplPutIfAbsentOnOwner() {
assertOrderedEvents(repl2, super::testReplPutIfAbsentOnOwner, createRemove("one"));
}
@Override
public void testDistPutIfAbsentOnNonOwner() {
assertNoEvents(dist2, super::testDistPutIfAbsentOnNonOwner);
}
@Override
public void testDistPutIfAbsentOnOwner() {
assertOrderedEvents(dist2, super::testDistPutIfAbsentOnOwner, createRemove("one"));
}
@Override
public void testLocalConditionalRemove() {
assertOrderedEvents(local2, super::testLocalConditionalRemove, createRemove("one"));
}
@Override
public void testReplConditionalRemoveOnNonOwner() {
assertOrderedEvents(repl2, super::testReplConditionalRemoveOnNonOwner, createRemove("one"));
}
@Override
public void testReplConditionalRemoveOnOwner() {
assertOrderedEvents(repl2, super::testReplConditionalRemoveOnOwner, createRemove("one"));
}
@Override
public void testDistConditionalRemoveOnNonOwner() {
assertNoEvents(dist2, super::testDistConditionalRemoveOnNonOwner);
}
@Override
public void testDistConditionalRemoveOnOwner() {
assertOrderedEvents(dist2, super::testDistConditionalRemoveOnOwner, createRemove("one"));
}
@Override
public void testLocalReplace() {
assertOrderedEvents(local2, super::testLocalReplace, createModifyRemove("one", "uno"));
}
@Override
public void testReplReplaceOnNonOwner() {
assertOrderedEvents(repl2, super::testReplReplaceOnNonOwner, createModifyRemove("one", "uno"));
}
@Override
public void testReplReplaceOnOwner() {
assertOrderedEvents(repl2, super::testReplReplaceOnOwner, createModifyRemove("one", "uno"));
}
@Override
public void testDistReplaceOnNonOwner() {
assertNoEvents(dist2, super::testDistReplaceOnNonOwner);
}
@Override
public void testDistReplaceOnOwner() {
assertOrderedEvents(dist2, super::testDistReplaceOnOwner, createModifyRemove("one", "uno"));
}
@Override
public void testLocalReplaceWithValue() {
assertOrderedEvents(local2, super::testLocalReplaceWithValue, createModifyRemove("one", "uno"));
}
@Override
public void testReplReplaceWithValueOnNonOwner() {
assertOrderedEvents(repl2, super::testReplReplaceWithValueOnNonOwner, createModifyRemove("one", "uno"));
}
@Override
public void testReplReplaceWithValueOnOwner() {
assertOrderedEvents(repl2, super::testReplReplaceWithValueOnOwner, createModifyRemove("one", "uno"));
}
@Override
public void testDistReplaceWithValueOnNonOwner() {
assertNoEvents(dist2, super::testDistReplaceWithValueOnNonOwner);
}
@Override
public void testDistReplaceWithValueOnOwner() {
assertOrderedEvents(dist2, super::testDistReplaceWithValueOnOwner, createModifyRemove("one", "uno"));
}
}
| 12,791
| 30.98
| 110
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalNoopDoesNotGoToBackupTest.java
|
package org.infinispan.functional;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.distribution.MagicKey;
import org.infinispan.functional.FunctionalMap.ReadWriteMap;
import org.infinispan.functional.FunctionalMap.WriteOnlyMap;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.functional.impl.WriteOnlyMapImpl;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.CountingRpcManager;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "functional.FunctionalNoopDoesNotGoToBackupTest")
public class FunctionalNoopDoesNotGoToBackupTest extends MultipleCacheManagersTest {
private ReadWriteMap<Object, Object> rw0, rw1;
private WriteOnlyMap<Object, Object> wo0, wo1;
private MagicKey key;
private CountingRpcManager rpcManager0;
private CountingRpcManager rpcManager1;
@Override
protected void createCacheManagers() throws Throwable {
createCluster(TestDataSCI.INSTANCE, getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC), 2);
FunctionalMapImpl<Object, Object> fmap0 = FunctionalMapImpl.create(cache(0).getAdvancedCache());
FunctionalMapImpl<Object, Object> fmap1 = FunctionalMapImpl.create(cache(1).getAdvancedCache());
rw0 = ReadWriteMapImpl.create(fmap0);
rw1 = ReadWriteMapImpl.create(fmap1);
wo0 = WriteOnlyMapImpl.create(fmap0);
wo1 = WriteOnlyMapImpl.create(fmap1);
key = new MagicKey(cache(0));
rpcManager0 = TestingUtil.wrapComponent(cache(0), RpcManager.class, CountingRpcManager::new);
rpcManager1 = TestingUtil.wrapComponent(cache(1), RpcManager.class, CountingRpcManager::new);
}
@DataProvider(name = "ownerAndExistence")
public Object[][] ownerAndExistence() {
return new Object[][]{
{false, false},
{false, true},
{true, false},
{true, true}
};
}
@Test(dataProvider = "ownerAndExistence")
public void testReadWriteKeyCommand(boolean onOwner, boolean withExisting) {
ReadWriteMap<Object, Object> rw = onOwner ? rw0 : rw1;
test(() -> rw.eval(key, view -> view.find().orElse(null)), onOwner, withExisting);
}
@Test(dataProvider = "ownerAndExistence")
public void testReadWriteKeyValueCommand(boolean onOwner, boolean withExisting) {
ReadWriteMap<Object, Object> rw = onOwner ? rw0 : rw1;
test(() -> rw.eval(key, "bar", (bar, view) -> view.find().orElse(null)), onOwner, withExisting);
}
// TODO: Updating routing logic for multi-commands, not sending the update to backup is non-trivial
@Test(dataProvider = "ownerAndExistence", enabled = false, description = "ISPN-8676")
public void testReadWriteManyCommand(boolean onOwner, boolean withExisting) {
ReadWriteMap<Object, Object> rw = onOwner ? rw0 : rw1;
testMany(() -> rw.evalMany(Collections.singleton(key), view -> view.find().orElse(null)), onOwner, withExisting);
}
@Test(dataProvider = "ownerAndExistence", enabled = false, description = "ISPN-8676")
public void testReadWriteManyEntriesCommand(boolean onOwner, boolean withExisting) {
ReadWriteMap<Object, Object> rw = onOwner ? rw0 : rw1;
testMany(() -> rw.evalMany(Collections.singletonMap(key, "bar"), (bar, view) -> view.find().orElse(null)), onOwner, withExisting);
}
@Test(dataProvider = "ownerAndExistence")
public void testWriteOnlyKeyCommand(boolean onOwner, boolean withExisting) {
WriteOnlyMap<Object, Object> wo = onOwner ? wo0 : wo1;
test(() -> wo.eval(key, view -> {
}), onOwner, withExisting);
}
@Test(dataProvider = "ownerAndExistence")
public void testWriteOnlyKeyValueCommand(boolean onOwner, boolean withExisting) {
WriteOnlyMap<Object, Object> wo = onOwner ? wo0 : wo1;
test(() -> wo.eval(key, "bar", (bar, view) -> {
}), onOwner, withExisting);
}
@Test(dataProvider = "ownerAndExistence", enabled = false, description = "ISPN-8676")
public void testWriteOnlyManyCommand(boolean onOwner, boolean withExisting) {
WriteOnlyMap<Object, Object> wo = onOwner ? wo0 : wo1;
test(() -> wo.evalMany(Collections.singleton(key), view -> {
}), onOwner, withExisting);
}
@Test(dataProvider = "ownerAndExistence", enabled = false, description = "ISPN-8676")
public void testWriteOnlyManyEntriesCommand(boolean onOwner, boolean withExisting) {
WriteOnlyMap<Object, Object> wo = onOwner ? wo0 : wo1;
test(() -> wo.evalMany(Collections.singletonMap(key, "bar"), (bar, view) -> {
}), onOwner, withExisting);
}
private void test(Supplier<CompletableFuture<?>> supplier, boolean onOwner, boolean withExisting) {
if (withExisting) {
cache(0).put(key, "foo");
}
rpcManager0.otherCount = 0;
rpcManager1.otherCount = 0;
supplier.get().join();
assertEquals(0, rpcManager0.otherCount);
assertEquals(onOwner ? 0 : 1, rpcManager1.otherCount);
}
private void testMany(Supplier<Traversable<?>> supplier, boolean onOwner, boolean withExisting) {
if (withExisting) {
cache(0).put(key, "foo");
}
rpcManager0.otherCount = 0;
rpcManager1.otherCount = 0;
supplier.get().forEach(x -> {
});
assertEquals(0, rpcManager0.otherCount);
assertEquals(onOwner ? 0 : 1, rpcManager1.otherCount);
}
}
| 5,777
| 42.443609
| 136
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalMapTest.java
|
package org.infinispan.functional;
import static org.infinispan.container.versioning.InequalVersionComparisonResult.EQUAL;
import static org.infinispan.functional.FunctionalTestUtils.assertReadOnlyViewEmpty;
import static org.infinispan.functional.FunctionalTestUtils.assertReadOnlyViewEquals;
import static org.infinispan.functional.FunctionalTestUtils.assertReadWriteViewEmpty;
import static org.infinispan.functional.FunctionalTestUtils.assertReadWriteViewEquals;
import static org.infinispan.functional.FunctionalTestUtils.await;
import static org.infinispan.functional.FunctionalTestUtils.ro;
import static org.infinispan.functional.FunctionalTestUtils.rw;
import static org.infinispan.functional.FunctionalTestUtils.supplyIntKey;
import static org.infinispan.functional.FunctionalTestUtils.wo;
import static org.infinispan.marshall.core.MarshallableFunctions.identity;
import static org.infinispan.marshall.core.MarshallableFunctions.removeReturnPrevOrNull;
import static org.infinispan.marshall.core.MarshallableFunctions.returnReadOnlyFindOrNull;
import static org.infinispan.marshall.core.MarshallableFunctions.returnReadWriteFind;
import static org.infinispan.marshall.core.MarshallableFunctions.returnReadWriteGet;
import static org.infinispan.marshall.core.MarshallableFunctions.returnReadWriteView;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueConsumer;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueReturnPrevOrNull;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueReturnView;
import static org.infinispan.test.TestingUtil.withCacheManager;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.marshall.Externalizer;
import org.infinispan.commons.marshall.SerializeFunctionWith;
import org.infinispan.commons.marshall.SerializeWith;
import org.infinispan.commons.test.skip.SkipTestNG;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.versioning.NumericVersion;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.functional.EntryView.ReadWriteEntryView;
import org.infinispan.functional.EntryView.WriteEntryView;
import org.infinispan.functional.FunctionalMap.ReadOnlyMap;
import org.infinispan.functional.FunctionalMap.ReadWriteMap;
import org.infinispan.functional.FunctionalMap.WriteOnlyMap;
import org.infinispan.functional.MetaParam.MetaEntryVersion;
import org.infinispan.functional.MetaParam.MetaLifespan;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadOnlyMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.functional.impl.WriteOnlyMapImpl;
import org.infinispan.test.CacheManagerCallable;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.function.SerializableFunction;
import org.testng.annotations.Test;
/**
* Test suite for verifying basic functional map functionality,
* and for testing out functionality that is not available via standard
* {@link java.util.concurrent.ConcurrentMap}
* APIs, such as atomic conditional metadata-based replace operations, which
* are required by Hot Rod.
*/
@Test(groups = "functional", testName = "functional.FunctionalMapTest")
public class FunctionalMapTest extends AbstractFunctionalTest {
public void testLocalWriteConstantAndReadGetsValue() {
doWriteConstantAndReadGetsValue(supplyIntKey(), ro(fmapL1), wo(fmapL2));
}
public void testReplWriteConstantAndReadGetsValueOnNonOwner() {
doWriteConstantAndReadGetsValue(supplyKeyForCache(0, REPL), ro(fmapR1), wo(fmapR2));
}
public void testReplWriteConstantAndReadGetsValueOnOwner() {
doWriteConstantAndReadGetsValue(supplyKeyForCache(1, REPL), ro(fmapR1), wo(fmapR2));
}
public void testDistWriteConstantAndReadGetsValueOnNonOwner() {
doWriteConstantAndReadGetsValue(supplyKeyForCache(0, DIST), ro(fmapD1), wo(fmapD2));
}
public void testDistWriteConstantAndReadGetsValueOnOwner() {
doWriteConstantAndReadGetsValue(supplyKeyForCache(1, DIST), ro(fmapD1), wo(fmapD2));
}
/**
* Write-only allows for constant, non-capturing, values to be written,
* and read-only allows for those values to be retrieved.
*/
private <K> void doWriteConstantAndReadGetsValue(Supplier<K> keySupplier,
ReadOnlyMap<K, String> map1, WriteOnlyMap<K, String> map2) {
K key = keySupplier.get();
await(
map2.eval(key, SetStringConstant.INSTANCE).thenCompose(r ->
map1.eval(key, returnReadOnlyFindOrNull()).thenAccept(v -> {
assertNull(r);
assertEquals("one", v);
}
)
)
);
}
@SerializeWith(value = SetStringConstant.Externalizer0.class)
private static final class SetStringConstant<K> implements Consumer<WriteEntryView<K, String>> {
@Override
public void accept(WriteEntryView<K, String> wo) {
wo.set("one");
}
private static final SetStringConstant INSTANCE = new SetStringConstant();
public static final class Externalizer0 implements Externalizer<Object> {
public void writeObject(ObjectOutput oo, Object o) {}
public Object readObject(ObjectInput input) { return INSTANCE; }
}
}
public void testLocalWriteValueAndReadValueAndMetadata() {
doWriteValueAndReadValueAndMetadata(supplyIntKey(), ro(fmapL1), wo(fmapL2));
}
public void testReplWriteValueAndReadValueAndMetadataOnNonOwner() {
doWriteValueAndReadValueAndMetadata(supplyKeyForCache(0, REPL), ro(fmapR1), wo(fmapR2));
}
public void testReplWriteValueAndReadValueAndMetadataOnOwner() {
doWriteValueAndReadValueAndMetadata(supplyKeyForCache(1, REPL), ro(fmapR1), wo(fmapR2));
}
public void testDistWriteValueAndReadValueAndMetadataOnNonOwner() {
doWriteValueAndReadValueAndMetadata(supplyKeyForCache(0, DIST), ro(fmapD1), wo(fmapD2));
}
public void testDistWriteValueAndReadValueAndMetadataOnOwner() {
doWriteValueAndReadValueAndMetadata(supplyKeyForCache(1, DIST), ro(fmapD1), wo(fmapD2));
}
/**
* Write-only allows for non-capturing values to be written along with metadata,
* and read-only allows for both values and metadata to be retrieved.
*/
private <K> void doWriteValueAndReadValueAndMetadata(Supplier<K> keySupplier,
ReadOnlyMap<K, String> map1, WriteOnlyMap<K, String> map2) {
K key = keySupplier.get();
await(
map2.eval(key, "one", SetValueAndConstantLifespan.getInstance()).thenCompose(r ->
map1.eval(key, identity()).thenAccept(ro -> {
assertNull(r);
assertEquals(Optional.of("one"), ro.find());
assertEquals("one", ro.get());
assertEquals(Optional.of(new MetaLifespan(100000)), ro.findMetaParam(MetaLifespan.class));
}
)
)
);
}
@SerializeWith(value = SetValueAndConstantLifespan.Externalizer0.class)
private static final class SetValueAndConstantLifespan<K, V>
implements BiConsumer<V, WriteEntryView<K, V>> {
@Override
public void accept(V v, WriteEntryView<K, V> wo) {
wo.set(v, new MetaLifespan(100000));
}
@SuppressWarnings("unchecked")
private static <K, V> SetValueAndConstantLifespan<K, V> getInstance() {
return INSTANCE;
}
private static final SetValueAndConstantLifespan INSTANCE =
new SetValueAndConstantLifespan<>();
public static final class Externalizer0 implements Externalizer<Object> {
public void writeObject(ObjectOutput oo, Object o) {}
public Object readObject(ObjectInput input) { return INSTANCE; }
}
}
public void testLocalReadWriteGetsEmpty() {
doReadWriteGetsEmpty(supplyIntKey(), rw(fmapL1));
}
public void testReplReadWriteGetsEmptyOnNonOwner() {
doReadWriteGetsEmpty(supplyKeyForCache(0, REPL), rw(fmapR1));
}
public void testReplReadWriteGetsEmptyOnOwner() {
doReadWriteGetsEmpty(supplyKeyForCache(1, REPL), rw(fmapR1));
}
public void testDistReadWriteGetsEmptyOnNonOwner() {
doReadWriteGetsEmpty(supplyKeyForCache(0, DIST), rw(fmapD1));
}
public void testDistReadWriteGetsEmptyOnOwner() {
doReadWriteGetsEmpty(supplyKeyForCache(1, DIST), rw(fmapD1));
}
/**
* Read-write allows to retrieve an empty cache entry.
*/
<K> void doReadWriteGetsEmpty(Supplier<K> keySupplier, ReadWriteMap<K, String> map) {
K key = keySupplier.get();
await(map.eval(key, returnReadWriteFind()).thenAccept(v -> assertEquals(Optional.empty(), v)));
}
public void testLocalReadWriteValuesReturnPrevious() {
doReadWriteConstantReturnPrev(supplyIntKey(), rw(fmapL1), rw(fmapL2));
}
public void testReplReadWriteValuesReturnPreviousOnNonOwner() {
doReadWriteConstantReturnPrev(supplyKeyForCache(0, REPL), rw(fmapR1), rw(fmapR2));
}
public void testReplReadWriteValuesReturnPreviousOnOwner() {
doReadWriteConstantReturnPrev(supplyKeyForCache(1, REPL), rw(fmapR1), rw(fmapR2));
}
public void testDistReadWriteValuesReturnPreviousOnNonOwner() {
doReadWriteConstantReturnPrev(supplyKeyForCache(0, DIST), rw(fmapD1), rw(fmapD2));
}
public void testDistReadWriteValuesReturnPreviousOnOwner() {
doReadWriteConstantReturnPrev(supplyKeyForCache(1, DIST), rw(fmapD1), rw(fmapD2));
}
/**
* Read-write allows for constant, non-capturing, values to be written,
* returns previous value, and also allows values to be retrieved.
*/
private <K> void doReadWriteConstantReturnPrev(Supplier<K> keySupplier,
ReadWriteMap<K, String> map1, ReadWriteMap<K, String> map2) {
K key = keySupplier.get();
await(
map2.eval(key, SetStringConstantReturnPrevious.getInstance()).thenCompose(r ->
map1.eval(key, returnReadWriteGet()).thenAccept(v -> {
assertFalse(r.isPresent());
assertEquals("one", v);
}
)
)
);
}
@SerializeFunctionWith(value = SetStringConstantReturnPrevious.Externalizer0.class)
private static final class SetStringConstantReturnPrevious<K>
implements Function<ReadWriteEntryView<K, String>, Optional<String>> {
@Override
public Optional<String> apply(ReadWriteEntryView<K, String> rw) {
Optional<String> prev = rw.find();
rw.set("one");
return prev;
}
@SuppressWarnings("unchecked")
private static <K> SetStringConstantReturnPrevious<K> getInstance() {
return INSTANCE;
}
private static final SetStringConstantReturnPrevious INSTANCE =
new SetStringConstantReturnPrevious<>();
public static final class Externalizer0 implements Externalizer<Object> {
public void writeObject(ObjectOutput oo, Object o) {}
public Object readObject(ObjectInput input) { return INSTANCE; }
}
}
// Transactions use SimpleClusteredVersions, not NumericVersions, and user is not supposed to modify those
public void testLocalReadWriteForConditionalParamBasedReplace() {
assumeNonTransactional();
doReadWriteForConditionalParamBasedReplace(supplyIntKey(), rw(fmapL1), rw(fmapL2));
}
public void testReplReadWriteForConditionalParamBasedReplaceOnNonOwner() {
assumeNonTransactional();
doReadWriteForConditionalParamBasedReplace(supplyKeyForCache(0, REPL), rw(fmapR1), rw(fmapR2));
}
public void testReplReadWriteForConditionalParamBasedReplaceOnOwner() {
assumeNonTransactional();
doReadWriteForConditionalParamBasedReplace(supplyKeyForCache(1, REPL), rw(fmapR1), rw(fmapR2));
}
public void testDistReadWriteForConditionalParamBasedReplaceOnNonOwner() {
assumeNonTransactional();
doReadWriteForConditionalParamBasedReplace(supplyKeyForCache(0, DIST), rw(fmapD1), rw(fmapD2));
}
public void testDistReadWriteForConditionalParamBasedReplaceOnOwner() {
assumeNonTransactional();
doReadWriteForConditionalParamBasedReplace(supplyKeyForCache(1, DIST), rw(fmapD1), rw(fmapD2));
}
/**
* Read-write allows for replace operations to happen based on version
* comparison, and update version information if replace is versions are
* equals.
*
* This is the kind of advance operation that Hot Rod prototocol requires
* but the current Infinispan API is unable to offer without offering
* atomicity at the level of the function that compares the version
* information.
*/
<K> void doReadWriteForConditionalParamBasedReplace(Supplier<K> keySupplier,
ReadWriteMap<K, String> map1, ReadWriteMap<K, String> map2) {
replaceWithVersion(keySupplier, map1, map2, 100, rw -> {
assertEquals("uno", rw.get());
assertEquals(Optional.of(new MetaEntryVersion(new NumericVersion(200))),
rw.findMetaParam(MetaEntryVersion.class));
}
);
replaceWithVersion(keySupplier, map1, map2, 900, rw -> {
assertEquals(Optional.of("one"), rw.find());
assertEquals(Optional.of(new MetaEntryVersion(new NumericVersion(100))),
rw.findMetaParam(MetaEntryVersion.class));
});
}
private <K> void replaceWithVersion(Supplier<K> keySupplier,
ReadWriteMap<K, String> map1, ReadWriteMap<K, String> map2,
long version, Consumer<ReadWriteEntryView<K, String>> asserts) {
K key = keySupplier.get();
await(
map1.eval(key, SetStringAndVersionConstant.getInstance()).thenCompose(r ->
map2.eval(key, new VersionBasedConditionalReplace<>(version)).thenAccept(rw -> {
assertNull(r);
asserts.accept(rw);
}
)
)
);
}
@SerializeFunctionWith(value = SetStringAndVersionConstant.Externalizer0.class)
private static final class SetStringAndVersionConstant<K>
implements Function<ReadWriteEntryView<K, String>, Void> {
@Override
public Void apply(ReadWriteEntryView<K, String> rw) {
rw.set("one", new MetaEntryVersion(new NumericVersion(100)));
return null;
}
@SuppressWarnings("unchecked")
private static <K> SetStringAndVersionConstant<K> getInstance() {
return INSTANCE;
}
private static final SetStringAndVersionConstant INSTANCE =
new SetStringAndVersionConstant<>();
public static final class Externalizer0 implements Externalizer<Object> {
public void writeObject(ObjectOutput oo, Object o) {}
public Object readObject(ObjectInput input) { return INSTANCE; }
}
}
@SerializeFunctionWith(value = VersionBasedConditionalReplace.Externalizer0.class)
private static final class VersionBasedConditionalReplace<K>
implements Function<ReadWriteEntryView<K, String>, ReadWriteEntryView<K, String>> {
private final long version;
private VersionBasedConditionalReplace(long version) {
this.version = version;
}
@Override
public ReadWriteEntryView<K, String> apply(ReadWriteEntryView<K, String> rw) {
Optional<MetaEntryVersion> metaParam = rw.findMetaParam(MetaEntryVersion.class);
metaParam.ifPresent(metaVersion -> {
if (metaVersion.get().compareTo(new NumericVersion(version)) == EQUAL)
rw.set("uno", new MetaEntryVersion(new NumericVersion(200)));
});
return rw;
}
public static final class Externalizer0 implements Externalizer<VersionBasedConditionalReplace<?>> {
@Override
public void writeObject(ObjectOutput output, VersionBasedConditionalReplace<?> object) throws IOException {
output.writeLong(object.version);
}
@Override
public VersionBasedConditionalReplace<?> readObject(ObjectInput input) throws IOException, ClassNotFoundException {
long version = input.readLong();
return new VersionBasedConditionalReplace<>(version);
}
}
}
public void testAutoClose() throws Exception {
withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()) {
@Override
public void call() throws Exception {
Configuration configBuilder = new ConfigurationBuilder().build();
cm.defineConfiguration("read-only", configBuilder);
AdvancedCache<?, ?> readOnlyCache = getAdvancedCache(cm, "read-only");
try (ReadOnlyMap<?, ?> ro = ReadOnlyMapImpl.create(FunctionalMapImpl.create(readOnlyCache))) {
assertNotNull(ro); // No-op, just verify that it implements AutoCloseable
}
assertTrue(readOnlyCache.getStatus().isTerminated());
cm.defineConfiguration("write-only", configBuilder);
AdvancedCache<?, ?> writeOnlyCache = getAdvancedCache(cm, "write-only");
try (WriteOnlyMap<?, ?> wo = WriteOnlyMapImpl.create(FunctionalMapImpl.create(writeOnlyCache))) {
assertNotNull(wo); // No-op, just verify that it implements AutoCloseable
}
assertTrue(writeOnlyCache.getStatus().isTerminated());
cm.defineConfiguration("read-write", configBuilder);
AdvancedCache<?, ?> readWriteCache = getAdvancedCache(cm, "read-write");
try (ReadWriteMap<?, ?> rw = ReadWriteMapImpl.create(FunctionalMapImpl.create(readWriteCache))) {
assertNotNull(rw); // No-op, just verify that it implements AutoCloseable
}
assertTrue(readWriteCache.getStatus().isTerminated());
}
});
}
public void testLocalReadOnlyEvalManyEmpty() {
doReadOnlyEvalManyEmpty(supplyIntKey(), ro(fmapL1));
}
public void testReplReadOnlyEvalManyEmptyOnNonOwner() {
doReadOnlyEvalManyEmpty(supplyKeyForCache(0, REPL), ro(fmapR1));
}
public void testReplReadOnlyEvalManyEmptyOnOwner() {
doReadOnlyEvalManyEmpty(supplyKeyForCache(1, REPL), ro(fmapR1));
}
public void testDistReadOnlyEvalManyEmptyOnNonOwner() {
doReadOnlyEvalManyEmpty(supplyKeyForCache(0, DIST), ro(fmapD1));
}
public void testDistReadOnlyEvalManyEmptyOnOwner() {
doReadOnlyEvalManyEmpty(supplyKeyForCache(1, DIST), ro(fmapD1));
}
private <K> void doReadOnlyEvalManyEmpty(Supplier<K> keySupplier, ReadOnlyMap<K, String> map) {
K key1 = keySupplier.get(), key2 = keySupplier.get(), key3 = keySupplier.get();
Traversable<ReadEntryView<K, String>> t = map
.evalMany(new HashSet<>(Arrays.asList(key1, key2, key3)), identity());
t.forEach(ro -> assertFalse(ro.find().isPresent()));
}
public void testLocalUpdateSubsetAndReturnPrevs() {
doUpdateSubsetAndReturnPrevs(supplyIntKey(), ro(fmapL1), wo(fmapL2), rw(fmapL2));
}
public void testReplUpdateSubsetAndReturnPrevsOnNonOwner() {
doUpdateSubsetAndReturnPrevs(supplyKeyForCache(0, REPL), ro(fmapR1), wo(fmapR2), rw(fmapR2));
}
public void testReplUpdateSubsetAndReturnPrevsOnOwner() {
doUpdateSubsetAndReturnPrevs(supplyKeyForCache(1, REPL), ro(fmapR1), wo(fmapR2), rw(fmapR2));
}
public void testDistUpdateSubsetAndReturnPrevsOnNonOwner() {
doUpdateSubsetAndReturnPrevs(supplyKeyForCache(0, DIST), ro(fmapD1), wo(fmapD2), rw(fmapD2));
}
public void testDistUpdateSubsetAndReturnPrevsOnOwner() {
doUpdateSubsetAndReturnPrevs(supplyKeyForCache(1, DIST), ro(fmapD1), wo(fmapD2), rw(fmapD2));
}
private <K> void doUpdateSubsetAndReturnPrevs(Supplier<K> keySupplier,
ReadOnlyMap<K, String> map1, WriteOnlyMap<K, String> map2, ReadWriteMap<K, String> map3) {
K key1 = keySupplier.get(), key2 = keySupplier.get(), key3 = keySupplier.get();
Map<K, String> data = new HashMap<>();
data.put(key1, "one");
data.put(key2, "two");
data.put(key3, "three");
await(map2.evalMany(data, setValueConsumer()));
Traversable<String> currentValues = map1.evalMany(data.keySet(), returnReadOnlyFindOrNull());
List<String> collectedValues = currentValues.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
Collections.sort(collectedValues);
List<String> dataValues = new ArrayList<>(data.values());
Collections.sort(dataValues);
assertEquals(collectedValues, dataValues);
Map<K, String> newData = new HashMap<>();
newData.put(key1, "bat");
newData.put(key2, "bi");
newData.put(key3, "hiru");
Traversable<String> prevTraversable = map3.evalMany(newData, setValueReturnPrevOrNull());
List<String> collectedPrev = prevTraversable.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
Collections.sort(collectedPrev);
assertEquals(dataValues, collectedPrev);
Traversable<String> updatedValues = map1.evalMany(data.keySet(), returnReadOnlyFindOrNull());
List<String> collectedUpdates = updatedValues.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
Collections.sort(collectedUpdates);
List<String> newDataValues = new ArrayList<>(newData.values());
Collections.sort(newDataValues);
assertEquals(newDataValues, collectedUpdates);
}
public void testLocalReadWriteToRemoveAllAndReturnPrevs() {
doReadWriteToRemoveAllAndReturnPrevs(supplyIntKey(), wo(fmapL1), rw(fmapL2));
}
public void testReplReadWriteToRemoveAllAndReturnPrevsOnNonOwner() {
doReadWriteToRemoveAllAndReturnPrevs(supplyKeyForCache(0, REPL), wo(fmapR1), rw(fmapR2));
}
public void testReplReadWriteToRemoveAllAndReturnPrevsOnOwner() {
doReadWriteToRemoveAllAndReturnPrevs(supplyKeyForCache(1, REPL), wo(fmapR1), rw(fmapR2));
}
public void testDistReadWriteToRemoveAllAndReturnPrevsOnNonOwner() {
doReadWriteToRemoveAllAndReturnPrevs(supplyKeyForCache(0, DIST), wo(fmapD1), rw(fmapD2));
}
public void testDistReadWriteToRemoveAllAndReturnPrevsOnOwner() {
doReadWriteToRemoveAllAndReturnPrevs(supplyKeyForCache(1, DIST), wo(fmapD1), rw(fmapD2));
}
<K> void doReadWriteToRemoveAllAndReturnPrevs(Supplier<K> keySupplier,
WriteOnlyMap<K, String> map1, ReadWriteMap<K, String> map2) {
K key1 = keySupplier.get(), key2 = keySupplier.get(), key3 = keySupplier.get();
Map<K, String> data = new HashMap<>();
data.put(key1, "one");
data.put(key2, "two");
data.put(key3, "three");
await(map1.evalMany(data, setValueConsumer()));
Traversable<String> prevTraversable = map2.evalAll(removeReturnPrevOrNull());
Set<String> prevValues = prevTraversable.collect(HashSet::new, HashSet::add, HashSet::addAll);
assertEquals(new HashSet<>(data.values()), prevValues);
}
public void testLocalReturnViewFromReadOnlyEval() {
doReturnViewFromReadOnlyEval(supplyIntKey(), ro(fmapL1), wo(fmapL2));
}
public void testReplReturnViewFromReadOnlyEvalOnNonOwner() {
doReturnViewFromReadOnlyEval(supplyKeyForCache(0, REPL), ro(fmapR1), wo(fmapR2));
}
public void testReplReturnViewFromReadOnlyEvalOnOwner() {
doReturnViewFromReadOnlyEval(supplyKeyForCache(1, REPL), ro(fmapR1), wo(fmapR2));
}
public void testDistReturnViewFromReadOnlyEvalOnNonOwner() {
doReturnViewFromReadOnlyEval(supplyKeyForCache(0, DIST), ro(fmapD1), wo(fmapD2));
}
public void testDistReturnViewFromReadOnlyEvalOnOwner() {
doReturnViewFromReadOnlyEval(supplyKeyForCache(1, DIST), ro(fmapD1), wo(fmapD2));
}
<K> void doReturnViewFromReadOnlyEval(Supplier<K> keySupplier,
ReadOnlyMap<K, String> ro, WriteOnlyMap<K, String> wo) {
K k = keySupplier.get();
assertReadOnlyViewEmpty(k, await(ro.eval(k, identity())));
await(wo.eval(k, wv -> wv.set("one")));
assertReadOnlyViewEquals(k, "one", await(ro.eval(k, identity())));
}
public void testLocalReturnViewFromReadWriteEval() {
doReturnViewFromReadWriteEval(supplyIntKey(), rw(fmapL1), rw(fmapL2));
}
public void testReplReturnViewFromReadWriteEvalOnNonOwner() {
doReturnViewFromReadWriteEval(supplyKeyForCache(0, REPL), rw(fmapR1), rw(fmapR2));
}
public void testReplReturnViewFromReadWriteEvalOnOwner() {
doReturnViewFromReadWriteEval(supplyKeyForCache(1, REPL), rw(fmapR1), rw(fmapR2));
}
public void testDistReturnViewFromReadWriteEvalOnNonOwner() {
doReturnViewFromReadWriteEval(supplyKeyForCache(0, DIST), rw(fmapD1), rw(fmapD2));
}
public void testDistReturnViewFromReadWriteEvalOnOwner() {
doReturnViewFromReadWriteEval(supplyKeyForCache(1, DIST), rw(fmapD1), rw(fmapD2));
}
<K> void doReturnViewFromReadWriteEval(Supplier<K> keySupplier,
ReadWriteMap<K, String> readMap, ReadWriteMap<K, String> writeMap) {
K k = keySupplier.get();
assertReadWriteViewEmpty(k, await(readMap.eval(k, returnReadWriteView())));
assertReadWriteViewEquals(k, "one", await(writeMap.eval(k, setOneReadWrite())));
assertReadWriteViewEquals(k, "one", await(readMap.eval(k, returnReadWriteView())));
assertReadWriteViewEquals(k, "uno", await(writeMap.eval(k, "uno", setValueReturnView())));
assertReadWriteViewEquals(k, "uno", await(readMap.eval(k, returnReadWriteView())));
}
private <K> SerializableFunction<ReadWriteEntryView<K, String>, ReadWriteEntryView<K, String>> setOneReadWrite() {
return rw -> {
rw.set("one");
return rw;
};
}
private void assumeNonTransactional() {
SkipTestNG.skipIf(transactional == Boolean.TRUE,
"Transactions use SimpleClusteredVersions, not NumericVersions, and user is not supposed to modify those");
}
}
| 26,840
| 42.643902
| 131
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalL1Test.java
|
package org.infinispan.functional;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import java.util.function.Function;
import org.infinispan.Cache;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.marshall.core.MarshallableFunctions;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.functional.impl.WriteOnlyMapImpl;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "functional.FunctionalL1Test")
public class FunctionalL1Test extends AbstractFunctionalOpTest {
@Override
protected void configureCache(ConfigurationBuilder builder) {
super.configureCache(builder);
if (builder.clustering().cacheMode().isDistributed()) {
builder.clustering().l1().enable();
}
}
@Test(dataProvider = "owningModeAndWriteMethod")
public void testEntryInvalidated(boolean isOwner, WriteMethod method) {
Cache<Object, String> primary = cache(isOwner ? 0 : 2, DIST);
Cache<Object, String> backup = cache(1, DIST);
Cache<Object, String> reader = cache(3, DIST);
Cache<Object, String> nonOwner = cache(isOwner ? 2 : 0, DIST);
Object KEY = getKeyForCache(primary, backup);
primary.put(KEY, "value");
assertNoEntry(reader, KEY);
assertEquals("value", reader.get(KEY));
assertEntry(primary, KEY, "value", false);
assertEntry(backup, KEY, "value", false);
assertEntry(reader, KEY, "value", true);
assertNoEntry(nonOwner, KEY);
FunctionalMapImpl<Object, String> functionalMap = FunctionalMapImpl.create(this.<Object, String>cache(0, DIST).getAdvancedCache());
FunctionalMap.WriteOnlyMap<Object, String> wo = WriteOnlyMapImpl.create(functionalMap);
FunctionalMap.ReadWriteMap<Object, String> rw = ReadWriteMapImpl.create(functionalMap);
Function<ReadEntryView<Object, String>, String> readFunc = MarshallableFunctions.returnReadOnlyFindOrNull();
method.eval(KEY, wo, rw, readFunc, (view, nil) -> view.set("value2"), FunctionalL1Test.class);
assertEntry(primary, KEY, "value2", false);
assertEntry(backup, KEY, "value2", false);
assertNoEntry(reader, KEY);
assertNoEntry(nonOwner, KEY);
}
private static void assertNoEntry(Cache<Object, String> cache, Object KEY) {
assertEquals(null, cache.getAdvancedCache().getDataContainer().get(KEY));
}
private static void assertEntry(Cache<Object, String> cache, Object KEY, String expectedValue, boolean isL1) {
InternalCacheEntry<Object, String> ice = cache.getAdvancedCache().getDataContainer().get(KEY);
assertNotNull(ice);
assertEquals(expectedValue, ice.getValue());
assertEquals(ice.toString(), isL1, ice.isL1Entry());
}
}
| 2,985
| 42.911765
| 137
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalEncodingTypeTest.java
|
//package org.infinispan.functional;
//
//import static org.testng.AssertJUnit.assertEquals;
//import static org.testng.AssertJUnit.assertFalse;
//
//import jakarta.transaction.Status;
//import jakarta.transaction.TransactionManager;
//
//import org.infinispan.AdvancedCache;
//import org.infinispan.commons.dataconversion.Encoder;
//import org.infinispan.commons.dataconversion.MediaType;
//import org.infinispan.commons.marshall.proto.RuntimeMarshallableWrapper;
//import org.infinispan.functional.impl.FunctionalMapImpl;
//import org.infinispan.functional.impl.ReadWriteMapImpl;
//import org.infinispan.manager.EmbeddedCacheManager;
//import org.infinispan.marshall.core.EncoderRegistry;
//import org.infinispan.test.fwk.InTransactionMode;
//import org.infinispan.transaction.TransactionMode;
//import org.infinispan.util.concurrent.CompletionStages;
//import org.testng.annotations.Test;
//
//@Test(groups = "functional", testName = "functional.FunctionalEncodingTypeTest")
//public class FunctionalEncodingTypeTest extends FunctionalMapTest {
//
// @Override
// public Object[] factory() {
// return new Object[] {
// new FunctionalEncodingTypeTest().transactional(false),
// new FunctionalEncodingTypeTest().transactional(true)
// };
// }
//
// @Override
// protected AdvancedCache<?, ?> getAdvancedCache(EmbeddedCacheManager cm, String cacheName) {
// AdvancedCache<?, ?> cache = super.getAdvancedCache(cm, cacheName);
// ensureEncoders(cache);
// return cache.withEncoding(TestKeyEncoder.class, TestValueEncoder.class);
// }
//
// private void ensureEncoders(AdvancedCache<?, ?> cache) {
// EncoderRegistry encoderRegistry = cache.getComponentRegistry().getComponent(EncoderRegistry.class);
// if (!encoderRegistry.isRegistered(TestKeyEncoder.class)) {
// encoderRegistry.registerEncoder(new TestKeyEncoder());
// encoderRegistry.registerEncoder(new TestValueEncoder());
// encoderRegistry.registerEncoder(new UserType1Encoder());
// encoderRegistry.registerEncoder(new UserType2Encoder());
// }
// }
//
// @InTransactionMode(TransactionMode.TRANSACTIONAL)
// public void testDifferentEncoders() throws Exception {
// AdvancedCache<UserType<String>, UserType<String>> ac1 = (AdvancedCache<UserType<String>, UserType<String>>) advancedCache(0).withEncoding(UserType1Encoder.class, UserType1Encoder.class);
// AdvancedCache<UserType<String>, UserType<String>> ac2 = (AdvancedCache<UserType<String>, UserType<String>>) advancedCache(0).withEncoding(UserType2Encoder.class, UserType2Encoder.class);
// FunctionalMap.ReadWriteMap<UserType<String>, UserType<String>> rw1 = ReadWriteMapImpl.create(FunctionalMapImpl.create(ac1));
// FunctionalMap.ReadWriteMap<UserType<String>, UserType<String>> rw2 = ReadWriteMapImpl.create(FunctionalMapImpl.create(ac2));
//
// assertEquals(0, ac1.size());
// TransactionManager tm = tm(0);
// tm.begin();
// try {
// CompletionStages.join(rw1.eval(new UserType<>(1, "key"), view -> {
// assertFalse(view.find().isPresent());
// view.set(new UserType<>(1, "value"));
// return null;
// }));
// CompletionStages.join(rw2.eval(new UserType<>(2, "key"), view -> {
// UserType<String> value = view.find().orElseThrow(() -> new AssertionError());
// assertEquals(2, value.type);
// assertEquals("value", value.instance);
// view.set(new UserType<>(2, "value2"));
// return null;
// }));
// UserType<String> value2 = ac1.get(new UserType<>(1, "key"));
// assertEquals(1, value2.type);
// assertEquals("value2", value2.instance);
// } finally {
// if (tm.getStatus() == Status.STATUS_ACTIVE) {
// tm.commit();
// } else {
// tm.rollback();
// }
// }
// assertEquals(1, ac1.size());
// UserType<String> value2 = ac2.get(new UserType<>(2, "key"));
// assertEquals(2, value2.type);
// assertEquals("value2", value2.instance);
// }
//
// static class TestKeyEncoder implements Encoder {
// private static final short ID = 42;
//
// @Override
// public Object toStorage(Object content) {
// return content == null ? null : new RuntimeMarshallableWrapper(content);
// }
//
// @Override
// public Object fromStorage(Object content) {
// return content == null ? null : ((RuntimeMarshallableWrapper) content).get();
// }
//
// @Override
// public boolean isStorageFormatFilterable() {
// return false;
// }
//
// @Override
// public MediaType getStorageFormat() {
// return MediaType.APPLICATION_OBJECT;
// }
//
// @Override
// public short id() {
// return ID;
// }
// }
//
// static class TestValueEncoder implements Encoder {
//
// private static final short ID = 43;
//
// @Override
// public Object toStorage(Object content) {
// return content == null ? null : new RuntimeMarshallableWrapper(content);
// }
//
// @Override
// public Object fromStorage(Object content) {
// return content == null ? null : ((RuntimeMarshallableWrapper) content).get();
// }
//
// @Override
// public boolean isStorageFormatFilterable() {
// return false;
// }
//
// @Override
// public MediaType getStorageFormat() {
// return MediaType.APPLICATION_OBJECT;
// }
//
// @Override
// public short id() {
// return ID;
// }
// }
//
// // Not serializable!
// static final class UserType<T> {
// public final int type;
// public final T instance;
//
// UserType(int type, T instance) {
// this.type = type;
// this.instance = instance;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// UserType<?> userType = (UserType<?>) o;
// return type == userType.type && instance.equals(userType.instance);
// }
//
// @Override
// public int hashCode() {
// return instance.hashCode();
// }
//
// @Override
// public String toString() {
// return "UserType#" + type + "#" + instance;
// }
// }
//
// static class UserType1Encoder implements Encoder {
// @Override
// public Object toStorage(Object content) {
// UserType<?> ut = (UserType<?>) content;
// assert ut.type == 1;
// return content == null ? null : ut.instance;
// }
//
// @Override
// public Object fromStorage(Object content) {
// return content == null ? null : new UserType<>(1, content);
// }
//
// @Override
// public boolean isStorageFormatFilterable() {
// return false;
// }
//
// @Override
// public MediaType getStorageFormat() {
// return MediaType.APPLICATION_OBJECT;
// }
//
// @Override
// public short id() {
// return (short) 44;
// }
// }
//
// static class UserType2Encoder implements Encoder {
// @Override
// public Object toStorage(Object content) {
// UserType<?> ut = (UserType<?>) content;
// assert ut.type == 2;
// return content == null ? null : ut.instance;
// }
//
// @Override
// public Object fromStorage(Object content) {
// return content == null ? null : new UserType<>(2, content);
// }
//
// @Override
// public boolean isStorageFormatFilterable() {
// return false;
// }
//
// @Override
// public MediaType getStorageFormat() {
// return MediaType.APPLICATION_OBJECT;
// }
//
// @Override
// public short id() {
// return (short) 45;
// }
// }
//}
| 7,979
| 32.813559
| 194
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/TestFunctionalInterfaces.java
|
package org.infinispan.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.function.Consumer;
import java.util.function.Function;
import org.infinispan.functional.EntryView.ReadWriteEntryView;
import org.infinispan.functional.EntryView.WriteEntryView;
import org.infinispan.commons.marshall.Externalizer;
import org.infinispan.commons.marshall.SerializeWith;
public class TestFunctionalInterfaces {
@SerializeWith(value = SetConstantOnReadWrite.Externalizer0.class)
public static final class SetConstantOnReadWrite<K>
implements Function<ReadWriteEntryView<K, String>, Void> {
final String constant;
public SetConstantOnReadWrite(String constant) {
this.constant = constant;
}
@Override
public Void apply(ReadWriteEntryView<K, String> rw) {
rw.set(constant);
return null;
}
public static final class Externalizer0
implements Externalizer<SetConstantOnReadWrite<?>> {
@Override
public void writeObject(ObjectOutput output, SetConstantOnReadWrite<?> object)
throws IOException {
output.writeUTF(object.constant);
}
@Override
public SetConstantOnReadWrite<?> readObject(ObjectInput input)
throws IOException, ClassNotFoundException {
String constant = input.readUTF();
return new SetConstantOnReadWrite<>(constant);
}
}
}
@SerializeWith(value = SetConstantOnWriteOnly.Externalizer0.class)
public static final class SetConstantOnWriteOnly<K> implements Consumer<WriteEntryView<K, String>> {
final String constant;
public SetConstantOnWriteOnly(String constant) {
this.constant = constant;
}
@Override
public void accept(WriteEntryView<K, String> wo) {
wo.set(constant);
}
public static final class Externalizer0 implements Externalizer<SetConstantOnWriteOnly> {
@Override
public void writeObject(ObjectOutput output, SetConstantOnWriteOnly object)
throws IOException {
output.writeUTF(object.constant);
}
@Override
public SetConstantOnWriteOnly readObject(ObjectInput input)
throws IOException, ClassNotFoundException {
String constant = input.readUTF();
return new SetConstantOnWriteOnly(constant);
}
}
}
}
| 2,501
| 30.670886
| 103
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalDistributionTest.java
|
package org.infinispan.functional;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.infinispan.AdvancedCache;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.distribution.BlockingInterceptor;
import org.infinispan.functional.FunctionalMap.ReadWriteMap;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.interceptors.impl.EntryWrappingInterceptor;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* @author Krzysztof Sobolewski <Krzysztof.Sobolewski@atende.pl>
*/
@Test(groups = "functional", testName = "functional.FunctionalDistributionTest")
public class FunctionalDistributionTest extends AbstractFunctionalTest {
public FunctionalDistributionTest() {
numNodes = 4;
// we want some non-owners and some secondary owners:
numDistOwners = 2;
/*
* The potential problem arises in async mode: the non-primary owner
* executes, then forwards to the primary owner, which executes and
* forwards to all non-primary owners, including the originator, which
* executes again. In sync mode this does not cause problems because the
* second invocation on the originator happens before the first is
* committed so it receives the same input data. Not so in async mode.
*/
isSync = false;
}
@BeforeClass
@Override
public void createBeforeClass() throws Throwable {
super.createBeforeClass();
}
public void testDistributionFromPrimaryOwner() throws Exception {
Object key = "testDistributionFromPrimaryOwner";
doTestDistribution(key, cacheManagers.stream()
.map(cm -> cm.<Object, Integer>getCache(DIST).getAdvancedCache())
.filter(cache -> cache.getDistributionManager().getCacheTopology().getDistribution(key).isPrimary())
.findAny()
.get());
}
public void testDistributionFromSecondaryOwner() throws Exception {
Object key = "testDistributionFromSecondaryOwner";
doTestDistribution(key, cacheManagers.stream()
.map(cm -> cm.<Object, Integer>getCache(DIST).getAdvancedCache())
// owner...
.filter(cache -> cache.getDistributionManager().getCacheTopology().getDistribution(key).isWriteBackup())
.findAny()
.get());
}
public void testDistributionFromNonOwner() throws Exception {
Object key = "testDistributionFromNonOwner";
doTestDistribution(key, cacheManagers.stream()
.map(cm -> cm.<Object, Integer>getCache(DIST).getAdvancedCache())
.filter(cache -> !cache.getDistributionManager().getCacheTopology().isWriteOwner(key))
.findAny()
.get());
}
private void doTestDistribution(Object key, AdvancedCache<Object, Integer> originator) throws Exception {
ReadWriteMap<Object, Integer> rw = ReadWriteMapImpl.create(FunctionalMapImpl.create(originator));
// with empty cache:
iterate(key, rw, 1);
// again:
iterate(key, rw, 2);
}
private void iterate(Object key, ReadWriteMap<Object, Integer> rw, int expectedValue) throws Exception {
List<AdvancedCache<Object, Object>> owners = cacheManagers
.stream().map(cm -> cm.getCache(DIST).getAdvancedCache())
.filter(cache -> cache.getDistributionManager().getCacheTopology().isWriteOwner(key))
.collect(Collectors.toList());
CyclicBarrier barrier = new CyclicBarrier(numDistOwners + 1);
for (AdvancedCache cache : owners) {
BlockingInterceptor bi = new BlockingInterceptor<>(barrier, ReadWriteKeyCommand.class, true, false);
cache.getAsyncInterceptorChain().addInterceptorBefore(bi, EntryWrappingInterceptor.class);
}
// While the command execution could be async the BlockingInterceptor would block us on primary owner == originator
// On backup == originator the blocking interceptor is not hit until
Future<Void> f = fork(() -> rw.eval(key, entry -> entry.set(entry.find().orElse(0) + 1)).join());
barrier.await(10, TimeUnit.SECONDS);
for (AdvancedCache cache : owners) {
cache.getAsyncInterceptorChain().findInterceptorWithClass(BlockingInterceptor.class).suspend(true);
}
barrier.await(10, TimeUnit.SECONDS);
for (AdvancedCache cache : owners) {
cache.getAsyncInterceptorChain().removeInterceptor(BlockingInterceptor.class);
}
f.get(10, TimeUnit.SECONDS);
// we want to ensure that each of the owners executes the function only once:
Assert.assertEquals(owners.stream()
.map(cache -> cache.getDataContainer().get(key).getValue())
.collect(Collectors.toList()),
Collections.nCopies(numDistOwners, expectedValue));
}
}
| 5,093
| 41.806723
| 121
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/FunctionalTxInMemoryTest.java
|
package org.infinispan.functional;
import static org.infinispan.commons.test.Exceptions.expectExceptionNonStrict;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Collections;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import java.util.stream.IntStream;
import jakarta.transaction.Status;
import jakarta.transaction.TransactionManager;
import org.infinispan.commons.CacheException;
import org.infinispan.marshall.core.MarshallableFunctions;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.concurrent.IsolationLevel;
import org.infinispan.util.function.SerializableFunction;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "functional.FunctionalTxInMemoryTest")
public class FunctionalTxInMemoryTest extends FunctionalInMemoryTest {
private static final int NUM_KEYS = 2;
private static final Integer[] INT_KEYS = IntStream.range(0, NUM_KEYS).boxed().toArray(Integer[]::new);
TransactionManager tm;
@Override
public Object[] factory() {
return new Object[]{
new FunctionalTxInMemoryTest().transactional(true).lockingMode(LockingMode.OPTIMISTIC).isolationLevel(IsolationLevel.READ_COMMITTED),
new FunctionalTxInMemoryTest().transactional(true).lockingMode(LockingMode.PESSIMISTIC).isolationLevel(IsolationLevel.READ_COMMITTED),
new FunctionalTxInMemoryTest().transactional(true).lockingMode(LockingMode.PESSIMISTIC).isolationLevel(IsolationLevel.REPEATABLE_READ),
};
}
@Override
protected void createCacheManagers() throws Throwable {
super.createCacheManagers();
tm = TestingUtil.extractComponentRegistry(cache(0)).getComponent(TransactionManager.class);
}
@Test(dataProvider = "owningModeAndReadMethod")
public void testReadLoads(boolean isOwner, ReadMethod method) throws Exception {
Object[] keys = getKeys(isOwner, NUM_KEYS);
for (Object key : keys) {
cache(0, DIST).put(key, key);
}
tm.begin();
for (Object key : keys) {
assertEquals(method.eval(key, ro, e -> {
assertTrue(e.find().isPresent());
assertEquals(e.get(), e.key());
return "OK";
}), "OK");
}
tm.commit();
}
@Test(dataProvider = "readMethods")
public void testReadLoadsLocal(ReadMethod method) throws Exception {
Integer[] keys = INT_KEYS;
for (Integer key : keys) {
cache(0).put(key, key);
}
tm.begin();
for (Integer key : keys) {
assertEquals(method.eval(key, lro, e -> {
assertTrue(e.find().isPresent());
assertEquals(e.get(), e.key());
return "OK";
}), "OK");
}
tm.commit();
}
@Test(dataProvider = "owningModeAndReadMethod")
public void testReadsAfterMods(boolean isOwner, ReadMethod method) throws Exception {
Object KEY = getKey(isOwner, DIST);
cache(0, DIST).put(KEY, "a");
tm.begin();
assertEquals("a", rw.eval(KEY, append("b")).join());
assertEquals("ab", rw.evalMany(Collections.singleton(KEY), append("c")).findAny().get());
assertEquals(null, rw.eval("otherKey", append("d")).join());
assertEquals("abc", method.eval(KEY, ro, MarshallableFunctions.returnReadOnlyFindOrNull()));
tm.commit();
}
@Test(dataProvider = "owningModeAndReadWrites")
public void testReadWriteAfterMods(boolean isOwner, WriteMethod method) throws Exception {
Object KEY = getKey(isOwner, DIST);
cache(0, DIST).put(KEY, "a");
tm.begin();
assertEquals("a", rw.eval(KEY, append("b")).join());
assertEquals("ab", rw.evalMany(Collections.singleton(KEY), append("c")).findAny().get());
assertEquals(null, rw.eval("otherKey", append("d")).join());
assertEquals("abc", method.eval(KEY, wo, rw,
MarshallableFunctions.returnReadOnlyFindOrNull(),
(e, prev) -> {}, getClass()));
tm.commit();
}
public void testNonFunctionalReadsAfterMods() throws Exception {
Object KEY = getKey(false, DIST);
cache(0, DIST).put(KEY, "a");
tm.begin();
assertEquals("a", rw.eval(KEY, append("b")).join());
assertEquals("ab", cache.get(KEY));
// try second time to make sure the modification is not applied twice
assertEquals("ab", cache.get(KEY));
tm.commit();
tm.begin();
assertEquals("ab", rw.evalMany(Collections.singleton(KEY), append("c")).findAny().get());
assertEquals("abc", cache.put(KEY, "abcd"));
tm.commit();
tm.begin();
assertEquals("abcd", cache.get(KEY));
tm.commit();
tm.begin();
wo.eval(KEY, "x", MarshallableFunctions.setValueConsumer()).join();
assertEquals("x", cache.putIfAbsent(KEY, "otherValue"));
tm.commit();
tm.begin();
wo.eval(KEY, MarshallableFunctions.removeConsumer()).join();
assertNull(cache.putIfAbsent(KEY, "y"));
assertEquals("y", ro.eval(KEY, MarshallableFunctions.returnReadOnlyFindOrNull()).join());
tm.commit();
tm.begin();
assertEquals("y", rw.eval(KEY, "z", MarshallableFunctions.setValueReturnPrevOrNull()).join());
assertTrue(cache.replace(KEY, "z", "a"));
tm.commit();
tm.begin();
assertEquals("a", rw.eval(KEY, append("b")).join());
assertEquals("ab", cache.getAll(Collections.singleton(KEY)).get(KEY));
tm.commit();
}
@Test(dataProvider = "owningModeAndReadWrites")
public void testWriteModsInTxContext(boolean isOwner, WriteMethod method) throws Exception {
Object KEY = getKey(isOwner, DIST);
cache(0, DIST).put(KEY, "a");
tm.begin();
assertEquals("a", cache(0, DIST).put(KEY, "b"));
// read-write operation should execute locally instead
assertEquals("b", method.eval(KEY, null, rw,
EntryView.ReadEntryView::get,
(e, prev) -> e.set(prev + "c"), getClass()));
// make sure that the operation was executed in context
assertEquals("bc", ro.eval(KEY, MarshallableFunctions.returnReadOnlyFindOrNull()).join());
tm.commit();
}
public static SerializableFunction<EntryView.ReadWriteEntryView<Object, String>, String> append(String str) {
return ev -> {
Optional<String> prev = ev.find();
if (prev.isPresent()) {
ev.set(prev.get() + str);
return prev.get();
} else {
ev.set(str);
return null;
}
};
}
@Test(dataProvider = "owningModeAndReadMethod")
public void testReadOnMissingValues(boolean isOwner, ReadMethod method) throws Exception {
testReadOnMissingValues(getKeys(isOwner, NUM_KEYS), ro, method);
}
@Test(dataProvider = "readMethods")
public void testReadOnMissingValuesLocal(ReadMethod method) throws Exception {
testReadOnMissingValues(INT_KEYS, lro, method);
}
private <K> void testReadOnMissingValues(K[] keys, FunctionalMap.ReadOnlyMap<K, String> ro, ReadMethod method) throws Exception {
tm.begin();
for (K key : keys) {
Assert.assertEquals(ro.eval(key, view -> view.find().isPresent()).join(), Boolean.FALSE);
}
tm.commit();
tm.begin();
for (K key : keys) {
expectExceptionNonStrict(CompletionException.class, CacheException.class, NoSuchElementException.class,
() -> method.eval(key, ro, EntryView.ReadEntryView::get));
// The first exception should cause the whole transaction to fail
assertEquals(Status.STATUS_MARKED_ROLLBACK, tm.getStatus());
tm.rollback();
break;
}
if (tm.getStatus() == Status.STATUS_ACTIVE) {
tm.commit();
}
}
private Object[] getKeys(boolean isOwner, int num) {
return IntStream.iterate(0, i -> i + 1)
.mapToObj(i -> "key" + i)
.filter(k -> cache(0, DIST).getAdvancedCache().getDistributionManager().getCacheTopology().isReadOwner(k) == isOwner)
.limit(num).toArray(Object[]::new);
}
}
| 8,283
| 37
| 147
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/stress/ReadOnlyKeyCommandStressTest.java
|
package org.infinispan.functional.stress;
import org.infinispan.Cache;
import org.infinispan.commands.GetAllCommandStressTest;
import org.infinispan.functional.FunctionalMap;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadOnlyMapImpl;
import org.infinispan.test.fwk.InCacheMode;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import static org.testng.AssertJUnit.assertEquals;
@Test(groups = "stress", testName = "functional.stress.ReadOnlyKeyCommandStressTest")
@InCacheMode(CacheMode.DIST_SYNC)
public class ReadOnlyKeyCommandStressTest extends GetAllCommandStressTest {
@Override
protected void workerLogic(Cache<Integer, Integer> cache, Set<Integer> threadKeys, int iteration) {
FunctionalMap.ReadOnlyMap<Integer, Integer> ro = ReadOnlyMapImpl.create(FunctionalMapImpl.create(cache.getAdvancedCache()));
List<CompletableFuture> futures = new ArrayList(threadKeys.size());
for (Integer key : threadKeys) {
futures.add(ro.eval(key, (view -> view.get() + 1)).thenAccept(value -> assertEquals(Integer.valueOf(key + 1), value)));
}
futures.stream().forEach(f -> f.join());
}
}
| 1,342
| 40.96875
| 130
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/distribution/rehash/FunctionalNonTxJoinerBecomingBackupOwnerTest.java
|
package org.infinispan.functional.distribution.rehash;
import org.infinispan.AdvancedCache;
import org.infinispan.distribution.rehash.NonTxJoinerBecomingBackupOwnerTest;
import org.infinispan.functional.decorators.FunctionalAdvancedCache;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.op.TestFunctionalWriteOperation;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "distribution.rehash.FunctionalNonTxJoinerBecomingBackupOwnerTest")
@CleanupAfterMethod
public class FunctionalNonTxJoinerBecomingBackupOwnerTest extends NonTxJoinerBecomingBackupOwnerTest {
@Override
protected <A, B> AdvancedCache<A, B> advancedCache(int i) {
AdvancedCache<A, B> cache = super.advancedCache(i);
return FunctionalAdvancedCache.create(cache);
}
@Override
public void testBackupOwnerJoiningDuringPut() throws Exception {
doTest(TestFunctionalWriteOperation.PUT_CREATE_FUNCTIONAL);
}
@Override
public void testBackupOwnerJoiningDuringPutIfAbsent() throws Exception {
doTest(TestFunctionalWriteOperation.PUT_IF_ABSENT_FUNCTIONAL);
}
@Override
public void testBackupOwnerJoiningDuringReplace() throws Exception {
doTest(TestFunctionalWriteOperation.REPLACE_FUNCTIONAL);
}
@Override
public void testBackupOwnerJoiningDuringReplaceWithPreviousValue() throws Exception {
doTest(TestFunctionalWriteOperation.REPLACE_EXACT_FUNCTIONAL);
}
@Override
public void testBackupOwnerJoiningDuringRemove() throws Exception {
doTest(TestFunctionalWriteOperation.REMOVE_FUNCTIONAL);
}
@Override
public void testBackupOwnerJoiningDuringRemoveWithPreviousValue() throws Exception {
doTest(TestFunctionalWriteOperation.REMOVE_EXACT_FUNCTIONAL);
}
}
| 1,789
| 34.098039
| 107
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/distribution/rehash/FunctionalNonTxBackupOwnerBecomingPrimaryOwnerTest.java
|
package org.infinispan.functional.distribution.rehash;
import org.infinispan.distribution.rehash.NonTxBackupOwnerBecomingPrimaryOwnerTest;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.op.TestFunctionalWriteOperation;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "distribution.rehash.FunctionalNonTxBackupOwnerBecomingPrimaryOwnerTest")
@CleanupAfterMethod
public class FunctionalNonTxBackupOwnerBecomingPrimaryOwnerTest extends NonTxBackupOwnerBecomingPrimaryOwnerTest {
// TODO: Add more tests, e.g. read-write key operation
public void testPrimaryOwnerChangingDuringReplaceBasedOnMeta() throws Exception {
doTest(TestFunctionalWriteOperation.REPLACE_META_FUNCTIONAL);
}
@Override
public void testPrimaryOwnerChangingDuringPut() throws Exception {
doTest(TestFunctionalWriteOperation.PUT_CREATE_FUNCTIONAL);
}
@Override
public void testPrimaryOwnerChangingDuringPutOverwrite() throws Exception {
doTest(TestFunctionalWriteOperation.PUT_OVERWRITE_FUNCTIONAL);
}
@Override
public void testPrimaryOwnerChangingDuringPutIfAbsent() throws Exception {
doTest(TestFunctionalWriteOperation.PUT_IF_ABSENT_FUNCTIONAL);
}
@Override
public void testPrimaryOwnerChangingDuringReplace() throws Exception {
doTest(TestFunctionalWriteOperation.REPLACE_FUNCTIONAL);
}
@Override
public void testPrimaryOwnerChangingDuringRemove() throws Exception {
doTest(TestFunctionalWriteOperation.REMOVE_FUNCTIONAL);
}
@Override
public void testPrimaryOwnerChangingDuringReplaceExact() throws Exception {
doTest(TestFunctionalWriteOperation.REPLACE_EXACT_FUNCTIONAL);
}
@Override
public void testPrimaryOwnerChangingDuringRemoveExact() throws Exception {
doTest(TestFunctionalWriteOperation.REMOVE_EXACT_FUNCTIONAL);
}
}
| 1,888
| 33.981481
| 114
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/distribution/rehash/FunctionalTxTest.java
|
package org.infinispan.functional.distribution.rehash;
import static org.infinispan.test.TestingUtil.withTx;
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.Collection;
import java.util.Collections;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import jakarta.transaction.Transaction;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.distribution.DistributionInfo;
import org.infinispan.functional.EntryView;
import org.infinispan.functional.FunctionalMap;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.statetransfer.DelegatingStateConsumer;
import org.infinispan.statetransfer.StateChunk;
import org.infinispan.statetransfer.StateConsumer;
import org.infinispan.test.MultipleCacheManagersTest;
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.testng.annotations.Test;
@Test(groups = "functional", testName = "functional.distribution.rehash.FunctionalTxTest")
@CleanupAfterMethod
public class FunctionalTxTest extends MultipleCacheManagersTest {
ConfigurationBuilder cb;
ControlledConsistentHashFactory chf;
@Override
protected void createCacheManagers() throws Throwable {
chf = new ControlledConsistentHashFactory.Default(0, 1);
cb = new ConfigurationBuilder();
cb.transaction().transactionMode(TransactionMode.TRANSACTIONAL).useSynchronization(false);
cb.clustering().cacheMode(CacheMode.DIST_SYNC).hash().numSegments(1).consistentHashFactory(chf);
createCluster(cb, 3);
waitForClusterToForm();
}
public void testDoubleIncrementBeforeTopology() throws Exception {
testBeforeTopology((rw, key) -> {
Integer oldValue = rw.eval(key, FunctionalTxTest::increment).join();
rw.eval(key, FunctionalTxTest::increment).join();
return oldValue;
}, 2);
}
public void testDoubleIncrementAfterTopology() throws Exception {
testAfterTopology((rw, key) -> {
Integer oldValue = rw.eval(key, FunctionalTxTest::increment).join();
rw.eval(key, FunctionalTxTest::increment).join();
return oldValue;
}, 2);
}
public void testReadWriteKeyBeforeTopology() throws Exception {
testBeforeTopology((rw, key) -> rw.eval(key, FunctionalTxTest::increment).join(), 1);
}
public void testReadWriteKeyAfterTopology() throws Exception {
testAfterTopology((rw, key) -> rw.eval(key, FunctionalTxTest::increment).join(), 1);
}
public void testReadWriteManyKeysBeforeTopology() throws Exception {
testBeforeTopology((rw, key) -> rw.evalMany(Collections.singleton(key), FunctionalTxTest::increment).findAny().get(), 1);
}
public void testReadWriteManyKeysAfterTopology() throws Exception {
testAfterTopology((rw, key) -> rw.evalMany(Collections.singleton(key), FunctionalTxTest::increment).findAny().get(), 1);
}
public void testReadWriteManyEntriesBeforeTopology() throws Exception {
testBeforeTopology((rw, key) -> rw.evalMany(Collections.singletonMap(key, 1), FunctionalTxTest::add).findAny().get(), 1);
}
public void testReadWriteManyEntriesAfterTopology() throws Exception {
testAfterTopology((rw, key) -> rw.evalMany(Collections.singletonMap(key, 1), FunctionalTxTest::add).findAny().get(), 1);
}
private void testBeforeTopology(BiFunction<FunctionalMap.ReadWriteMap<String, Integer>, String, Integer> op, int expectedIncrement) throws Exception {
cache(0).put("key", 1);
// Blocking on receiver side. We cannot block the StateResponseCommand on the server side since
// the InternalCacheEntries in its state are the same instances of data stored in DataContainer
// - therefore when the command is blocked on sender the command itself would be mutated by applying
// the transaction below.
BlockingStateConsumer bsc2 = TestingUtil.wrapComponent(cache(2), StateConsumer.class, BlockingStateConsumer::new);
tm(2).begin();
FunctionalMap.ReadWriteMap<String, Integer> rw = ReadWriteMapImpl.create(
FunctionalMapImpl.create(this.<String, Integer>cache(2).getAdvancedCache()));
assertEquals(Integer.valueOf(1), op.apply(rw, "key"));
Transaction tx = tm(2).suspend();
chf.setOwnerIndexes(0, 2);
EmbeddedCacheManager cm = createClusteredCacheManager(false, GlobalConfigurationBuilder.defaultClusteredBuilder(),
cb, new TransportFlags());
registerCacheManager(cm);
Future<?> future = fork(() -> {
cache(3);
});
bsc2.await();
DistributionInfo distributionInfo = cache(2).getAdvancedCache().getDistributionManager().getCacheTopology().getDistribution("key");
assertFalse(distributionInfo.isReadOwner());
assertTrue(distributionInfo.isWriteBackup());
tm(2).resume(tx);
tm(2).commit();
bsc2.unblock();
future.get(10, TimeUnit.SECONDS);
InternalCacheEntry<Object, Object> ice = cache(2).getAdvancedCache().getDataContainer().get("key");
assertEquals("Current ICE: " + ice, 1 + expectedIncrement, ice.getValue());
}
private void testAfterTopology(BiFunction<FunctionalMap.ReadWriteMap<String, Integer>, String, Integer> op, int expectedIncrement) throws Exception {
cache(0).put("key", 1);
// Blocking on receiver side. We cannot block the StateResponseCommand on the server side since
// the InternalCacheEntries in its state are the same instances of data stored in DataContainer
// - therefore when the command is blocked on sender the command itself would be mutated by applying
// the transaction below.
BlockingStateConsumer bsc2 = TestingUtil.wrapComponent(cache(2), StateConsumer.class, BlockingStateConsumer::new);
chf.setOwnerIndexes(0, 2);
EmbeddedCacheManager cm = createClusteredCacheManager(false, GlobalConfigurationBuilder.defaultClusteredBuilder(),
cb, new TransportFlags());
registerCacheManager(cm);
Future<?> future = fork(() -> {
cache(3);
});
bsc2.await();
DistributionInfo distributionInfo = cache(2).getAdvancedCache().getDistributionManager().getCacheTopology()
.getDistribution("key");
assertFalse(distributionInfo.isReadOwner());
assertTrue(distributionInfo.isWriteBackup());
withTx(tm(2), () -> {
FunctionalMap.ReadWriteMap<String, Integer> rw = ReadWriteMapImpl.create(
FunctionalMapImpl.create(this.<String, Integer>cache(2).getAdvancedCache()));
assertEquals(Integer.valueOf(1), op.apply(rw, "key"));
return null;
});
bsc2.unblock();
future.get(10, TimeUnit.SECONDS);
InternalCacheEntry<Object, Object> ice = cache(2).getAdvancedCache().getDataContainer().get("key");
assertEquals("Current ICE: " + ice, 1 + expectedIncrement, ice.getValue());
}
private static Integer increment(EntryView.ReadWriteEntryView<String, Integer> view) {
int value = view.find().orElse(0);
view.set(value + 1);
return value;
}
private static Integer add(Integer param, EntryView.ReadWriteEntryView<String, Integer> view) {
int value = view.find().orElse(0);
view.set(value + param);
return value;
}
private static class BlockingStateConsumer extends DelegatingStateConsumer {
private CountDownLatch expectLatch = new CountDownLatch(1);
private CountDownLatch blockLatch = new CountDownLatch(1);
public BlockingStateConsumer(StateConsumer delegate) {
super(delegate);
}
@Override
public CompletionStage<?> applyState(Address sender, int topologyId, Collection<StateChunk> stateChunks) {
expectLatch.countDown();
try {
assertTrue(blockLatch.await(10, TimeUnit.SECONDS));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return super.applyState(sender, topologyId, stateChunks);
}
public void await() {
try {
assertTrue(expectLatch.await(10, TimeUnit.SECONDS));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void unblock() {
blockLatch.countDown();
}
}
}
| 9,298
| 40.699552
| 153
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/decorators/FunctionalAdvancedCache.java
|
package org.infinispan.functional.decorators;
import static org.infinispan.marshall.core.MarshallableFunctions.removeConsumer;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueIfEqualsReturnBoolean;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueMetasConsumer;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueMetasIfAbsentReturnPrevOrNull;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueMetasIfPresentReturnPrevOrNull;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueMetasReturnPrevOrNull;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Function;
import javax.security.auth.Subject;
import jakarta.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
import org.infinispan.AdvancedCache;
import org.infinispan.CacheCollection;
import org.infinispan.CacheSet;
import org.infinispan.CacheStream;
import org.infinispan.LockedStream;
import org.infinispan.batch.BatchContainer;
import org.infinispan.commons.dataconversion.Encoder;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.Wrapper;
import org.infinispan.commons.util.AbstractDelegatingCollection;
import org.infinispan.commons.util.AbstractDelegatingSet;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.commons.util.CloseableSpliterator;
import org.infinispan.commons.util.Closeables;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.container.DataContainer;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.context.Flag;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.encoding.DataConversion;
import org.infinispan.eviction.EvictionManager;
import org.infinispan.expiration.ExpirationManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.FunctionalMap.ReadWriteMap;
import org.infinispan.functional.FunctionalMap.WriteOnlyMap;
import org.infinispan.functional.MetaParam.MetaLifespan;
import org.infinispan.functional.MetaParam.MetaMaxIdle;
import org.infinispan.functional.Param.PersistenceMode;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.functional.impl.WriteOnlyMapImpl;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilter;
import org.infinispan.partitionhandling.AvailabilityMode;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.security.AuthorizationManager;
import org.infinispan.stats.Stats;
import org.infinispan.util.concurrent.locks.LockManager;
public final class FunctionalAdvancedCache<K, V> implements AdvancedCache<K, V> {
final AdvancedCache<K, V> cache;
final ConcurrentMap<K, V> map;
final ReadWriteMap<K, V> rw;
final WriteOnlyMap<K, V> wo;
private FunctionalAdvancedCache(ConcurrentMap<K, V> map, AdvancedCache<K, V> cache) {
this.map = map;
this.cache = cache;
FunctionalMapImpl<K, V> fmap = FunctionalMapImpl.create(cache);
this.rw = ReadWriteMapImpl.create(fmap);
this.wo = WriteOnlyMapImpl.create(fmap);
}
public static <K, V> AdvancedCache<K, V> create(AdvancedCache<K, V> cache) {
return new FunctionalAdvancedCache<>(FunctionalConcurrentMap.create(cache), cache);
}
////////////////////////////////////////////////////////////////////////////
@Override
public V put(K key, V value) {
return map.put(key, value);
}
@Override
public V get(Object key) {
return map.get(key);
}
@Override
public V putIfAbsent(K key, V value) {
return map.putIfAbsent(key, value);
}
@Override
public V replace(K key, V value) {
return map.replace(key, value);
}
@Override
public V remove(Object key) {
return map.remove(key);
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
return map.replace(key, oldValue, newValue);
}
@Override
public boolean remove(Object key, Object value) {
return map.remove(key, value);
}
@Override
public int size() {
return map.size();
}
@Override
public CompletableFuture<Long> sizeAsync() {
return cache.sizeAsync();
}
@Override
public CacheSet<Entry<K, V>> entrySet() {
return new SetAsCacheSet<>(map.entrySet());
}
@Override
public CacheCollection<V> values() {
return new CollectionAsCacheCollection<>(map.values());
}
@Override
public void clear() {
map.clear();
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
map.putAll(m);
}
@Override
public V put(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
final MetaLifespan metaLifespan = createMetaLifespan(lifespan, lifespanUnit);
final MetaMaxIdle metaMaxIdle = createMetaMaxIdle(maxIdleTime, maxIdleTimeUnit);
return await(rw.eval(key, value, setValueMetasReturnPrevOrNull(metaLifespan, metaMaxIdle)));
}
@Override
public void putAll(Map<? extends K, ? extends V> map, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
final MetaLifespan metaLifespan = createMetaLifespan(lifespan, lifespanUnit);
final MetaMaxIdle metaMaxIdle = createMetaMaxIdle(maxIdleTime, maxIdleTimeUnit);
await(wo.evalMany(map, setValueMetasConsumer(metaLifespan, metaMaxIdle)));
}
@Override
public V putIfAbsent(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
final MetaLifespan metaLifespan = createMetaLifespan(lifespan, lifespanUnit);
final MetaMaxIdle metaMaxIdle = createMetaMaxIdle(maxIdleTime, maxIdleTimeUnit);
return await(rw.eval(key, value, setValueMetasIfAbsentReturnPrevOrNull(metaLifespan, metaMaxIdle)));
}
@Override
public V replace(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
final MetaLifespan metaLifespan = createMetaLifespan(lifespan, lifespanUnit);
final MetaMaxIdle metaMaxIdle = createMetaMaxIdle(maxIdleTime, maxIdleTimeUnit);
return await(rw.eval(key, value, setValueMetasIfPresentReturnPrevOrNull(metaLifespan, metaMaxIdle)));
}
@Override
public boolean replace(K key, V oldValue, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
final MetaLifespan metaLifespan = createMetaLifespan(lifespan, lifespanUnit);
final MetaMaxIdle metaMaxIdle = createMetaMaxIdle(maxIdleTime, maxIdleTimeUnit);
return await(rw.eval(key, value, setValueIfEqualsReturnBoolean(oldValue, metaLifespan, metaMaxIdle)));
}
@Override
public V put(K key, V value, long lifespan, TimeUnit unit) {
final MetaLifespan metaLifespan = createMetaLifespan(lifespan, unit);
return await(rw.eval(key, value, setValueMetasReturnPrevOrNull(metaLifespan)));
}
@Override
public void putAll(Map<? extends K, ? extends V> map, long lifespan, TimeUnit unit) {
final MetaLifespan metaLifespan = createMetaLifespan(lifespan, unit);
await(wo.evalMany(map, setValueMetasConsumer(metaLifespan)));
}
@Override
public V putIfAbsent(K key, V value, long lifespan, TimeUnit unit) {
final MetaLifespan metaLifespan = createMetaLifespan(lifespan, unit);
return await(rw.eval(key, value, setValueMetasIfAbsentReturnPrevOrNull(metaLifespan)));
}
@Override
public V replace(K key, V value, long lifespan, TimeUnit unit) {
final MetaLifespan metaLifespan = createMetaLifespan(lifespan, unit);
return await(rw.eval(key, value, setValueMetasIfPresentReturnPrevOrNull(metaLifespan)));
}
@Override
public boolean replace(K key, V oldValue, V value, long lifespan, TimeUnit unit) {
final MetaLifespan metaLifespan = createMetaLifespan(lifespan, unit);
return await(rw.eval(key, value, setValueIfEqualsReturnBoolean(oldValue, metaLifespan)));
}
@Override
public void evict(K key) {
await(wo.withParams(PersistenceMode.SKIP).eval(key, removeConsumer()));
}
@Override
public void putForExternalRead(K key, V value) {
map.putIfAbsent(key, value);
}
private MetaLifespan createMetaLifespan(long lifespan, TimeUnit lifespanUnit) {
return new MetaLifespan(lifespanUnit.toMillis(lifespan));
}
private MetaMaxIdle createMetaMaxIdle(long maxIdleTime, TimeUnit maxIdleTimeUnit) {
return new MetaMaxIdle(maxIdleTimeUnit.toMillis(maxIdleTime));
}
////////////////////////////////////////////////////////////////////////////
@Override
public RpcManager getRpcManager() {
return cache.getRpcManager();
}
@Override
public ComponentRegistry getComponentRegistry() {
return cache.getComponentRegistry();
}
@Override
public AdvancedCache<K, V> getAdvancedCache() {
return cache.getAdvancedCache();
}
@Override
public EmbeddedCacheManager getCacheManager() {
return cache.getCacheManager();
}
@Override
public AdvancedCache<K, V> withFlags(Flag... flags) {
return cache.withFlags(flags);
}
@Override
public AdvancedCache<K, V> withSubject(Subject subject) {
return cache.withSubject(subject);
}
@Override
public Configuration getCacheConfiguration() {
return cache.getCacheConfiguration();
}
@Override
public void stop() {
cache.stop();
}
@Override
public void start() {
cache.start();
}
@Override
public CompletionStage<Boolean> touch(Object key, int segment, boolean touchEvenIfExpired) {
return cache.touch(key, segment, touchEvenIfExpired);
}
@Override
public CompletionStage<Boolean> touch(Object key, boolean touchEvenIfExpired) {
return cache.touch(key, -1, touchEvenIfExpired);
}
////////////////////////////////////////////////////////////////////////////
/**
* @deprecated Since 10.0, will be removed without a replacement
*/
@Deprecated
@Override
public AsyncInterceptorChain getAsyncInterceptorChain() {
return cache.getAsyncInterceptorChain();
}
@Override
public EvictionManager getEvictionManager() {
return null; // TODO: Customise this generated block
}
@Override
public ExpirationManager<K, V> getExpirationManager() {
return null; // TODO: Customise this generated block
}
@Override
public DistributionManager getDistributionManager() {
return null; // TODO: Customise this generated block
}
@Override
public AuthorizationManager getAuthorizationManager() {
return null; // TODO: Customise this generated block
}
@Override
public AdvancedCache<K, V> lockAs(Object lockOwner) {
throw new UnsupportedOperationException("lockAs is not supported with Functional Cache!");
}
@Override
public boolean lock(K... keys) {
return false; // TODO: Customise this generated block
}
@Override
public boolean lock(Collection<? extends K> keys) {
return false; // TODO: Customise this generated block
}
@Override
public BatchContainer getBatchContainer() {
return null; // TODO: Customise this generated block
}
@Override
public DataContainer<K, V> getDataContainer() {
return null; // TODO: Customise this generated block
}
@Override
public TransactionManager getTransactionManager() {
return null; // TODO: Customise this generated block
}
@Override
public LockManager getLockManager() {
return null; // TODO: Customise this generated block
}
@Override
public Stats getStats() {
return null; // TODO: Customise this generated block
}
@Override
public XAResource getXAResource() {
return null; // TODO: Customise this generated block
}
@Override
public ClassLoader getClassLoader() {
return null; // TODO: Customise this generated block
}
@Override
public AdvancedCache<K, V> with(ClassLoader classLoader) {
return null; // TODO: Customise this generated block
}
@Override
public V put(K key, V value, Metadata metadata) {
return null; // TODO: Customise this generated block
}
@Override
public void putAll(Map<? extends K, ? extends V> map, Metadata metadata) {
// TODO: Customise this generated block
}
@Override
public V replace(K key, V value, Metadata metadata) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<CacheEntry<K, V>> replaceAsyncEntry(K key, V value, Metadata metadata) {
return null; // TODO: Customise this generated block
}
@Override
public boolean replace(K key, V oldValue, V newValue, Metadata metadata) {
return false; // TODO: Customise this generated block
}
@Override
public V putIfAbsent(K key, V value, Metadata metadata) {
return null; // TODO: Customise this generated block
}
@Override
public void putForExternalRead(K key, V value, Metadata metadata) {
// TODO: Customise this generated block
}
@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) {
throw new UnsupportedOperationException();
}
@Override
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
throw new UnsupportedOperationException();
}
@Override
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, Metadata metadata) {
throw new UnsupportedOperationException();
}
@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction, Metadata metadata) {
throw new UnsupportedOperationException();
}
@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) {
throw new UnsupportedOperationException();
}
@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit) {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<V> putAsync(K key, V value, Metadata metadata) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<CacheEntry<K, V>> putAsyncEntry(K key, V value, Metadata metadata) {
return null; // TODO: Customise this generated block
}
@Override
public Map<K, V> getAll(Set<?> keys) {
return null; // TODO: Customise this generated block
}
@Override
public CacheEntry<K, V> getCacheEntry(Object key) {
return null; // TODO: Customise this generated block
}
@Override
public Map<K, CacheEntry<K, V>> getAllCacheEntries(Set<?> keys) {
return null; // TODO: Customise this generated block
}
@Override
public Map<K, V> getGroup(String groupName) {
return null; // TODO: Customise this generated block
}
@Override
public void removeGroup(String groupName) {
// TODO: Customise this generated block
}
@Override
public AvailabilityMode getAvailability() {
return null; // TODO: Customise this generated block
}
@Override
public void setAvailability(AvailabilityMode availabilityMode) {
// TODO: Customise this generated block
}
@Override
public CacheSet<CacheEntry<K, V>> cacheEntrySet() {
return null; // TODO: Customise this generated block
}
@Override
public LockedStream<K, V> lockedStream() {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<Boolean> removeLifespanExpired(K key, V value, Long lifespan) {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<Boolean> removeMaxIdleExpired(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public AdvancedCache<?, ?> withEncoding(Class<? extends Encoder> encoder) {
return cache.withEncoding(encoder);
}
@Override
public AdvancedCache<?, ?> withKeyEncoding(Class<? extends Encoder> encoder) {
return cache.withKeyEncoding(encoder);
}
@Override
public AdvancedCache<?, ?> withEncoding(Class<? extends Encoder> keyEncoder, Class<? extends Encoder> valueEncoder) {
return cache.withEncoding(keyEncoder, valueEncoder);
}
@Override
public AdvancedCache<K, V> withWrapping(Class<? extends Wrapper> keyWrapper, Class<? extends Wrapper> valueWrapper) {
return cache.withWrapping(keyWrapper, valueWrapper);
}
@Override
public AdvancedCache<K, V> withWrapping(Class<? extends Wrapper> wrapper) {
return cache.withWrapping(wrapper);
}
@Override
public AdvancedCache<?, ?> withMediaType(String keyMediaType, String valueMediaType) {
return cache.withMediaType(keyMediaType, valueMediaType);
}
@Override
public <K1, V1> AdvancedCache<K1, V1> withMediaType(MediaType keyMediaType, MediaType valueMediaType) {
return cache.withMediaType(keyMediaType, valueMediaType);
}
@Override
public AdvancedCache<K, V> withStorageMediaType() {
return cache.withStorageMediaType();
}
@Override
public DataConversion getKeyDataConversion() {
return cache.getKeyDataConversion();
}
@Override
public DataConversion getValueDataConversion() {
return cache.getValueDataConversion();
}
@Override
public void putForExternalRead(K key, V value, long lifespan, TimeUnit unit) {
// TODO: Customise this generated block
}
@Override
public void putForExternalRead(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
// TODO: Customise this generated block
}
@Override
public ComponentStatus getStatus() {
return null; // TODO: Customise this generated block
}
@Override
public boolean isEmpty() {
return false; // TODO: Customise this generated block
}
@Override
public boolean containsKey(Object key) {
return false; // TODO: Customise this generated block
}
@Override
public boolean containsValue(Object value) {
return false; // TODO: Customise this generated block
}
@Override
public CacheSet<K> keySet() {
return null; // TODO: Customise this generated block
}
@Override
public String getName() {
return null; // TODO: Customise this generated block
}
@Override
public String getVersion() {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> putAsync(K key, V value) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> putAsync(K key, V value, long lifespan, TimeUnit unit) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> putAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data, long lifespan, TimeUnit unit) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<Void> clearAsync() {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> putIfAbsentAsync(K key, V value) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> putIfAbsentAsync(K key, V value, long lifespan, TimeUnit unit) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> putIfAbsentAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<CacheEntry<K, V>> putIfAbsentAsyncEntry(K key, V value, Metadata metadata) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> removeAsync(Object key) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<Boolean> removeAsync(Object key, Object value) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> replaceAsync(K key, V value) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> replaceAsync(K key, V value, long lifespan, TimeUnit unit) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> replaceAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue, long lifespan, TimeUnit unit) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> getAsync(K key) {
return null; // TODO: Customise this generated block
}
@Override
public CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata) {
return null;
}
@Override
public CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata) {
return null;
}
@Override
public CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction, Metadata metadata) {
return null;
}
@Override
public CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) {
return null;
}
@Override
public CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
return null;
}
@Override
public CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, Metadata metadata) {
return null;
}
@Override
public CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
return null;
}
@Override
public CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction) {
return null;
}
@Override
public CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
return null;
}
@Override
public CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
return null;
}
@Override
public boolean startBatch() {
return false; // TODO: Customise this generated block
}
@Override
public void endBatch(boolean successful) {
// TODO: Customise this generated block
}
@Override
public <C> CompletionStage<Void> addListenerAsync(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter) {
return null;
}
@Override
public CompletionStage<Void> addListenerAsync(Object listener) {
// TODO: Customise this generated block
return null;
}
@Override
public CompletionStage<Void> removeListenerAsync(Object listener) {
// TODO: Customise this generated block
return null;
}
@Deprecated
@Override
public Set<Object> getListeners() {
return null; // TODO: Customise this generated block
}
@Override
public <C> CompletionStage<Void> addFilteredListenerAsync(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter, Set<Class<? extends Annotation>> filterAnnotations) {
// TODO: Customise this generated block
return null;
}
@Override
public <C> CompletionStage<Void> addStorageFormatFilteredListenerAsync(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter, Set<Class<? extends Annotation>> filterAnnotations) {
// TODO: Customise this generated block
return null;
}
@Override
public CompletableFuture<CacheEntry<K, V>> removeAsyncEntry(Object key) {
return null; // TODO: Customise this generated block
}
public static <T> T await(CompletableFuture<T> cf) {
try {
return cf.get();
} catch (InterruptedException | ExecutionException e) {
throw new Error(e);
}
}
private static final class SetAsCacheSet<E> extends AbstractDelegatingSet<E> implements CacheSet<E> {
final Set<E> set;
private SetAsCacheSet(Set<E> set) {
this.set = set;
}
@Override
protected Set<E> delegate() {
return set;
}
@Override
public CacheStream<E> stream() {
return null;
}
@Override
public CacheStream<E> parallelStream() {
return null;
}
@Override
public CloseableIterator<E> iterator() {
return Closeables.iterator(set.iterator());
}
@Override
public CloseableSpliterator<E> spliterator() {
return Closeables.spliterator(set.spliterator());
}
@Override
public String toString() {
return "SetAsCacheSet{" +
"set=" + set +
'}';
}
}
private static class CollectionAsCacheCollection<E> extends AbstractDelegatingCollection<E> implements CacheCollection<E> {
private final Collection<E> col;
public CollectionAsCacheCollection(Collection<E> col) {
this.col = col;
}
@Override
protected Collection<E> delegate() {
return col;
}
@Override
public CloseableIterator<E> iterator() {
return Closeables.iterator(col.iterator());
}
@Override
public CloseableSpliterator<E> spliterator() {
return Closeables.spliterator(col.spliterator());
}
@Override
public CacheStream<E> stream() {
return null;
}
@Override
public CacheStream<E> parallelStream() {
return null;
}
}
}
| 31,845
| 31.89876
| 247
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/decorators/FunctionalConcurrentMap.java
|
package org.infinispan.functional.decorators;
import static org.infinispan.marshall.core.MarshallableFunctions.removeIfValueEqualsReturnBoolean;
import static org.infinispan.marshall.core.MarshallableFunctions.removeReturnPrevOrNull;
import static org.infinispan.marshall.core.MarshallableFunctions.returnReadOnlyFindIsPresent;
import static org.infinispan.marshall.core.MarshallableFunctions.returnReadOnlyFindOrNull;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueConsumer;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueIfAbsentReturnPrevOrNull;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueIfEqualsReturnBoolean;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueIfPresentReturnPrevOrNull;
import static org.infinispan.marshall.core.MarshallableFunctions.setValueReturnPrevOrNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.infinispan.AdvancedCache;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.functional.FunctionalMap.ReadOnlyMap;
import org.infinispan.functional.FunctionalMap.ReadWriteMap;
import org.infinispan.functional.FunctionalMap.WriteOnlyMap;
import org.infinispan.functional.Listeners.ReadWriteListeners;
import org.infinispan.functional.Listeners.WriteListeners;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadOnlyMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.functional.impl.WriteOnlyMapImpl;
import org.infinispan.stream.CacheCollectors;
/**
* A {@link ConcurrentMap} implementation that uses the operations exposed by
* {@link ReadOnlyMap}, {@link WriteOnlyMap} and {@link ReadWriteMap}, and
* validates their usefulness.
*/
public final class FunctionalConcurrentMap<K, V> implements ConcurrentMap<K, V>, FunctionalListeners<K, V> {
final ReadOnlyMap<K, V> readOnly;
final WriteOnlyMap<K, V> writeOnly;
final ReadWriteMap<K, V> readWrite;
// Rudimentary constructor, we'll provide more idiomatic construction
// via main Infinispan class which is still to be defined
private FunctionalConcurrentMap(FunctionalMapImpl<K, V> map) {
this.readOnly = ReadOnlyMapImpl.create(map);
this.writeOnly = WriteOnlyMapImpl.create(map);
this.readWrite = ReadWriteMapImpl.create(map);
}
public static <K, V> FunctionalConcurrentMap<K, V> create(AdvancedCache<K, V> cache) {
return new FunctionalConcurrentMap<>(FunctionalMapImpl.create(cache));
}
@Override
public ReadWriteListeners<K, V> readWriteListeners() {
return readWrite.listeners();
}
@Override
public WriteListeners<K, V> writeOnlyListeners() {
return writeOnly.listeners();
}
@Override
public int size() {
return (int) readOnly.keys().count();
}
@Override
public boolean isEmpty() {
return !readOnly.keys().findAny().isPresent();
}
@Override
public boolean containsKey(Object key) {
return await(readOnly.eval(toK(key), returnReadOnlyFindIsPresent()));
}
@Override
public boolean containsValue(Object value) {
return readOnly.entries().anyMatch(ro -> ro.get().equals(value));
}
@Override
public V get(Object key) {
return await(readOnly.eval(toK(key), returnReadOnlyFindOrNull()));
}
@SuppressWarnings("unchecked")
private K toK(Object key) {
return (K) key;
}
@SuppressWarnings("unchecked")
private V toV(Object value) {
return (V) value;
}
@Override
public V put(K key, V value) {
return await(readWrite.eval(toK(key), value, setValueReturnPrevOrNull()));
}
@Override
public V remove(Object key) {
return await(readWrite.eval(toK(key), removeReturnPrevOrNull()));
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
await(writeOnly.evalMany(m, setValueConsumer()));
}
@Override
public void clear() {
await(writeOnly.truncate());
}
@Override
public Set<K> keySet() {
return readOnly.keys().collect(CacheCollectors.serializableCollector(() -> Collectors.toSet()));
}
@Override
public Collection<V> values() {
return readOnly.entries().collect(ArrayList::new, (l, v) -> l.add(v.get()), ArrayList::addAll);
}
@Override
public Set<Entry<K, V>> entrySet() {
return readOnly.entries().collect(HashSet::new, (s, ro) ->
s.add(new FunctionalMapEntry<>(ro, writeOnly)), HashSet::addAll);
}
@Override
public V putIfAbsent(K key, V value) {
return await(readWrite.eval(toK(key), value, setValueIfAbsentReturnPrevOrNull()));
}
@Override
public boolean remove(Object key, Object value) {
return await(readWrite.eval(toK(key), toV(value), removeIfValueEqualsReturnBoolean()));
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
return await(readWrite.eval(toK(key), newValue, setValueIfEqualsReturnBoolean(oldValue)));
}
@Override
public V replace(K key, V value) {
return await(readWrite.eval(toK(key), value, setValueIfPresentReturnPrevOrNull()));
}
public static <T> T await(CompletableFuture<T> cf) {
try {
return cf.get();
} catch (InterruptedException | ExecutionException e) {
throw new Error(e);
}
}
private static final class FunctionalMapEntry<K, V> implements Entry<K, V> {
final ReadEntryView<K, V> view;
final WriteOnlyMap<K, V> writeOnly;
private FunctionalMapEntry(ReadEntryView<K, V> view, WriteOnlyMap<K, V> writeOnly) {
this.view = view;
this.writeOnly = writeOnly;
}
@Override
public K getKey() {
return view.key();
}
@Override
public V getValue() {
return view.get();
}
@Override
public V setValue(V value) {
V prev = view.get();
await(writeOnly.eval(view.key(), value, setValueConsumer()));
return prev;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Entry) {
Entry<?, ?> e = (Entry<?, ?>) o;
if (Objects.equals(view.key(), e.getKey()) &&
Objects.equals(view.get(), e.getValue()))
return true;
}
return false;
}
@Override
public int hashCode() {
return view.hashCode();
}
@Override
public String toString() {
return "FunctionalMapEntry{" +
"view=" + view +
'}';
}
}
}
| 6,930
| 30.361991
| 108
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/decorators/FunctionalListeners.java
|
package org.infinispan.functional.decorators;
import org.infinispan.functional.Listeners.ReadWriteListeners;
import org.infinispan.functional.Listeners.WriteListeners;
public interface FunctionalListeners<K, V> {
ReadWriteListeners<K, V> readWriteListeners();
WriteListeners<K, V> writeOnlyListeners();
}
| 313
| 30.4
| 62
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/impl/MetaParamsTest.java
|
package org.infinispan.functional.impl;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Optional;
import org.infinispan.container.versioning.NumericVersion;
import org.infinispan.functional.MetaParam.MetaCreated;
import org.infinispan.functional.MetaParam.MetaEntryVersion;
import org.infinispan.functional.MetaParam.MetaLastUsed;
import org.infinispan.functional.MetaParam.MetaLifespan;
import org.infinispan.functional.MetaParam.MetaMaxIdle;
import org.testng.annotations.Test;
/**
* Unit test for metadata parameters collection.
*/
@Test(groups = "functional", testName = "functional.impl.MetaParamsTest")
public class MetaParamsTest {
public void testEmptyMetaParamsFind() {
MetaParams metas = MetaParams.empty();
assertTrue(metas.isEmpty());
assertEquals(0, metas.size());
assertFalse(metas.find(MetaLifespan.class).isPresent());
assertFalse(metas.find(MetaEntryVersion.class).isPresent());
assertFalse(metas.find(MetaMaxIdle.class).isPresent());
}
@Test
public void testAddFindMetaParam() {
MetaParams metas = MetaParams.empty();
MetaLifespan lifespan = new MetaLifespan(1000);
metas.add(lifespan);
assertFalse(metas.isEmpty());
assertEquals(1, metas.size());
Optional<MetaLifespan> lifespanFound = metas.find(MetaLifespan.class);
assertEquals(new MetaLifespan(1000), lifespanFound.get());
assertEquals(1000, metas.find(MetaLifespan.class).get().get().longValue());
assertFalse(new MetaLifespan(900).equals(lifespanFound.get()));
metas.add(new MetaLifespan(900));
assertFalse(metas.isEmpty());
assertEquals(1, metas.size());
assertEquals(Optional.of(new MetaLifespan(900)), metas.find(lifespan.getClass()));
}
@Test
public void testAddFindMultipleMetaParams() {
MetaParams metas = MetaParams.empty();
metas.addMany(new MetaLifespan(1000), new MetaMaxIdle(1000), new MetaEntryVersion(new NumericVersion(12345)));
assertFalse(metas.isEmpty());
assertEquals(3, metas.size());
Optional<MetaMaxIdle> maxIdle = metas.find(MetaMaxIdle.class);
Optional<MetaEntryVersion> entryVersion = metas.find(MetaEntryVersion.class);
assertEquals(Optional.of(new MetaMaxIdle(1000)), maxIdle);
assertFalse(900 == maxIdle.get().get().longValue());
assertEquals(new MetaEntryVersion(new NumericVersion(12345)), entryVersion.get());
assertFalse(new MetaEntryVersion(new NumericVersion(23456)).equals(entryVersion.get()));
}
@Test
public void testReplaceFindMultipleMetaParams() {
MetaParams metas = MetaParams.empty();
metas.addMany(new MetaLifespan(1000), new MetaMaxIdle(1000), new MetaEntryVersion(new NumericVersion(12345)));
assertFalse(metas.isEmpty());
assertEquals(3, metas.size());
metas.addMany(new MetaLifespan(2000), new MetaMaxIdle(2000));
assertFalse(metas.isEmpty());
assertEquals(3, metas.size());
assertEquals(Optional.of(new MetaMaxIdle(2000)), metas.find(MetaMaxIdle.class));
assertEquals(Optional.of(new MetaLifespan(2000)), metas.find(MetaLifespan.class));
assertEquals(Optional.of(new MetaEntryVersion(new NumericVersion(12345))),
metas.find(MetaEntryVersion.class));
}
@Test
public void testConstructors() {
MetaParams metasOf1 = MetaParams.of(new MetaCreated(1000));
assertFalse(metasOf1.isEmpty());
assertEquals(1, metasOf1.size());
MetaParams metasOf2 = MetaParams.of(new MetaCreated(1000), new MetaLastUsed(2000));
assertFalse(metasOf2.isEmpty());
assertEquals(2, metasOf2.size());
MetaParams metasOf4 = MetaParams.of(
new MetaCreated(1000), new MetaLastUsed(2000), new MetaLifespan(3000), new MetaMaxIdle(4000));
assertFalse(metasOf4.isEmpty());
assertEquals(4, metasOf4.size());
}
@Test
public void testDuplicateParametersOnConstruction() {
MetaEntryVersion versionParam1 = new MetaEntryVersion(new NumericVersion(100));
MetaEntryVersion versionParam2 = new MetaEntryVersion(new NumericVersion(200));
MetaParams metas = MetaParams.of(versionParam1, versionParam2);
assertEquals(1, metas.size());
assertEquals(Optional.of(new MetaEntryVersion(new NumericVersion(200))),
metas.find(MetaEntryVersion.class));
}
@Test
public void testDuplicateParametersOnAdd() {
MetaEntryVersion versionParam1 = new MetaEntryVersion(new NumericVersion(100));
MetaParams metas = MetaParams.of(versionParam1);
assertEquals(1, metas.size());
assertEquals(Optional.of(new MetaEntryVersion(new NumericVersion(100))),
metas.find(MetaEntryVersion.class));
MetaEntryVersion versionParam2 = new MetaEntryVersion(new NumericVersion(200));
metas.add(versionParam2);
assertEquals(1, metas.size());
assertEquals(Optional.of(new MetaEntryVersion(new NumericVersion(200))),
metas.find(MetaEntryVersion.class));
MetaEntryVersion versionParam3 = new MetaEntryVersion(new NumericVersion(300));
MetaEntryVersion versionParam4 = new MetaEntryVersion(new NumericVersion(400));
metas.addMany(versionParam3, versionParam4);
assertEquals(1, metas.size());
assertEquals(Optional.of(new MetaEntryVersion(new NumericVersion(400))),
metas.find(MetaEntryVersion.class));
}
}
| 5,483
| 42.52381
| 116
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/persistence/FunctionalPersistenceTest.java
|
package org.infinispan.functional.persistence;
import java.lang.reflect.Method;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.SystemException;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.functional.decorators.FunctionalAdvancedCache;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.persistence.CacheLoaderFunctionalTest;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "functional.persistence.FunctionalPersistenceTest")
public class FunctionalPersistenceTest extends CacheLoaderFunctionalTest {
@Factory
public Object[] factory() {
return new Object[]{
new FunctionalPersistenceTest().segmented(true),
new FunctionalPersistenceTest().segmented(false),
};
}
@Override
protected ConfigurationBuilder getConfiguration() {
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.persistence()
.addStore(DummyInMemoryStoreConfigurationBuilder.class)
.storeName(this.getClass().getName()); // in order to use the same store
return cfg;
}
@Override
protected Cache<String, String> getCache(EmbeddedCacheManager cm) {
Cache<String, String> cache = super.getCache(cm);
return FunctionalAdvancedCache.create(cache.getAdvancedCache());
}
@Override
protected Cache<String, String> getCache(EmbeddedCacheManager cm, String name) {
Cache<String, String> cache = super.getCache(cm, name);
return FunctionalAdvancedCache.create(cache.getAdvancedCache());
}
@Override @Test(enabled = false, description = "Transactional support not yet in place")
public void testDuplicatePersistence(Method m) throws Exception {
super.testDuplicatePersistence(m);
}
@Override @Test(enabled = false, description = "Transactional support not yet in place")
public void testNullFoundButLoaderReceivedValueLaterInTransaction() throws SystemException, NotSupportedException {
super.testNullFoundButLoaderReceivedValueLaterInTransaction();
}
@Override @Test(enabled = false, description = "Transactional support not yet in place")
public void testPreloading() throws Exception {
super.testPreloading();
}
@Override @Test(enabled = false, description = "Transactional support not yet in place")
public void testPreloadingWithEviction() throws Exception {
super.testPreloadingWithEviction();
}
@Override @Test(enabled = false, description = "Transactional support not yet in place")
public void testPreloadingWithEvictionAndOneMaxEntry() throws Exception {
super.testPreloadingWithEvictionAndOneMaxEntry();
}
@Override @Test(enabled = false, description = "Transactional support not yet in place")
public void testPreloadingWithoutAutoCommit() throws Exception {
super.testPreloadingWithoutAutoCommit();
}
@Override @Test(enabled = false, description = "Transactional support not yet in place")
public void testTransactionalWrites() throws Exception {
super.testTransactionalWrites();
}
@Override @Test(enabled = false, description = "Transactional support not yet in place")
public void testTransactionalReplace(Method m) throws Exception {
super.testTransactionalReplace(m);
}
}
| 3,490
| 36.945652
| 118
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/functional/expiry/FunctionalExpiryTest.java
|
package org.infinispan.functional.expiry;
import org.infinispan.Cache;
import org.infinispan.expiry.ExpiryTest;
import org.infinispan.functional.decorators.FunctionalAdvancedCache;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "functional.expiry.FunctionalExpiryTest")
public class FunctionalExpiryTest extends ExpiryTest {
@Override
protected Cache<String, String> getCache() {
Cache<String, String> cache = super.getCache();
return FunctionalAdvancedCache.create(cache.getAdvancedCache());
}
}
| 551
| 29.666667
| 81
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/LockedStream.java
|
package org.infinispan;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import org.infinispan.commons.util.Experimental;
import org.infinispan.commons.util.IntSet;
import org.infinispan.configuration.cache.LockingConfiguration;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.util.function.SerializableBiConsumer;
import org.infinispan.util.function.SerializableBiFunction;
import org.infinispan.util.function.SerializablePredicate;
/**
* Stream that allows for operation upon data solely with side effects by using {@link LockedStream#forEach(BiConsumer)}
* where the <b>BiConsumer</b> is invoked while guaranteeing that the entry being passed is properly locked for the
* entire duration of the invocation.
* <p>
* An attempt is made to acquire the lock for an entry using the default
* {@link LockingConfiguration#lockAcquisitionTimeout()} before invoking any operations on it.
* </p>
* @author wburns
* @since 9.1
*/
public interface LockedStream<K, V> extends BaseCacheStream<CacheEntry<K, V>, LockedStream<K, V>> {
/**
* Returns a locked stream consisting of the elements of this stream that match
* the given predicate.
* <p>
* This filter is after the lock is acquired for the given key. This way the filter will see the same value as
* the consumer is given.
* @param predicate predicate
* @return a LockedStream with the filter applied
*/
LockedStream<K, V> filter(Predicate<? super CacheEntry<K, V>> predicate);
/**
* Same as {@link LockedStream#filter(Predicate)} except that the Predicate must also
* implement <code>Serializable</code>
* <p>
* The compiler will pick this overload for lambda parameters, making them <code>Serializable</code>
* @param predicate the predicate to filter out unwanted entries
* @return a LockedStream with the filter applied
*/
default LockedStream<K, V> filter(SerializablePredicate<? super CacheEntry<K ,V>> predicate) {
return filter((Predicate<? super CacheEntry<K, V>> ) predicate);
}
/**
* Performs an action for each element of this stream on the primary owner of the given key.
* <p>
* This method is performed while holding exclusive lock over the given entry and will be released
* only after the consumer has completed. In the function, {@code entry.setValue(newValue)} is equivalent to
* {@code cache.put(entry.getKey(), newValue)}.
* <p>
* If using pessimistic transactions this lock is not held using a transaction and thus the user can start a
* transaction in this consumer which also must be completed before returning. A transaction can be started in
* the consumer and if done it will share the same lock used to obtain the key.
* <p>
* Remember that if you are using an explicit transaction or an async method that these must be completed before
* the consumer returns to guarantee that they are operating within the scope of the lock for the given key. Failure
* to do so will lead into possible inconsistency as they will be performing operations without the proper locking.
* <p>
* Some methods on the provided cache may not work as expected. These include
* {@link AdvancedCache#putForExternalRead(Object, Object)}, {@link AdvancedCache#lock(Object[])},
* {@link AdvancedCache#lock(Collection)}, and {@link AdvancedCache#removeGroup(String)}.
* If these methods are used inside of the Consumer on the cache it will throw a {@link IllegalStateException}.
* This is due to possible interactions with locks while using these commands.
* @param biConsumer the biConsumer to run for each entry under their lock
*/
void forEach(BiConsumer<Cache<K, V>, ? super CacheEntry<K, V>> biConsumer);
/**
* Same as {@link LockedStream#forEach(BiConsumer)} except that the BiConsumer must also
* implement <code>Serializable</code>
* <p>
* The compiler will pick this overload for lambda parameters, making them <code>Serializable</code>
* @param biConsumer the biConsumer to run for each entry under their lock
*/
default void forEach(SerializableBiConsumer<Cache<K, V>, ? super CacheEntry<K, V>> biConsumer) {
forEach((BiConsumer<Cache<K, V>, ? super CacheEntry<K, V>>) biConsumer);
}
/**
* Performs a BiFunction for each element of this stream on the primary owner of each entry returning
* a value. The returned value from the function will be sent back to the user mapped to the key that generated
* it, with all of these stored in a map. Both the BiFunction and the returned value must be Serializable in some
* way. This method will return only after all entries have been processed.
* <p>
* This method is currently marked as {@link Experimental} since this method returns a Map and requires blocking.
* This operation could take a deal of time and as such should be done using an asynchronous API. Most likely
* this return type will be changed to use some sort of asynchronous return value. This method is here until
* this can be implemented.
* <p>
* This <b>BiFunction</b> is invoked while holding an exclusive lock over the given entry that will be released
* only after the function has completed. In the function, {@code entry.setValue(newValue)} is equivalent to
* {@code cache.put(entry.getKey(), newValue)}.
* <p>
* If using pessimistic transactions this lock is not held using a transaction and thus the user can start a
* transaction in this consumer which also must be completed before returning. A transaction can be started in
* the biFunction and if done it will share the same lock used to obtain the key.
* <p>
* Remember if you are using an explicit transaction or an async method that these must be completed before
* the consumer returns to guarantee that they are operating within the scope of the lock for the given key. Failure
* to do so will lead into possible inconsistency as they will be performing operations without the proper locking.
* <p>
* Some methods on the provided cache may not work as expected. These include
* {@link AdvancedCache#putForExternalRead(Object, Object)}, {@link AdvancedCache#lock(Object[])},
* {@link AdvancedCache#lock(Collection)}, and {@link AdvancedCache#removeGroup(String)}.
* If these methods are used inside of the Consumer on the cache it will throw a {@link IllegalStateException}.
* This is due to possible interactions with locks while using these commands.
* @param biFunction the biFunction to run for each entry under their lock
* @param <R> the return type
* @return a map with each key mapped to the value returned from the bi function
*/
@Experimental
<R> Map<K, R> invokeAll(BiFunction<Cache<K, V>, ? super CacheEntry<K, V>, R> biFunction);
/**
* Same as {@link LockedStream#invokeAll(BiFunction)} except that the BiFunction must also
* implement <code>Serializable</code>
* <p>
* The compiler will pick this overload for lambda parameters, making them <code>Serializable</code>
* @param biFunction the biFunction to run for each entry under their lock
* @param <R> the return type
* @return a map with each key mapped to the value returned from the bi function
*/
@Experimental
default <R> Map<K, R> invokeAll(SerializableBiFunction<Cache<K, V>, ? super CacheEntry<K, V>, R> biFunction) {
return invokeAll((BiFunction<Cache<K, V>, ? super CacheEntry<K, V>, R>) biFunction);
}
/**
* {@inheritDoc}
*/
@Override
LockedStream<K, V> sequentialDistribution();
/**
* {@inheritDoc}
*/
@Override
LockedStream<K, V> parallelDistribution();
/**
* {@inheritDoc}
* @deprecated This is to be replaced by {@link #filterKeySegments(IntSet)}
*/
@Override
LockedStream<K, V> filterKeySegments(Set<Integer> segments);
/**
* {@inheritDoc}
*/
@Override
LockedStream<K, V> filterKeySegments(IntSet segments);
/**
* {@inheritDoc}
*/
@Override
LockedStream<K, V> filterKeys(Set<?> keys);
/**
* {@inheritDoc}
*/
@Override
LockedStream<K, V> distributedBatchSize(int batchSize);
/**
* {@inheritDoc}
*/
@Override
LockedStream<K, V> disableRehashAware();
/**
* Sets the timeout for the acquisition of the lock for each entry.
* @param time the maximum time to wait
* @param unit the time unit of the timeout argument
* @return a LockedStream with the timeout applied
*/
LockedStream<K, V> timeout(long time, TimeUnit unit);
/**
* This method is not supported when using a {@link LockedStream}
*/
@Override
LockedStream<K, V> segmentCompletionListener(SegmentCompletionListener listener) throws UnsupportedOperationException;
/**
* This method is not supported when using a {@link LockedStream}
*/
@Override
Iterator<CacheEntry<K, V>> iterator() throws UnsupportedOperationException;
/**
* This method is not supported when using a {@link LockedStream}
*/
@Override
Spliterator<CacheEntry<K, V>> spliterator() throws UnsupportedOperationException;
}
| 9,439
| 44.167464
| 121
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/package-info.java
|
/**
* This is the core of Infinispan, a distributed, transactional, highly scalable data grid
* platform. For more information on Infinispan, please read the documentation, tutorials
* and sample code on <a href="http://www.jboss.org/infinispan">the Infinispan project page</a>.
*
* @api.public
*/
package org.infinispan;
| 329
| 35.666667
| 96
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/InvalidCacheUsageException.java
|
package org.infinispan;
import org.infinispan.commons.CacheException;
/**
* Thrown when client makes cache usage errors. Situations like this include
* when clients invoke operations on the cache that are not allowed.
*
* @author Galder Zamarreño
* @since 5.2
*/
public class InvalidCacheUsageException extends CacheException {
public InvalidCacheUsageException(Throwable cause) {
super(cause);
}
public InvalidCacheUsageException(String msg) {
super(msg);
}
public InvalidCacheUsageException(String msg, Throwable cause) {
super(msg, cause);
}
}
| 595
| 21.074074
| 76
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/CacheSet.java
|
package org.infinispan;
import org.infinispan.commons.util.CloseableIteratorSet;
/**
* A set that also must implement the various {@link CacheCollection} methods for streams.
* @param <E> The type of the set
*/
public interface CacheSet<E> extends CacheCollection<E>, CloseableIteratorSet<E> {
}
| 301
| 26.454545
| 90
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.