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/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/CacheKeysFactoryTest.java
|
package org.infinispan.test.hibernate.cache.commons;
import static org.infinispan.test.hibernate.cache.commons.util.TxUtil.withTxSession;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Iterator;
import org.hibernate.SessionFactory;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.cache.internal.SimpleCacheKeysFactory;
import org.hibernate.cache.spi.CacheImplementor;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.infinispan.Cache;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Name;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Person;
import org.infinispan.test.hibernate.cache.commons.util.InfinispanTestingSetup;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.junit.Rule;
import org.junit.Test;
public class CacheKeysFactoryTest extends BaseUnitTestCase {
@Rule
public InfinispanTestingSetup infinispanTestIdentifier = new InfinispanTestingSetup();
private SessionFactory getSessionFactory(String cacheKeysFactory) {
Configuration configuration = new Configuration()
.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true")
.setProperty(Environment.CACHE_REGION_FACTORY, TestRegionFactoryProvider.load().getRegionFactoryClass().getName())
.setProperty(Environment.DEFAULT_CACHE_CONCURRENCY_STRATEGY, "transactional")
.setProperty("javax.persistence.sharedCache.mode", "ALL")
.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
if (cacheKeysFactory != null) {
configuration.setProperty(Environment.CACHE_KEYS_FACTORY, cacheKeysFactory);
}
configuration.addAnnotatedClass(Person.class);
return configuration.buildSessionFactory();
}
@Test
public void testNotSet() throws Exception {
test(null, "CacheKeyImplementation");
}
@Test
public void testDefault() throws Exception {
test(DefaultCacheKeysFactory.SHORT_NAME, "CacheKeyImplementation");
}
@Test
public void testDefaultClass() throws Exception {
test(DefaultCacheKeysFactory.class.getName(), "CacheKeyImplementation");
}
@Test
public void testSimple() throws Exception {
test(SimpleCacheKeysFactory.SHORT_NAME, Name.class.getSimpleName());
}
@Test
public void testSimpleClass() throws Exception {
test(SimpleCacheKeysFactory.class.getName(), Name.class.getSimpleName());
}
private void test(String cacheKeysFactory, String keyClassName) throws Exception {
SessionFactory sessionFactory = getSessionFactory(cacheKeysFactory);
try {
withTxSession(false, sessionFactory, s -> {
Person person = new Person("John", "Black", 39);
s.persist(person);
});
RegionFactory regionFactory = ((CacheImplementor) sessionFactory.getCache()).getRegionFactory();
TestRegionFactory factory = TestRegionFactoryProvider.load().wrap(regionFactory);
Cache<Object, Object> cache = factory.getCacheManager().getCache(Person.class.getName());
Iterator<InternalCacheEntry<Object, Object>> iterator = cache.getAdvancedCache().getDataContainer().iterator();
assertTrue(iterator.hasNext());
Object key = iterator.next().getKey();
assertEquals(keyClassName, key.getClass().getSimpleName());
withTxSession(false, sessionFactory, s -> {
Person person = s.load(Person.class, new Name("John", "Black"));
assertEquals(39, person.getAge());
});
} finally {
sessionFactory.close();
}
}
}
| 3,946
| 40.547368
| 123
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/AbstractRegionAccessStrategyTest.java
|
package org.infinispan.test.hibernate.cache.commons;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.cache.spi.entry.CacheEntry;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.InvalidateCommand;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.hibernate.cache.commons.access.PutFromLoadValidator;
import org.infinispan.hibernate.cache.commons.access.SessionAccess;
import org.infinispan.hibernate.cache.commons.util.Caches;
import org.infinispan.hibernate.cache.commons.util.FutureUpdate;
import org.infinispan.hibernate.cache.commons.util.TombstoneUpdate;
import org.infinispan.hibernate.cache.commons.util.VersionedEntry;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.hibernate.cache.commons.util.ExpectingInterceptor;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess.TestRegionAccessStrategy;
import org.infinispan.test.hibernate.cache.commons.util.TestSynchronization;
import org.infinispan.util.ControlledTimeService;
import org.jboss.logging.Logger;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public abstract class AbstractRegionAccessStrategyTest<S>
extends AbstractNonFunctionalTest {
protected final Logger log = Logger.getLogger(getClass());
public static final String REGION_NAME = "com.foo.test";
public static final String KEY_BASE = "KEY";
public static final TestCacheEntry VALUE1 = new TestCacheEntry("VALUE1", 1);
public static final TestCacheEntry VALUE2 = new TestCacheEntry("VALUE2", 2);
protected static final ControlledTimeService TIME_SERVICE = new ControlledTimeService();
protected static final TestSessionAccess TEST_SESSION_ACCESS = TestSessionAccess.findTestSessionAccess();
protected static final SessionAccess SESSION_ACCESS = SessionAccess.findSessionAccess();
protected NodeEnvironment localEnvironment;
protected InfinispanBaseRegion localRegion;
protected S localAccessStrategy;
protected TestRegionAccessStrategy testLocalAccessStrategy;
protected NodeEnvironment remoteEnvironment;
protected InfinispanBaseRegion remoteRegion;
protected S remoteAccessStrategy;
protected TestRegionAccessStrategy testRemoteAccessStrategy;
protected boolean transactional;
protected boolean invalidation;
protected boolean synchronous;
protected Exception node1Exception;
protected Exception node2Exception;
protected AssertionError node1Failure;
protected AssertionError node2Failure;
protected List<Runnable> cleanup = new ArrayList<>();
@Rule
public TestName name = new TestName();
@Override
protected boolean canUseLocalMode() {
return false;
}
@BeforeClassOnce
public void prepareResources() throws Exception {
// to mimic exactly the old code results, both environments here are exactly the same...
StandardServiceRegistryBuilder ssrb = createStandardServiceRegistryBuilder();
localEnvironment = new NodeEnvironment( ssrb );
localEnvironment.prepare();
localRegion = getRegion(localEnvironment);
localAccessStrategy = getAccessStrategy(localRegion);
testLocalAccessStrategy = TEST_SESSION_ACCESS.fromAccess(localAccessStrategy);
transactional = Caches.isTransactionalCache(localRegion.getCache());
invalidation = Caches.isInvalidationCache(localRegion.getCache());
synchronous = Caches.isSynchronousCache(localRegion.getCache());
remoteEnvironment = new NodeEnvironment( ssrb );
remoteEnvironment.prepare();
remoteRegion = getRegion(remoteEnvironment);
remoteAccessStrategy = getAccessStrategy(remoteRegion);
testRemoteAccessStrategy = TEST_SESSION_ACCESS.fromAccess(remoteAccessStrategy);
waitForClusterToForm(localRegion.getCache(), remoteRegion.getCache());
}
@After
public void cleanup() {
cleanup.forEach(Runnable::run);
cleanup.clear();
if (localRegion != null) localRegion.getCache().clear();
if (remoteRegion != null) remoteRegion.getCache().clear();
node1Exception = node2Exception = null;
node1Failure = node2Failure = null;
TIME_SERVICE.advance(1); // There might be invalidation from the previous test
}
@AfterClassOnce
public void releaseResources() throws Exception {
try {
if (localEnvironment != null) {
localEnvironment.release();
}
}
finally {
if (remoteEnvironment != null) {
remoteEnvironment.release();
}
}
}
@Override
protected StandardServiceRegistryBuilder createStandardServiceRegistryBuilder() {
StandardServiceRegistryBuilder ssrb = super.createStandardServiceRegistryBuilder();
ssrb.applySetting(TestRegionFactory.TIME_SERVICE, TIME_SERVICE);
return ssrb;
}
/**
* Simulate 2 nodes, both start, tx do a get, experience a cache miss, then
* 'read from db.' First does a putFromLoad, then an update (or removal if it is a collection).
* Second tries to do a putFromLoad with stale data (i.e. it took longer to read from the db).
* Both commit their tx. Then both start a new tx and get. First should see
* the updated data; second should either see the updated data
* (isInvalidation() == false) or null (isInvalidation() == true).
*
* @param useMinimalAPI
* @param isRemoval
* @throws Exception
*/
protected void putFromLoadTest(final boolean useMinimalAPI, boolean isRemoval) throws Exception {
final Object KEY = generateNextKey();
final CountDownLatch writeLatch1 = new CountDownLatch(1);
final CountDownLatch writeLatch2 = new CountDownLatch(1);
final CountDownLatch completionLatch = new CountDownLatch(2);
CountDownLatch[] putFromLoadLatches = new CountDownLatch[2];
Thread node1 = new Thread(() -> {
try {
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
putFromLoadLatches[0] = withTx(localEnvironment, session, () -> {
assertNull(testLocalAccessStrategy.get(session, KEY));
writeLatch1.await();
CountDownLatch latch = expectPutFromLoad(remoteRegion, KEY);
if (useMinimalAPI) {
testLocalAccessStrategy.putFromLoad(session, KEY, VALUE1, SESSION_ACCESS.getTimestamp(session), VALUE1.version, true);
} else {
testLocalAccessStrategy.putFromLoad(session, KEY, VALUE1, SESSION_ACCESS.getTimestamp(session), VALUE1.version);
}
doUpdate(testLocalAccessStrategy, session, KEY, VALUE2);
return latch;
});
} catch (Exception e) {
log.error("node1 caught exception", e);
node1Exception = e;
} catch (AssertionError e) {
node1Failure = e;
} finally {
// Let node2 write
writeLatch2.countDown();
completionLatch.countDown();
}
}, putFromLoadTestThreadName("node1", useMinimalAPI, isRemoval));
Thread node2 = new Thread(() -> {
try {
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
putFromLoadLatches[1] = withTx(remoteEnvironment, session, () -> {
assertNull(testRemoteAccessStrategy.get(session, KEY));
// Let node1 write
writeLatch1.countDown();
// Wait for node1 to finish
writeLatch2.await();
CountDownLatch latch = expectPutFromLoad(localRegion, KEY);
if (useMinimalAPI) {
testRemoteAccessStrategy.putFromLoad(session, KEY, VALUE1, SESSION_ACCESS.getTimestamp(session), VALUE1.version, true);
} else {
testRemoteAccessStrategy.putFromLoad(session, KEY, VALUE1, SESSION_ACCESS.getTimestamp(session), VALUE1.version);
}
return latch;
});
} catch (Exception e) {
log.error("node2 caught exception", e);
node2Exception = e;
} catch (AssertionError e) {
node2Failure = e;
} finally {
completionLatch.countDown();
}
}, putFromLoadTestThreadName("node2", useMinimalAPI, isRemoval));
node1.setDaemon(true);
node2.setDaemon(true);
CountDownLatch remoteUpdate = expectAfterUpdate(KEY);
node1.start();
node2.start();
assertTrue("Threads completed", completionLatch.await(2, TimeUnit.SECONDS));
assertThreadsRanCleanly();
assertTrue("Update was replicated", remoteUpdate.await(2, TimeUnit.SECONDS));
// At least one of the put from load latch should have completed
assertPutFromLoadLatches(putFromLoadLatches);
Object s1 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
assertEquals(isRemoval ? null : VALUE2, testLocalAccessStrategy.get(s1, KEY));
Object s2 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
Object remoteValue = testRemoteAccessStrategy.get(s2, KEY);
if (isUsingInvalidation() || isRemoval) {
// invalidation command invalidates pending put
assertNull(remoteValue);
} else {
// The node1 update is replicated, preventing the node2 PFER
assertEquals(VALUE2, remoteValue);
}
}
protected void assertPutFromLoadLatches(CountDownLatch[] latches) {
// In some cases, both puts might execute, so make sure you wait for both
// If waiting directly in the || condition, the right side might not wait
boolean await0 = await(latches[0]);
boolean await1 = await(latches[1]);
assertTrue(String.format(
"One of the latches in %s should have at least completed", Arrays.toString(latches)),
await0 || await1);
}
private boolean await(CountDownLatch latch) {
assertNotNull(latch);
try {
log.debugf("Await latch: %s", latch);
boolean await = latch.await(1, TimeUnit.SECONDS);
log.debugf("Finished waiting for latch, did latch reach zero? %b", await);
return await;
} catch (InterruptedException e) {
// ignore;
return false;
}
}
String putFromLoadTestThreadName(String node, boolean useMinimalAPI, boolean isRemoval) {
return String.format("putFromLoad=%s,%s,%s,%s,minimal=%s,isRemove=%s",
node, mode, cacheMode, accessType, useMinimalAPI, isRemoval);
}
protected CountDownLatch expectAfterUpdate(Object key) {
return expectReadWriteKeyCommand(key, value -> value instanceof FutureUpdate);
}
protected CountDownLatch expectReadWriteKeyCommand(Object key, Predicate<Object> functionPredicate) {
if (!isUsingInvalidation() && accessType != AccessType.NONSTRICT_READ_WRITE) {
CountDownLatch latch = new CountDownLatch(1);
ExpectingInterceptor.get(remoteRegion.getCache())
.when((ctx, cmd) -> isExpectedReadWriteKey(key, cmd) &&
functionPredicate.test(((ReadWriteKeyCommand) cmd).getFunction()))
.countDown(latch);
cleanup.add(() -> ExpectingInterceptor.cleanup(remoteRegion.getCache()));
return latch;
} else {
return new CountDownLatch(0);
}
}
protected CountDownLatch expectPutFromLoad(Object key) {
return expectReadWriteKeyCommand(key, value -> value instanceof TombstoneUpdate);
}
protected CountDownLatch expectPutFromLoad(InfinispanBaseRegion region, Object key) {
Predicate<Object> functionPredicate = accessType == AccessType.NONSTRICT_READ_WRITE
? VersionedEntry.class::isInstance : TombstoneUpdate.class::isInstance;
CountDownLatch latch = new CountDownLatch(1);
if (!isUsingInvalidation()) {
ExpectingInterceptor.get(region.getCache())
.when((ctx, cmd) -> isExpectedReadWriteKey(key, cmd)
&& functionPredicate.test(((ReadWriteKeyCommand) cmd).getFunction()))
.countDown(latch);
cleanup.add(() -> ExpectingInterceptor.cleanup(region.getCache()));
} else {
if (transactional) {
expectPutFromLoadEndInvalidating(region, key, latch);
} else {
expectInvalidateCommand(region, latch);
}
}
log.debugf("Create latch for putFromLoad: %s", latch);
return latch;
}
protected abstract void doUpdate(TestRegionAccessStrategy strategy, Object session, Object key, TestCacheEntry entry);
protected abstract S getAccessStrategy(InfinispanBaseRegion region);
@Test
public void testRemove() throws Exception {
log.infof(name.getMethodName());
evictOrRemoveTest( false );
}
@Test
public void testEvict() throws Exception {
log.infof(name.getMethodName());
evictOrRemoveTest( true );
}
protected abstract InfinispanBaseRegion getRegion(NodeEnvironment environment);
protected void waitForClusterToForm(Cache... caches) {
TestingUtil.blockUntilViewsReceived(10000, Arrays.asList(caches));
}
protected boolean isTransactional() {
return transactional;
}
protected boolean isUsingInvalidation() {
return invalidation;
}
protected boolean isSynchronous() {
return synchronous;
}
protected void evictOrRemoveTest(final boolean evict) throws Exception {
final Object KEY = generateNextKey();
assertEquals(0, localRegion.getElementCountInMemory());
assertEquals(0, remoteRegion.getElementCountInMemory());
CountDownLatch localPutFromLoadLatch = expectRemotePutFromLoad(remoteRegion.getCache(), localRegion.getCache(), KEY);
CountDownLatch remotePutFromLoadLatch = expectRemotePutFromLoad(localRegion.getCache(), remoteRegion.getCache(), KEY);
Object s1 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
assertNull("local is clean", testLocalAccessStrategy.get(s1, KEY));
Object s2 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
assertNull("remote is clean", testRemoteAccessStrategy.get(s2, KEY));
Object s3 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
testLocalAccessStrategy.putFromLoad(s3, KEY, VALUE1, SESSION_ACCESS.getTimestamp(s3), VALUE1.version);
Object s5 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
testRemoteAccessStrategy.putFromLoad(s5, KEY, VALUE1, SESSION_ACCESS.getTimestamp(s5), VALUE1.version);
// putFromLoad is applied on local node synchronously, but if there's a concurrent update
// from the other node it can silently fail when acquiring the loc . Then we could try to read
// before the update is fully applied.
assertTrue(localPutFromLoadLatch.await(1, TimeUnit.SECONDS));
assertTrue(remotePutFromLoadLatch.await(1, TimeUnit.SECONDS));
Object s4 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
assertEquals(VALUE1, testLocalAccessStrategy.get(s4, KEY));
Object s6 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
assertEquals(VALUE1, testRemoteAccessStrategy.get(s6, KEY));
CountDownLatch endInvalidationLatch = createEndInvalidationLatch(evict, KEY);
CountDownLatch endRemoveLatch = createRemoveLatch(evict, KEY);
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
withTx(localEnvironment, session, () -> {
if (evict) {
testLocalAccessStrategy.evict(KEY);
}
else {
doRemove(testLocalAccessStrategy, session, KEY);
}
return null;
});
Object s7 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
assertNull(testLocalAccessStrategy.get(s7, KEY));
Object s8 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
assertNull(testRemoteAccessStrategy.get(s8, KEY));
assertTrue(endInvalidationLatch.await(1, TimeUnit.SECONDS));
assertEquals(0, localRegion.getElementCountInMemory());
assertEquals(0, remoteRegion.getElementCountInMemory());
assertTrue(endRemoveLatch.await(1, TimeUnit.SECONDS));
}
protected CountDownLatch createRemoveLatch(boolean evict, Object key) {
if (!evict)
return expectAfterUpdate(key);
return new CountDownLatch(0);
}
protected void doRemove(TestRegionAccessStrategy strategy, Object session, Object key) throws SystemException, RollbackException {
SoftLock softLock = strategy.lockItem(session, key, null);
strategy.remove(session, key);
SessionAccess.TransactionCoordinatorAccess transactionCoordinator = SESSION_ACCESS.getTransactionCoordinator(session);
transactionCoordinator.registerLocalSynchronization(
new TestSynchronization.UnlockItem(strategy, session, key, softLock));
}
@Test
public void testRemoveAll() throws Exception {
log.infof(name.getMethodName());
evictOrRemoveAllTest(false);
}
@Test
public void testEvictAll() throws Exception {
log.infof(name.getMethodName());
evictOrRemoveAllTest(true);
}
protected void assertThreadsRanCleanly() {
if (node1Failure != null) {
throw node1Failure;
}
if (node2Failure != null) {
throw node2Failure;
}
if (node1Exception != null) {
log.error("node1 saw an exception", node1Exception);
assertEquals("node1 saw no exceptions", null, node1Exception);
}
if (node2Exception != null) {
log.error("node2 saw an exception", node2Exception);
assertEquals("node2 saw no exceptions", null, node2Exception);
}
}
protected abstract Object generateNextKey();
protected void evictOrRemoveAllTest(final boolean evict) throws Exception {
final Object KEY = generateNextKey();
assertEquals(0, localRegion.getElementCountInMemory());
assertEquals(0, remoteRegion.getElementCountInMemory());
Object s1 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
assertNull("local is clean", testLocalAccessStrategy.get(s1, KEY));
Object s2 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
assertNull("remote is clean", testRemoteAccessStrategy.get(s2, KEY));
CountDownLatch localPutFromLoadLatch = expectRemotePutFromLoad(remoteRegion.getCache(), localRegion.getCache(), KEY);
CountDownLatch remotePutFromLoadLatch = expectRemotePutFromLoad(localRegion.getCache(), remoteRegion.getCache(), KEY);
Object s3 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
log.infof("Call putFromLoad strategy get for key=%s", KEY);
testLocalAccessStrategy.putFromLoad(s3, KEY, VALUE1, SESSION_ACCESS.getTimestamp(s3), VALUE1.version);
Object s5 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
log.infof("Call remote putFromLoad strategy get for key=%s", KEY);
testRemoteAccessStrategy.putFromLoad(s5, KEY, VALUE1, SESSION_ACCESS.getTimestamp(s5), VALUE2.version);
// putFromLoad is applied on local node synchronously, but if there's a concurrent update
// from the other node it can silently fail when acquiring the loc . Then we could try to read
// before the update is fully applied.
assertTrue(localPutFromLoadLatch.await(1, TimeUnit.SECONDS));
assertTrue(remotePutFromLoadLatch.await(1, TimeUnit.SECONDS));
Object s4 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
Object s6 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
log.infof("Call local strategy get for key=%s", KEY);
assertEquals(VALUE1, testLocalAccessStrategy.get(s4, KEY));
assertEquals(VALUE1, testRemoteAccessStrategy.get(s6, KEY));
CountDownLatch endInvalidationLatch = createEndInvalidationLatch(evict, KEY);
Object removeSession = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
withTx(localEnvironment, removeSession, () -> {
if (evict) {
testLocalAccessStrategy.evictAll();
} else {
SoftLock softLock = testLocalAccessStrategy.lockRegion();
testLocalAccessStrategy.removeAll(removeSession);
testLocalAccessStrategy.unlockRegion(softLock);
}
return null;
});
Object s7 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
assertNull(testLocalAccessStrategy.get(s7, KEY));
assertEquals(0, localRegion.getElementCountInMemory());
Object s8 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
assertNull(testRemoteAccessStrategy.get(s8, KEY));
assertEquals(0, remoteRegion.getElementCountInMemory());
// Wait for async propagation of EndInvalidationCommand before executing naked put
assertTrue(endInvalidationLatch.await(1, TimeUnit.SECONDS));
TIME_SERVICE.advance(1);
CountDownLatch lastPutFromLoadLatch = expectRemotePutFromLoad(remoteRegion.getCache(), localRegion.getCache(), KEY);
// Test whether the get above messes up the optimistic version
Object s9 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
log.infof("Call remote strategy putFromLoad for key=%s and value=%s", KEY, VALUE1);
assertTrue(testRemoteAccessStrategy.putFromLoad(s9, KEY, VALUE1, SESSION_ACCESS.getTimestamp(s9), 1));
Object s10 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
log.infof("Call remote strategy get for key=%s", KEY);
assertEquals(VALUE1, testRemoteAccessStrategy.get(s10, KEY));
// Wait for change to be applied in local, otherwise the count might not be correct
assertTrue(lastPutFromLoadLatch.await(1, TimeUnit.SECONDS));
assertEquals(1, remoteRegion.getElementCountInMemory());
Object s11 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
assertEquals((isUsingInvalidation() ? null : VALUE1), testLocalAccessStrategy.get(s11, KEY));
Object s12 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
assertEquals(VALUE1, testRemoteAccessStrategy.get(s12, KEY));
}
private CountDownLatch createEndInvalidationLatch(boolean evict, Object key) {
CountDownLatch endInvalidationLatch;
if (invalidation && !evict) {
// removeAll causes transactional remove commands which trigger EndInvalidationCommands on the remote side
// if the cache is non-transactional, PutFromLoadValidator.registerRemoteInvalidations cannot find
// current session nor register tx synchronization, so it falls back to simple InvalidationCommand.
endInvalidationLatch = new CountDownLatch(1);
if (transactional) {
expectPutFromLoadEndInvalidating(remoteRegion, key, endInvalidationLatch);
} else {
expectInvalidateCommand(remoteRegion, endInvalidationLatch);
}
} else {
endInvalidationLatch = new CountDownLatch(0);
}
log.debugf("Create end invalidation latch: %s", endInvalidationLatch);
return endInvalidationLatch;
}
private void expectPutFromLoadEndInvalidating(InfinispanBaseRegion region, Object key, CountDownLatch endInvalidationLatch) {
PutFromLoadValidator originalValidator = PutFromLoadValidator.removeFromCache(region.getCache());
assertEquals(PutFromLoadValidator.class, originalValidator.getClass());
PutFromLoadValidator mockValidator = spy(originalValidator);
doAnswer(invocation -> {
try {
return invocation.callRealMethod();
} finally {
log.debugf("Count down latch after calling endInvalidatingKey %s", endInvalidationLatch);
endInvalidationLatch.countDown();
}
}).when(mockValidator).endInvalidatingKey(any(), eq(key));
PutFromLoadValidator.addToCache(region.getCache(), mockValidator);
cleanup.add(() -> {
PutFromLoadValidator.removeFromCache(region.getCache());
PutFromLoadValidator.addToCache(region.getCache(), originalValidator);
});
}
private void expectInvalidateCommand(InfinispanBaseRegion region, CountDownLatch latch) {
ExpectingInterceptor.get(region.getCache())
.when((ctx, cmd) -> cmd instanceof InvalidateCommand || cmd instanceof ClearCommand)
.countDown(latch);
cleanup.add(() -> ExpectingInterceptor.cleanup(region.getCache()));
}
private CountDownLatch expectRemotePutFromLoad(AdvancedCache localCache, AdvancedCache remoteCache, Object key) {
CountDownLatch putFromLoadLatch;
if (!isUsingInvalidation()) {
putFromLoadLatch = new CountDownLatch(1);
// The command may fail to replicate if it can't acquire lock locally
ExpectingInterceptor.Condition remoteCondition = ExpectingInterceptor.get(remoteCache)
.when((ctx, cmd) -> {
final boolean isRemote = !ctx.isOriginLocal();
final boolean isExpectedReadWriteKey = isExpectedReadWriteKey(key, cmd);
final boolean cond = isRemote && isExpectedReadWriteKey;
log.debugf("Remote condition [test: isRemote=%b && isRWK=%b; should be true: %b]"
, isRemote, isExpectedReadWriteKey, cond);
return cond;
});
ExpectingInterceptor.Condition localCondition = ExpectingInterceptor.get(localCache)
.whenFails((ctx, cmd) -> {
final boolean isLocal = ctx.isOriginLocal();
final boolean isExpectedReadWriteKey = isExpectedReadWriteKey(key, cmd);
final boolean cond = isLocal && isExpectedReadWriteKey;
log.debugf("Local condition [test: isLocal=%b && isRWK=%b; should be false: %b]"
, isLocal, isExpectedReadWriteKey, cond);
return cond;
});
remoteCondition.run(() -> {
localCondition.cancel();
log.debugf("Counting down latch because remote condition succeed");
putFromLoadLatch.countDown();
});
localCondition.run(() -> {
remoteCondition.cancel();
log.debugf("Counting down latch because local condition succeed");
putFromLoadLatch.countDown();
});
// just for case the test fails and does not remove the interceptor itself
cleanup.add(() -> ExpectingInterceptor.cleanup(localCache, remoteCache));
} else {
putFromLoadLatch = new CountDownLatch(0);
}
return putFromLoadLatch;
}
private boolean isExpectedReadWriteKey(Object key, VisitableCommand cmd) {
final boolean isPut = cmd instanceof ReadWriteKeyCommand;
if (isPut) {
final Object cmdKey = ((ReadWriteKeyCommand) cmd).getKey();
final boolean isPutForKey = cmdKey.equals(key);
if (!isPutForKey)
log.warnf("Put received for key=%s, but expecting put for key=%s. Maybe there's a command leak?"
, cmdKey, key);
return isPutForKey;
}
return false;
}
public static class TestCacheEntry implements CacheEntry, Serializable {
private final Serializable value;
private final Serializable version;
public TestCacheEntry(Serializable value, Serializable version) {
this.value = value;
this.version = version;
}
@Override
public boolean isReferenceEntry() {
return false;
}
@Override
public String getSubclass() {
return REGION_NAME;
}
@Override
public Object getVersion() {
return version;
}
@Override
public Serializable[] getDisassembledState() {
return new Serializable[] { value, version };
}
@Override
public String toString() {
return value + "/" + version;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestCacheEntry that = (TestCacheEntry) o;
return Objects.equals(value, that.value) &&
Objects.equals(version, that.version);
}
@Override
public int hashCode() {
return Objects.hash(value, version);
}
}
}
| 29,167
| 40.549858
| 140
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/TestsModule.java
|
package org.infinispan.test.hibernate.cache.commons;
import org.infinispan.factories.annotations.InfinispanModule;
/**
* {@code InfinispanModule} annotation is required for component annotation processing
*/
@InfinispanModule(name = "hibernate-commons-tests")
public class TestsModule implements org.infinispan.lifecycle.ModuleLifecycle {
}
| 345
| 30.454545
| 86
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/NodeEnvironment.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.access.AccessType;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.test.hibernate.cache.commons.util.CacheTestUtil;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
/**
* Defines the environment for a node.
*
* @author Steve Ebersole
*/
public class NodeEnvironment {
private final StandardServiceRegistryBuilder ssrb;
private StandardServiceRegistry serviceRegistry;
private TestRegionFactory regionFactory;
private Map<String, InfinispanBaseRegion> entityRegionMap;
private Map<String, InfinispanBaseRegion> collectionRegionMap;
public NodeEnvironment(StandardServiceRegistryBuilder ssrb) {
this.ssrb = ssrb;
}
public StandardServiceRegistry getServiceRegistry() {
return serviceRegistry;
}
public InfinispanBaseRegion getEntityRegion(String name, AccessType accessType) {
if (entityRegionMap == null) {
entityRegionMap = new HashMap<>();
return buildAndStoreEntityRegion(name, accessType);
}
InfinispanBaseRegion region = entityRegionMap.get(name);
if (region == null) {
region = buildAndStoreEntityRegion(name, accessType);
}
return region;
}
private InfinispanBaseRegion buildAndStoreEntityRegion(String name, AccessType accessType) {
InfinispanBaseRegion region = regionFactory.buildEntityRegion(name, accessType);
entityRegionMap.put(name, region);
return region;
}
public InfinispanBaseRegion getCollectionRegion(String name, AccessType accessType) {
if (collectionRegionMap == null) {
collectionRegionMap = new HashMap<>();
return buildAndStoreCollectionRegion(name, accessType);
}
InfinispanBaseRegion region = collectionRegionMap.get(name);
if (region == null) {
region = buildAndStoreCollectionRegion(name, accessType);
collectionRegionMap.put(name, region);
}
return region;
}
private InfinispanBaseRegion buildAndStoreCollectionRegion(String name, AccessType accessType) {
return regionFactory.buildCollectionRegion(name, accessType);
}
public void prepare() throws Exception {
serviceRegistry = ssrb.build();
regionFactory = CacheTestUtil.startRegionFactory( serviceRegistry );
}
public void release() throws Exception {
try {
if (entityRegionMap != null) {
for (InfinispanBaseRegion region : entityRegionMap.values()) {
try {
region.getCache().stop();
} catch (Exception e) {
// Ignore...
}
}
entityRegionMap.clear();
}
if (collectionRegionMap != null) {
for (InfinispanBaseRegion reg : collectionRegionMap.values()) {
try {
reg.getCache().stop();
} catch (Exception e) {
// Ignore...
}
}
collectionRegionMap.clear();
}
}
finally {
try {
if (regionFactory != null) {
// Currently the RegionFactory is shutdown by its registration
// with the CacheTestSetup from CacheTestUtil when built
regionFactory.stop();
}
}
finally {
if (serviceRegistry != null) {
StandardServiceRegistryBuilder.destroy( serviceRegistry );
}
}
}
}
public RegionFactory getRegionFactory() {
return regionFactory.unwrap();
}
}
| 4,139
| 31.857143
| 99
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/InfinispanRegionFactoryTestCase.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.DEF_INFINISPAN_CONFIG_RESOURCE;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.DEF_PENDING_PUTS_RESOURCE;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.DEF_TIMESTAMPS_RESOURCE;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.INFINISPAN_CONFIG_RESOURCE_PROP;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.TIMESTAMPS_CACHE_RESOURCE_PROP;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import java.util.function.Consumer;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.Environment;
import org.hibernate.testing.boot.ServiceRegistryTestingImpl;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.util.FileLookupFactory;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ClusteringConfigurationBuilder;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.configuration.parsing.ParserRegistry;
import org.infinispan.eviction.EvictionType;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.hibernate.cache.commons.util.InfinispanTestingSetup;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.transaction.TransactionMode;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
/**
* InfinispanRegionFactoryTestCase.
*
* @author Galder Zamarreño
* @since 3.5
*/
public class InfinispanRegionFactoryTestCase {
@Rule
public InfinispanTestingSetup infinispanTestIdentifier = new InfinispanTestingSetup();
private final ServiceRegistryTestingImpl serviceRegistry = ServiceRegistryTestingImpl.forUnitTesting();
@After
public void tearDown() {
serviceRegistry.destroy();
}
@Test
public void testConfigurationProcessing() {
final String person = "com.acme.Person";
final String addresses = "com.acme.Person.addresses";
Properties p = createProperties();
p.setProperty("hibernate.cache.infinispan.com.acme.Person.cfg", "person-cache");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.memory.eviction.type", "MEMORY");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.memory.size", "5000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.wake_up_interval", "2000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.cfg", "person-addresses-cache");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.lifespan", "120000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.max_idle", "60000");
p.setProperty("hibernate.cache.infinispan.query.cfg", "my-query-cache");
p.setProperty("hibernate.cache.infinispan.query.memory.eviction.type", "MEMORY");
p.setProperty("hibernate.cache.infinispan.query.expiration.wake_up_interval", "3000");
p.setProperty("hibernate.cache.infinispan.query.memory.size", "10000");
TestRegionFactory factory = createRegionFactory(p);
try {
assertEquals("person-cache", factory.getBaseConfiguration(person));
Configuration personOverride = factory.getConfigurationOverride(person);
assertEquals(EvictionType.COUNT, personOverride.memory().evictionType());
assertEquals(5000, personOverride.memory().size());
assertEquals(2000, personOverride.expiration().wakeUpInterval());
assertEquals(60000, personOverride.expiration().lifespan());
assertEquals(30000, personOverride.expiration().maxIdle());
assertEquals("person-addresses-cache", factory.getBaseConfiguration(addresses));
Configuration addressesOverride = factory.getConfigurationOverride(addresses);
assertEquals(120000, addressesOverride.expiration().lifespan());
assertEquals(60000, addressesOverride.expiration().maxIdle());
assertEquals("my-query-cache", factory.getBaseConfiguration(InfinispanProperties.QUERY));
Configuration queryOverride = factory.getConfigurationOverride(InfinispanProperties.QUERY);
assertEquals(EvictionType.COUNT, queryOverride.memory().evictionType());
assertEquals(10000, queryOverride.memory().size());
assertEquals(3000, queryOverride.expiration().wakeUpInterval());
} finally {
factory.stop();
}
}
@Test
public void testBuildEntityCollectionRegionsPersonPlusEntityCollectionOverrides() {
final String person = "com.acme.Person";
final String address = "com.acme.Address";
final String car = "com.acme.Car";
final String addresses = "com.acme.Person.addresses";
final String parts = "com.acme.Car.parts";
Properties p = createProperties();
// First option, cache defined for entity and overrides for generic entity data type and entity itself.
p.setProperty("hibernate.cache.infinispan.com.acme.Person.cfg", "person-cache");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.memory.eviction.type", "MEMORY");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.memory.size", "5000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.wake_up_interval", "2000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
p.setProperty("hibernate.cache.infinispan.entity.memory.eviction.type", "MEMORY");
p.setProperty("hibernate.cache.infinispan.entity.expiration.wake_up_interval", "3000");
p.setProperty("hibernate.cache.infinispan.entity.memory.size", "20000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.cfg", "addresses-cache");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.memory.eviction.type", "MEMORY");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.memory.size", "5500");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.wake_up_interval", "2500");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.lifespan", "65000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.addresses.expiration.max_idle", "35000");
p.setProperty("hibernate.cache.infinispan.collection.cfg", "mycollection-cache");
p.setProperty("hibernate.cache.infinispan.collection.memory.eviction.type", "MEMORY");
p.setProperty("hibernate.cache.infinispan.collection.expiration.wake_up_interval", "3500");
p.setProperty("hibernate.cache.infinispan.collection.memory.size", "25000");
TestRegionFactory factory = createRegionFactory(p);
try {
EmbeddedCacheManager manager = factory.getCacheManager();
assertFalse(manager.getCacheManagerConfiguration().jmx().enabled());
assertNotNull(factory.getBaseConfiguration(person));
assertFalse(isDefinedCache(factory, person));
assertNotNull(factory.getBaseConfiguration(addresses));
assertFalse(isDefinedCache(factory, addresses));
assertNull(factory.getBaseConfiguration(address));
assertNull(factory.getBaseConfiguration(parts));
AdvancedCache cache;
InfinispanBaseRegion region = factory.buildEntityRegion(person, AccessType.TRANSACTIONAL);
assertTrue(isDefinedCache(factory, person));
cache = region.getCache();
Configuration cacheCfg = cache.getCacheConfiguration();
assertEquals(EvictionType.COUNT, cacheCfg.memory().evictionType());
assertEquals(2000, cacheCfg.expiration().wakeUpInterval());
assertEquals(5000, cacheCfg.memory().size());
assertEquals(60000, cacheCfg.expiration().lifespan());
assertEquals(30000, cacheCfg.expiration().maxIdle());
assertFalse(cacheCfg.statistics().enabled());
region = factory.buildEntityRegion(address, AccessType.TRANSACTIONAL);
assertTrue(isDefinedCache(factory, person));
cache = region.getCache();
cacheCfg = cache.getCacheConfiguration();
assertEquals(EvictionType.COUNT, cacheCfg.memory().evictionType());
assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
assertEquals(20000, cacheCfg.memory().size());
assertFalse(cacheCfg.statistics().enabled());
region = factory.buildEntityRegion(car, AccessType.TRANSACTIONAL);
assertTrue(isDefinedCache(factory, person));
cache = region.getCache();
cacheCfg = cache.getCacheConfiguration();
assertEquals(EvictionType.COUNT, cacheCfg.memory().evictionType());
assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
assertEquals(20000, cacheCfg.memory().size());
assertFalse(cacheCfg.statistics().enabled());
InfinispanBaseRegion collectionRegion = factory.buildCollectionRegion(addresses, AccessType.TRANSACTIONAL);
assertTrue(isDefinedCache(factory, person));
cache = collectionRegion .getCache();
cacheCfg = cache.getCacheConfiguration();
assertEquals(EvictionType.COUNT, cacheCfg.memory().evictionType());
assertEquals(2500, cacheCfg.expiration().wakeUpInterval());
assertEquals(5500, cacheCfg.memory().size());
assertEquals(65000, cacheCfg.expiration().lifespan());
assertEquals(35000, cacheCfg.expiration().maxIdle());
assertFalse(cacheCfg.statistics().enabled());
collectionRegion = factory.buildCollectionRegion(parts, AccessType.TRANSACTIONAL);
assertTrue(isDefinedCache(factory, addresses));
cache = collectionRegion.getCache();
cacheCfg = cache.getCacheConfiguration();
assertEquals(EvictionType.COUNT, cacheCfg.memory().evictionType());
assertEquals(3500, cacheCfg.expiration().wakeUpInterval());
assertEquals(25000, cacheCfg.memory().size());
assertFalse(cacheCfg.statistics().enabled());
collectionRegion = factory.buildCollectionRegion(parts, AccessType.TRANSACTIONAL);
assertTrue(isDefinedCache(factory, addresses));
cache = collectionRegion.getCache();
cacheCfg = cache.getCacheConfiguration();
assertEquals(EvictionType.COUNT, cacheCfg.memory().evictionType());
assertEquals(3500, cacheCfg.expiration().wakeUpInterval());
assertEquals(25000, cacheCfg.memory().size());
assertFalse(cacheCfg.statistics().enabled());
} finally {
factory.stop();
}
}
@Test
public void testBuildEntityCollectionRegionOverridesOnly() {
final String address = "com.acme.Address";
final String personAddressses = "com.acme.Person.addresses";
AdvancedCache cache;
Properties p = createProperties();
p.setProperty("hibernate.cache.infinispan.entity.memory.eviction.type", "MEMORY");
p.setProperty("hibernate.cache.infinispan.entity.memory.size", "30000");
p.setProperty("hibernate.cache.infinispan.entity.expiration.wake_up_interval", "3000");
p.setProperty("hibernate.cache.infinispan.collection.memory.eviction.type", "MEMORY");
p.setProperty("hibernate.cache.infinispan.collection.memory.size", "35000");
p.setProperty("hibernate.cache.infinispan.collection.expiration.wake_up_interval", "3500");
TestRegionFactory factory = createRegionFactory(p);
try {
factory.getCacheManager();
InfinispanBaseRegion region = factory.buildEntityRegion(address, AccessType.TRANSACTIONAL);
assertNull(factory.getBaseConfiguration(address));
cache = region.getCache();
Configuration cacheCfg = cache.getCacheConfiguration();
assertEquals(EvictionType.COUNT, cacheCfg.memory().evictionType());
assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
assertEquals(30000, cacheCfg.memory().maxCount());
// Max idle value comes from base XML configuration
assertEquals(100000, cacheCfg.expiration().maxIdle());
InfinispanBaseRegion collectionRegion = factory.buildCollectionRegion(personAddressses, AccessType.TRANSACTIONAL);
assertNull(factory.getBaseConfiguration(personAddressses));
cache = collectionRegion.getCache();
cacheCfg = cache.getCacheConfiguration();
assertEquals(EvictionType.COUNT, cacheCfg.memory().evictionType());
assertEquals(3500, cacheCfg.expiration().wakeUpInterval());
assertEquals(35000, cacheCfg.memory().size());
assertEquals(100000, cacheCfg.expiration().maxIdle());
} finally {
factory.stop();
}
}
@Test
public void testBuildEntityRegionPersonPlusEntityOverridesWithoutCfg() {
final String person = "com.acme.Person";
Properties p = createProperties();
// Third option, no cache defined for entity and overrides for generic entity data type and entity itself.
p.setProperty("hibernate.cache.infinispan.com.acme.Person.memory.eviction.type", "MEMORY");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
p.setProperty("hibernate.cache.infinispan.entity.memory.eviction.type", "FIFO");
p.setProperty("hibernate.cache.infinispan.entity.memory.size", "10000");
p.setProperty("hibernate.cache.infinispan.entity.expiration.wake_up_interval", "3000");
TestRegionFactory factory = createRegionFactory(p);
try {
factory.getCacheManager();
assertFalse( isDefinedCache(factory, person ) );
InfinispanBaseRegion region = factory.buildEntityRegion(person, AccessType.TRANSACTIONAL);
assertTrue( isDefinedCache(factory, person ) );
AdvancedCache cache = region.getCache();
Configuration cacheCfg = cache.getCacheConfiguration();
assertEquals(EvictionType.COUNT, cacheCfg.memory().evictionType());
assertEquals(3000, cacheCfg.expiration().wakeUpInterval());
assertEquals(10000, cacheCfg.memory().size());
assertEquals(60000, cacheCfg.expiration().lifespan());
assertEquals(30000, cacheCfg.expiration().maxIdle());
} finally {
factory.stop();
}
}
@Test
public void testBuildImmutableEntityRegion() {
AdvancedCache cache;
Properties p = new Properties();
TestRegionFactory factory = createRegionFactory(p);
try {
factory.getCacheManager();
InfinispanBaseRegion region = factory.buildEntityRegion("com.acme.Address", AccessType.TRANSACTIONAL);
assertNull( factory.getBaseConfiguration( "com.acme.Address" ) );
cache = region.getCache();
Configuration cacheCfg = cache.getCacheConfiguration();
assertEquals("Immutable entity should get non-transactional cache", TransactionMode.NON_TRANSACTIONAL, cacheCfg.transaction().transactionMode());
} finally {
factory.stop();
}
}
@Test
public void testTimestampValidation() throws IOException {
final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
Properties p = createProperties();
URL url = FileLookupFactory.newInstance().lookupFileLocation(DEF_INFINISPAN_CONFIG_RESOURCE, getClass().getClassLoader());
ConfigurationBuilderHolder cbh = new ParserRegistry().parse(url);
ConfigurationBuilder builder = cbh.getNamedConfigurationBuilders().get( DEF_TIMESTAMPS_RESOURCE );
builder.clustering().cacheMode(CacheMode.INVALIDATION_SYNC);
DefaultCacheManager manager = new DefaultCacheManager(cbh, true);
try {
TestRegionFactory factory = createRegionFactory(manager, p, null);
factory.start(serviceRegistry, p);
// Should have failed saying that invalidation is not allowed for timestamp caches.
Exceptions.expectException(CacheException.class, () -> factory.buildTimestampsRegion(timestamps));
} finally {
TestingUtil.killCacheManagers( manager );
}
}
@Test
public void testBuildDefaultTimestampsRegion() {
final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
Properties p = createProperties();
TestRegionFactory factory = createRegionFactory(p);
try {
assertTrue(isDefinedCache(factory, DEF_TIMESTAMPS_RESOURCE));
InfinispanBaseRegion region = factory.buildTimestampsRegion(timestamps);
AdvancedCache cache = region.getCache();
assertEquals(timestamps, cache.getName());
Configuration cacheCfg = cache.getCacheConfiguration();
assertEquals( CacheMode.REPL_ASYNC, cacheCfg.clustering().cacheMode() );
assertFalse( cacheCfg.statistics().enabled() );
} finally {
factory.stop();
}
}
protected boolean isDefinedCache(TestRegionFactory factory, String cacheName) {
return factory.getCacheManager().getCacheConfiguration(cacheName) != null;
}
@Test
public void testBuildDiffCacheNameTimestampsRegion() {
final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
final String unrecommendedTimestamps = "unrecommended-timestamps";
Properties p = createProperties();
p.setProperty( TIMESTAMPS_CACHE_RESOURCE_PROP, unrecommendedTimestamps);
TestRegionFactory factory = createRegionFactory(p, m -> {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.clustering().stateTransfer().fetchInMemoryState(true);
builder.clustering().cacheMode( CacheMode.REPL_SYNC );
m.defineConfiguration(unrecommendedTimestamps, builder.build() );
});
try {
assertEquals(unrecommendedTimestamps, factory.getBaseConfiguration(InfinispanProperties.TIMESTAMPS));
InfinispanBaseRegion region = factory.buildTimestampsRegion(timestamps);
AdvancedCache cache = region.getCache();
Configuration cacheCfg = cache.getCacheConfiguration();
assertEquals(CacheMode.REPL_SYNC, cacheCfg.clustering().cacheMode());
assertTrue(cacheCfg.memory().storageType() != StorageType.BINARY);
assertFalse(cacheCfg.statistics().enabled());
} finally {
factory.stop();
}
}
@Test
public void testBuildTimestampsRegionWithCacheNameOverride() {
final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
final String myTimestampsCache = "mytimestamps-cache";
Properties p = createProperties();
p.setProperty(TIMESTAMPS_CACHE_RESOURCE_PROP, myTimestampsCache);
TestRegionFactory factory = createRegionFactory(p, m -> {
ClusteringConfigurationBuilder builder = new ConfigurationBuilder().clustering().cacheMode(CacheMode.LOCAL);
m.defineConfiguration(myTimestampsCache, builder.build());
});
try {
InfinispanBaseRegion region = factory.buildTimestampsRegion(timestamps);
assertTrue(isDefinedCache(factory, timestamps));
// default timestamps cache is async replicated
assertEquals(CacheMode.LOCAL, region.getCache().getCacheConfiguration().clustering().cacheMode());
} finally {
factory.stop();
}
}
@Test
public void testBuildTimestampsRegionWithFifoEvictionOverride() {
final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
final String myTimestampsCache = "mytimestamps-cache";
Properties p = createProperties();
p.setProperty(TIMESTAMPS_CACHE_RESOURCE_PROP, myTimestampsCache);
p.setProperty("hibernate.cache.infinispan.timestamps.memory.eviction.type", "FIFO");
p.setProperty("hibernate.cache.infinispan.timestamps.memory.size", "10000");
p.setProperty("hibernate.cache.infinispan.timestamps.expiration.wake_up_interval", "3000");
TestRegionFactory factory = createRegionFactory(p);
try {
Exceptions.expectException(CacheException.class, () -> factory.buildTimestampsRegion(timestamps));
} finally {
factory.stop();
}
}
@Test
public void testBuildTimestampsRegionWithNoneEvictionOverride() {
final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
final String timestampsNoEviction = "timestamps-no-eviction";
Properties p = createProperties();
p.setProperty("hibernate.cache.infinispan.timestamps.cfg", timestampsNoEviction);
p.setProperty("hibernate.cache.infinispan.timestamps.memory.size", "0");
p.setProperty("hibernate.cache.infinispan.timestamps.expiration.wake_up_interval", "3000");
TestRegionFactory factory = createRegionFactory(p);
try {
InfinispanBaseRegion region = factory.buildTimestampsRegion(timestamps);
assertTrue( isDefinedCache(factory, timestamps) );
assertEquals(3000, region.getCache().getCacheConfiguration().expiration().wakeUpInterval());
} finally {
factory.stop();
}
}
@Test
public void testBuildQueryRegion() {
final String query = "org.hibernate.cache.internal.StandardQueryCache";
Properties p = createProperties();
TestRegionFactory factory = createRegionFactory(p);
try {
assertTrue(isDefinedCache(factory, "local-query"));
InfinispanBaseRegion region = factory.buildQueryResultsRegion(query);
AdvancedCache cache = region.getCache();
Configuration cacheCfg = cache.getCacheConfiguration();
assertEquals( CacheMode.LOCAL, cacheCfg.clustering().cacheMode() );
assertFalse( cacheCfg.statistics().enabled() );
} finally {
factory.stop();
}
}
@Test
public void testBuildQueryRegionWithCustomRegionName() {
final String queryRegionName = "myquery";
Properties p = createProperties();
p.setProperty("hibernate.cache.infinispan.myquery.cfg", "timestamps-none-eviction");
p.setProperty("hibernate.cache.infinispan.myquery.memory.eviction.type", "MEMORY");
p.setProperty("hibernate.cache.infinispan.myquery.expiration.wake_up_interval", "2222");
p.setProperty("hibernate.cache.infinispan.myquery.memory.size", "11111");
TestRegionFactory factory = createRegionFactory(p);
try {
assertTrue(isDefinedCache(factory, "local-query"));
InfinispanBaseRegion region = factory.buildQueryResultsRegion(queryRegionName);
assertNotNull(factory.getBaseConfiguration(queryRegionName));
assertTrue(isDefinedCache(factory, queryRegionName));
AdvancedCache cache = region.getCache();
Configuration cacheCfg = cache.getCacheConfiguration();
assertEquals(EvictionType.COUNT, cacheCfg.memory().evictionType());
assertEquals(2222, cacheCfg.expiration().wakeUpInterval());
assertEquals( 11111, cacheCfg.memory().size() );
} finally {
factory.stop();
}
}
@Test
public void testEnableStatistics() {
Properties p = createProperties();
p.setProperty("hibernate.cache.infinispan.statistics", "true");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
p.setProperty("hibernate.cache.infinispan.entity.memory.eviction.type", "FIFO");
p.setProperty("hibernate.cache.infinispan.entity.expiration.wake_up_interval", "3000");
p.setProperty("hibernate.cache.infinispan.entity.memory.size", "10000");
TestRegionFactory factory = createRegionFactory(p);
try {
EmbeddedCacheManager manager = factory.getCacheManager();
assertTrue(manager.getCacheManagerConfiguration().jmx().enabled());
InfinispanBaseRegion region = factory.buildEntityRegion("com.acme.Address", AccessType.TRANSACTIONAL);
AdvancedCache cache = region.getCache();
assertTrue(cache.getCacheConfiguration().statistics().enabled());
region = factory.buildEntityRegion("com.acme.Person", AccessType.TRANSACTIONAL);
cache = region.getCache();
assertTrue(cache.getCacheConfiguration().statistics().enabled());
final String query = "org.hibernate.cache.internal.StandardQueryCache";
InfinispanBaseRegion queryRegion = factory.buildQueryResultsRegion(query);
cache = queryRegion.getCache();
assertTrue(cache.getCacheConfiguration().statistics().enabled());
final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
InfinispanBaseRegion timestampsRegion = factory.buildTimestampsRegion(timestamps);
cache = timestampsRegion.getCache();
assertTrue(cache.getCacheConfiguration().statistics().enabled());
InfinispanBaseRegion collectionRegion = factory.buildCollectionRegion("com.acme.Person.addresses", AccessType.TRANSACTIONAL);
cache = collectionRegion.getCache();
assertTrue(cache.getCacheConfiguration().statistics().enabled());
} finally {
factory.stop();
}
}
@Test
public void testDisableStatistics() {
Properties p = createProperties();
p.setProperty("hibernate.cache.infinispan.statistics", "false");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
p.setProperty("hibernate.cache.infinispan.entity.memory.eviction.type", "FIFO");
p.setProperty("hibernate.cache.infinispan.entity.expiration.wake_up_interval", "3000");
p.setProperty("hibernate.cache.infinispan.entity.memory.size", "10000");
TestRegionFactory factory = createRegionFactory(p);
try {
InfinispanBaseRegion region = factory.buildEntityRegion("com.acme.Address", AccessType.TRANSACTIONAL);
AdvancedCache cache = region.getCache();
assertFalse( cache.getCacheConfiguration().statistics().enabled() );
region = factory.buildEntityRegion("com.acme.Person", AccessType.TRANSACTIONAL);
cache = region.getCache();
assertFalse( cache.getCacheConfiguration().statistics().enabled() );
final String query = "org.hibernate.cache.internal.StandardQueryCache";
InfinispanBaseRegion queryRegion = factory.buildQueryResultsRegion(query);
cache = queryRegion.getCache();
assertFalse( cache.getCacheConfiguration().statistics().enabled() );
final String timestamps = "org.hibernate.cache.spi.UpdateTimestampsCache";
InfinispanBaseRegion timestampsRegion = factory.buildTimestampsRegion(timestamps);
cache = timestampsRegion.getCache();
assertFalse( cache.getCacheConfiguration().statistics().enabled() );
InfinispanBaseRegion collectionRegion = factory.buildCollectionRegion("com.acme.Person.addresses", AccessType.TRANSACTIONAL);
cache = collectionRegion.getCache();
assertFalse( cache.getCacheConfiguration().statistics().enabled() );
} finally {
factory.stop();
}
}
@Test
public void testDefaultPendingPutsCache() {
Properties p = createProperties();
TestRegionFactory factory = createRegionFactory(p);
try {
Configuration ppConfig = factory.getCacheManager().getCacheConfiguration(DEF_PENDING_PUTS_RESOURCE);
assertTrue(ppConfig.isTemplate());
assertFalse(ppConfig.clustering().cacheMode().isClustered());
assertTrue(ppConfig.simpleCache());
assertEquals(TransactionMode.NON_TRANSACTIONAL, ppConfig.transaction().transactionMode());
assertEquals(60000, ppConfig.expiration().maxIdle());
assertFalse(ppConfig.statistics().enabled());
assertFalse(ppConfig.statistics().available());
} finally {
factory.stop();
}
}
@Test
public void testCustomPendingPutsCache() {
Properties p = createProperties();
p.setProperty(INFINISPAN_CONFIG_RESOURCE_PROP, "alternative-infinispan-configs.xml");
TestRegionFactory factory = createRegionFactory(p);
try {
Configuration ppConfig = factory.getCacheManager().getCacheConfiguration(DEF_PENDING_PUTS_RESOURCE);
assertEquals(120000, ppConfig.expiration().maxIdle());
} finally {
factory.stop();
}
}
private TestRegionFactory createRegionFactory(Properties p) {
return createRegionFactory(null, p, null);
}
private TestRegionFactory createRegionFactory(Properties p,
Consumer<EmbeddedCacheManager> hook) {
return createRegionFactory(null, p, hook);
}
private TestRegionFactory createRegionFactory(final EmbeddedCacheManager manager, Properties p,
Consumer<EmbeddedCacheManager> hook) {
if (manager != null) {
p.put(TestRegionFactory.MANAGER, manager);
}
if (hook != null) {
p.put(TestRegionFactory.AFTER_MANAGER_CREATED, hook);
}
final TestRegionFactory factory = TestRegionFactoryProvider.load().create(p);
factory.start(serviceRegistry, p);
return factory;
}
private static Properties createProperties() {
final Properties properties = new Properties();
// If configured in the environment, add configuration file name to properties.
final String cfgFileName =
(String) Environment.getProperties().get( INFINISPAN_CONFIG_RESOURCE_PROP );
if ( cfgFileName != null ) {
properties.put( INFINISPAN_CONFIG_RESOURCE_PROP, cfgFileName );
}
return properties;
}
}
| 29,176
| 46.988487
| 148
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/AbstractRegionImplTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
/**
* Base class for tests of Region implementations.
*
* @author Galder Zamarreño
* @since 3.5
*/
public abstract class AbstractRegionImplTest extends AbstractNonFunctionalTest {
protected abstract InfinispanBaseRegion createRegion(TestRegionFactory regionFactory, String regionName);
}
| 733
| 30.913043
| 108
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/AbstractEntityCollectionRegionTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons;
import java.util.Properties;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.spi.access.AccessType;
import org.infinispan.test.hibernate.cache.commons.util.CacheTestUtil;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.junit.Test;
/**
* Base class for tests of EntityRegion and CollectionRegion implementations.
*
* @author Galder Zamarreño
* @since 3.5
*/
public abstract class AbstractEntityCollectionRegionTest extends AbstractRegionImplTest {
@Test
public void testSupportedAccessTypes() {
StandardServiceRegistryBuilder ssrb = createStandardServiceRegistryBuilder();
final StandardServiceRegistry registry = ssrb.build();
try {
TestRegionFactory regionFactory = CacheTestUtil.startRegionFactory(
registry,
getCacheTestSupport()
);
supportedAccessTypeTest( regionFactory, CacheTestUtil.toProperties( ssrb.getSettings() ) );
}
finally {
StandardServiceRegistryBuilder.destroy( registry );
}
}
/**
* Creates a Region using the given factory, and then ensure that it handles calls to
* buildAccessStrategy as expected when all the various {@link AccessType}s are passed as
* arguments.
*/
protected abstract void supportedAccessTypeTest(TestRegionFactory regionFactory, Properties properties);
}
| 1,687
| 34.166667
| 105
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/AbstractExtraAPITest.java
|
package org.infinispan.test.hibernate.cache.commons;
import org.hibernate.cache.spi.access.SoftLock;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess.TestRegionAccessStrategy;
import org.infinispan.test.hibernate.cache.commons.util.TestingKeyFactory;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
import org.junit.Test;
import static org.junit.Assert.assertNull;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public abstract class AbstractExtraAPITest<S> extends AbstractNonFunctionalTest {
public static final String REGION_NAME = "test/com.foo.test";
public static final Object KEY = TestingKeyFactory.generateCollectionCacheKey( "KEY" );
protected static final TestSessionAccess TEST_SESSION_ACCESS = TestSessionAccess.findTestSessionAccess();
protected static final Object SESSION = TEST_SESSION_ACCESS.mockSessionImplementor();
protected S accessStrategy;
protected TestRegionAccessStrategy testAccessStrategy;
protected NodeEnvironment environment;
@BeforeClassOnce
public final void prepareLocalAccessStrategy() throws Exception {
environment = new NodeEnvironment( createStandardServiceRegistryBuilder() );
environment.prepare();
accessStrategy = getAccessStrategy();
testAccessStrategy = TEST_SESSION_ACCESS.fromAccess(accessStrategy);
}
protected abstract S getAccessStrategy();
@AfterClassOnce
public final void releaseLocalAccessStrategy() throws Exception {
if ( environment != null ) {
environment.release();
}
}
@Test
public void testLockItem() {
assertNull( testAccessStrategy.lockItem(SESSION, KEY, Integer.valueOf( 1 ) ) );
}
@Test
public void testLockRegion() {
assertNull( testAccessStrategy.lockRegion() );
}
@Test
public void testUnlockItem() {
testAccessStrategy.unlockItem(SESSION, KEY, new MockSoftLock() );
}
@Test
public void testUnlockRegion() {
testAccessStrategy.unlockItem(SESSION, KEY, new MockSoftLock() );
}
public static class MockSoftLock implements SoftLock {
}
}
| 2,141
| 30.043478
| 108
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/CacheKeySerializationTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.hibernate.Session;
import org.hibernate.Version;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.cache.internal.SimpleCacheKeysFactory;
import org.hibernate.cache.spi.CacheKeysFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.cache.CachingRegionFactory;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.infinispan.test.hibernate.cache.commons.functional.entities.PK;
import org.infinispan.test.hibernate.cache.commons.functional.entities.WithEmbeddedId;
import org.infinispan.test.hibernate.cache.commons.functional.entities.WithSimpleId;
import org.infinispan.test.hibernate.cache.commons.util.InfinispanTestingSetup;
import org.junit.Rule;
import org.junit.Test;
/**
* @author Gail Badner
*/
public class CacheKeySerializationTest extends BaseUnitTestCase {
@Rule
public InfinispanTestingSetup infinispanTestIdentifier = new InfinispanTestingSetup();
private SessionFactoryImplementor getSessionFactory(String cacheKeysFactory) {
Configuration configuration = new Configuration()
.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true")
.setProperty(Environment.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName())
.setProperty(Environment.DEFAULT_CACHE_CONCURRENCY_STRATEGY, "transactional")
.setProperty("javax.persistence.sharedCache.mode", "ALL")
.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
if (cacheKeysFactory != null) {
configuration.setProperty(Environment.CACHE_KEYS_FACTORY, cacheKeysFactory);
}
configuration.addAnnotatedClass(WithSimpleId.class);
configuration.addAnnotatedClass(WithEmbeddedId.class);
return (SessionFactoryImplementor) configuration.buildSessionFactory();
}
@Test
@TestForIssue(jiraKey = "HHH-11202")
public void testSimpleCacheKeySimpleId() throws Exception {
testId(SimpleCacheKeysFactory.INSTANCE, WithSimpleId.class.getName(), 1L);
}
@Test
@TestForIssue(jiraKey = "HHH-11202")
public void testSimpleCacheKeyEmbeddedId() throws Exception {
testId(SimpleCacheKeysFactory.INSTANCE, WithEmbeddedId.class.getName(), new PK(1L));
}
@Test
@TestForIssue(jiraKey = "HHH-11202")
public void testDefaultCacheKeySimpleId() throws Exception {
testId(DefaultCacheKeysFactory.INSTANCE, WithSimpleId.class.getName(), 1L);
}
@Test
@TestForIssue(jiraKey = "HHH-11202")
public void testDefaultCacheKeyEmbeddedId() throws Exception {
testId(DefaultCacheKeysFactory.INSTANCE, WithEmbeddedId.class.getName(), new PK(1L));
}
private void testId(CacheKeysFactory cacheKeysFactory, String entityName, Object id) throws Exception {
final SessionFactoryImplementor sessionFactory = getSessionFactory(cacheKeysFactory.getClass().getName());
final EntityPersister persister = sessionFactory.getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(entityName);
final Object key = cacheKeysFactory.createEntityKey(
id,
persister,
sessionFactory,
null
);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject( key );
final ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( baos.toByteArray() ) );
final Object keyClone = ois.readObject();
try {
if (Version.getVersionString().contains("6.0")) {
assertEquals( key, keyClone );
assertEquals( keyClone, key );
assertEquals( key.hashCode(), keyClone.hashCode() );
final Object idClone = cacheKeysFactory.getEntityId( keyClone );
assertEquals( id.hashCode(), idClone.hashCode() );
assertEquals( id, idClone );
assertEquals( idClone, id );
assertTrue( persister.getIdentifierType().isEqual( id, idClone, sessionFactory ) );
assertTrue( persister.getIdentifierType().isEqual( idClone, id, sessionFactory ) );
} else {
assertEquals(key, keyClone);
assertEquals(keyClone, key);
assertEquals(key.hashCode(), keyClone.hashCode());
final Object idClone;
if (cacheKeysFactory == SimpleCacheKeysFactory.INSTANCE) {
idClone = cacheKeysFactory.getEntityId(keyClone);
} else {
// DefaultCacheKeysFactory#getEntityId will return a disassembled version
try (Session session = sessionFactory.openSession()) {
idClone = persister.getIdentifierType().assemble(
(Serializable) cacheKeysFactory.getEntityId(keyClone),
(SharedSessionContractImplementor) session,
null
);
}
}
assertEquals(id.hashCode(), idClone.hashCode());
assertEquals(id, idClone);
assertEquals(idClone, id);
assertTrue(persister.getIdentifierType().isEqual(id, idClone, sessionFactory));
assertTrue(persister.getIdentifierType().isEqual(idClone, id, sessionFactory));
}
}
finally {
sessionFactory.close();
}
}
}
| 5,629
| 37.29932
| 128
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/stress/CorrectnessTestCase.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.stress;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.hibernate.LockMode;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.PessimisticLockException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
import org.hibernate.Transaction;
import org.hibernate.TransactionException;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cache.spi.access.CachedDomainDataAccess;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.LockAcquisitionException;
import org.hibernate.jpa.QueryHints;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
import org.hibernate.query.criteria.HibernateCriteriaBuilder;
import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl;
import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
import org.hibernate.testing.jta.JtaAwareConnectionProviderImpl;
import org.hibernate.testing.jta.TestingJtaPlatformImpl;
import org.hibernate.testing.junit4.CustomParameterized;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commons.test.TestResourceTracker;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.InterceptorConfiguration;
import org.infinispan.context.InvocationContext;
import org.infinispan.hibernate.cache.commons.access.InvalidationCacheAccessDelegate;
import org.infinispan.hibernate.cache.commons.access.PutFromLoadValidator;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.remoting.RemoteException;
import org.infinispan.test.hibernate.cache.commons.stress.entities.Address;
import org.infinispan.test.hibernate.cache.commons.stress.entities.Family;
import org.infinispan.test.hibernate.cache.commons.stress.entities.Family_;
import org.infinispan.test.hibernate.cache.commons.stress.entities.Person;
import org.infinispan.test.hibernate.cache.commons.util.TestConfigurationHook;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import jakarta.persistence.OptimisticLockException;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import jakarta.transaction.RollbackException;
import jakarta.transaction.TransactionManager;
/**
* Tries to execute random operations for {@link #EXECUTION_TIME} and then verify the log for correctness.
*
* Assumes serializable consistency.
*
* @author Radim Vansa
*/
@RunWith(CustomParameterized.class)
public abstract class CorrectnessTestCase {
static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(CorrectnessTestCase.class);
static final long EXECUTION_TIME = TimeUnit.MINUTES.toMillis(2);
static final int NUM_NODES = 4;
static final int NUM_THREADS_PER_NODE = 4;
static final int NUM_THREADS = NUM_NODES * NUM_THREADS_PER_NODE;
static final int NUM_FAMILIES = 1;
static final int NUM_ACCESS_AFTER_REMOVAL = NUM_THREADS * 2;
static final int MAX_MEMBERS = 10;
private final static Comparator<Log<?>> WALL_CLOCK_TIME_COMPARATOR = (o1, o2) -> Long.compare(o1.wallClockTime, o2.wallClockTime);
private final static boolean INVALIDATE_REGION = Boolean.getBoolean("testInfinispan.correctness.invalidateRegion");
private final static boolean INJECT_FAILURES = Boolean.getBoolean("testInfinispan.correctness.injectFailures");
@Parameterized.Parameter(0)
public String name;
@Parameterized.Parameter(1)
public CacheMode cacheMode;
@Parameterized.Parameter(2)
public AccessType accessType;
static ThreadLocal<Integer> threadNode = new ThreadLocal<>();
final AtomicInteger timestampGenerator = new AtomicInteger();
final ConcurrentSkipListMap<Integer, AtomicInteger> familyIds = new ConcurrentSkipListMap<>();
SessionFactory[] sessionFactories;
volatile boolean running = true;
final ThreadLocal<Map<Integer, List<Log<String>>>> familyNames = new ThreadLocal<Map<Integer, List<Log<String>>>>() {
@Override
protected Map<Integer, List<Log<String>>> initialValue() {
return new HashMap<>();
}
};
final ThreadLocal<Map<Integer, List<Log<Set<String>>>>> familyMembers = new ThreadLocal<Map<Integer, List<Log<Set<String>>>>>() {
@Override
protected Map<Integer, List<Log<Set<String>>>> initialValue() {
return new HashMap<>();
}
};
private BlockingDeque<Exception> exceptions = new LinkedBlockingDeque<>();
public String getDbName() {
return getClass().getName().replaceAll("\\W", "_");
}
public static class Jta extends CorrectnessTestCase {
private final TransactionManager transactionManager = TestingJtaPlatformImpl.transactionManager();
@Parameterized.Parameters(name = "{0}")
public List<Object[]> getParameters() {
return Arrays.<Object[]>asList(
new Object[] { "transactional, invalidation", CacheMode.INVALIDATION_SYNC, AccessType.TRANSACTIONAL },
new Object[] { "read-only, invalidation", CacheMode.INVALIDATION_SYNC, AccessType.READ_ONLY }, // maybe not needed
new Object[] { "read-write, invalidation", CacheMode.INVALIDATION_SYNC, AccessType.READ_WRITE },
new Object[] { "read-write, replicated", CacheMode.REPL_SYNC, AccessType.READ_WRITE },
new Object[] { "read-write, distributed", CacheMode.DIST_SYNC, AccessType.READ_WRITE },
new Object[] { "non-strict, replicated", CacheMode.REPL_SYNC, AccessType.NONSTRICT_READ_WRITE }
);
}
@Override
protected void applySettings(StandardServiceRegistryBuilder ssrb) {
super.applySettings(ssrb);
ssrb.applySetting( Environment.JTA_PLATFORM, TestingJtaPlatformImpl.class.getName() );
ssrb.applySetting( Environment.CONNECTION_PROVIDER, JtaAwareConnectionProviderImpl.class.getName() );
ssrb.applySetting( Environment.TRANSACTION_COORDINATOR_STRATEGY, JtaTransactionCoordinatorBuilderImpl.class.getName() );
}
@Override
protected Operation getOperation() {
if (accessType == AccessType.READ_ONLY) {
ThreadLocalRandom random = ThreadLocalRandom.current();
Operation operation;
int r = random.nextInt(30);
if (r == 0 && INVALIDATE_REGION) operation = new InvalidateCache();
else if (r < 5) operation = new QueryFamilies();
else if (r < 10) operation = new RemoveFamily(r < 12);
else operation = new ReadFamily(r < 20);
return operation;
} else {
return super.getOperation();
}
}
}
public static class NonJta extends CorrectnessTestCase {
@Parameterized.Parameters(name = "{0}")
public List<Object[]> getParameters() {
return Arrays.<Object[]>asList(
new Object[] { "read-write, invalidation", CacheMode.INVALIDATION_SYNC, AccessType.READ_WRITE },
new Object[] { "read-write, replicated", CacheMode.REPL_SYNC, AccessType.READ_WRITE },
new Object[] { "read-write, distributed", CacheMode.DIST_SYNC, AccessType.READ_WRITE },
new Object[] { "non-strict, replicated", CacheMode.REPL_SYNC, AccessType.NONSTRICT_READ_WRITE }
);
}
@Override
protected void applySettings(StandardServiceRegistryBuilder ssrb) {
super.applySettings(ssrb);
ssrb.applySetting(Environment.JTA_PLATFORM, NoJtaPlatform.class.getName());
ssrb.applySetting(Environment.TRANSACTION_COORDINATOR_STRATEGY, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class.getName());
}
}
@BeforeClassOnce
public void beforeClass() {
TestResourceTracker.testStarted(getClass().getSimpleName());
Arrays.asList(new File(System.getProperty("java.io.tmpdir"))
.listFiles((dir, name) -> name.startsWith("family_") || name.startsWith("invalidations-")))
.stream().forEach(f -> f.delete());
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().enableAutoClose()
.applySetting( Environment.USE_SECOND_LEVEL_CACHE, "true" )
.applySetting( Environment.USE_QUERY_CACHE, "true" )
.applySetting( Environment.DRIVER, "org.h2.Driver" )
.applySetting( Environment.URL, "jdbc:h2:mem:" + getDbName() + ";TRACE_LEVEL_FILE=4")
.applySetting( Environment.DIALECT, H2Dialect.class.getName() )
.applySetting( Environment.HBM2DDL_AUTO, "create-drop" )
.applySetting( TestRegionFactory.CONFIGURATION_HOOK, InjectFailures.class)
.applySetting( TestRegionFactory.CACHE_MODE, cacheMode )
.applySetting( Environment.USE_MINIMAL_PUTS, "false" )
.applySetting( Environment.GENERATE_STATISTICS, "false" );
applySettings(ssrb);
sessionFactories = new SessionFactory[NUM_NODES];
for (int i = 0; i < NUM_NODES; ++i) {
StandardServiceRegistry registry = ssrb.build();
Metadata metadata = buildMetadata( registry );
sessionFactories[i] = metadata.buildSessionFactory();
}
}
protected void applySettings(StandardServiceRegistryBuilder ssrb) {
ssrb.applySetting( Environment.DEFAULT_CACHE_CONCURRENCY_STRATEGY, accessType.getExternalName());
ssrb.applySetting(TestRegionFactory.TRANSACTIONAL, TestRegionFactoryProvider.load().supportTransactionalCaches() && accessType == AccessType.TRANSACTIONAL);
}
@AfterClassOnce
public void afterClass() {
for (SessionFactory sf : sessionFactories) {
if (sf != null) sf.close();
}
TestResourceTracker.testFinished(getClass().getSimpleName());
}
public static Class[] getAnnotatedClasses() {
return new Class[] {Family.class, Person.class, Address.class};
}
private Metadata buildMetadata(StandardServiceRegistry registry) {
MetadataSources metadataSources = new MetadataSources( registry );
for ( Class entityClass : getAnnotatedClasses() ) {
metadataSources.addAnnotatedClass( entityClass );
}
Metadata metadata = metadataSources.buildMetadata();
for ( PersistentClass entityBinding : metadata.getEntityBindings() ) {
if (!entityBinding.isInherited()) {
( (RootClass) entityBinding ).setCacheConcurrencyStrategy( accessType.getExternalName() );
}
}
// Collections don't have integrated version, these piggyback on parent's owner version (for DB).
// However, this version number isn't extractable and is not passed to cache methods.
AccessType collectionAccessType = accessType == AccessType.NONSTRICT_READ_WRITE ? AccessType.READ_WRITE : accessType;
for ( Collection collectionBinding : metadata.getCollectionBindings() ) {
collectionBinding.setCacheConcurrencyStrategy( collectionAccessType.getExternalName() );
}
return metadata;
}
public static class InducedException extends Exception {
public InducedException(String message) {
super(message);
}
}
public static class FailureInducingInterceptor extends BaseAsyncInterceptor {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
// Failure in CommitCommand/RollbackCommand keeps some locks closed, therefore blocking the test
if (!(command instanceof CommitCommand || command instanceof RollbackCommand)) {
/* Introduce 5 % probability of failure */
if (ThreadLocalRandom.current().nextInt(100) < 5) {
throw new InducedException("Simulating failure somewhere");
}
}
return invokeNext(ctx, command);
}
}
public static class InjectFailures extends TestConfigurationHook {
public InjectFailures(Properties properties) {
super(properties);
}
@Override
public void amendCacheConfiguration(String cacheName, ConfigurationBuilder configurationBuilder) {
super.amendCacheConfiguration(cacheName, configurationBuilder);
configurationBuilder.transaction().cacheStopTimeout(1, TimeUnit.SECONDS);
if (INJECT_FAILURES) {
// failure to write into timestamps would cause failure even though both DB and cache has been updated
if (!cacheName.equals("timestamps") && !cacheName.endsWith(InfinispanProperties.DEF_PENDING_PUTS_RESOURCE)) {
configurationBuilder.customInterceptors().addInterceptor()
.interceptorClass(FailureInducingInterceptor.class)
.position(InterceptorConfiguration.Position.FIRST);
log.trace("Injecting FailureInducingInterceptor into " + cacheName);
} else {
log.trace("Not injecting into " + cacheName);
}
}
}
}
private final static Class[][] EXPECTED = {
{TransactionException.class, RollbackException.class, StaleObjectStateException.class},
{TransactionException.class, RollbackException.class, PessimisticLockException.class},
{TransactionException.class, RollbackException.class, LockAcquisitionException.class},
{RemoteException.class, TimeoutException.class},
{StaleStateException.class, PessimisticLockException.class},
{StaleStateException.class, ObjectNotFoundException.class},
{StaleStateException.class, ConstraintViolationException.class},
{StaleStateException.class, LockAcquisitionException.class},
{PersistenceException.class, ConstraintViolationException.class},
{PersistenceException.class, LockAcquisitionException.class},
{jakarta.persistence.PessimisticLockException.class, PessimisticLockException.class},
{OptimisticLockException.class, StaleStateException.class},
{PessimisticLockException.class},
{StaleObjectStateException.class},
{ObjectNotFoundException.class},
{LockAcquisitionException.class}
};
@Test
public void test() throws Exception {
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
Map<Integer, List<Log<String>>> allFamilyNames = new HashMap<>();
Map<Integer, List<Log<Set<String>>>> allFamilyMembers = new HashMap<>();
running = true;
List<Future<Void>> futures = new ArrayList<>();
for (int node = 0; node < NUM_NODES; ++node) {
final int NODE = node;
for (int i = 0; i < NUM_THREADS_PER_NODE; ++i) {
final int I = i;
futures.add(exec.submit(() -> {
Thread.currentThread().setName("Node" + (char)('A' + NODE) + "-thread-" + I);
threadNode.set(NODE);
while (running) {
Operation operation;
if (familyIds.size() < NUM_FAMILIES) {
operation = new InsertFamily(ThreadLocalRandom.current().nextInt(5) == 0);
} else {
operation = getOperation();
}
try {
operation.run();
} catch (Exception e) {
// ignore exceptions from optimistic failures and induced exceptions
if (hasCause(e, InducedException.class)) {
continue;
} else if (Stream.of(EXPECTED).anyMatch(exceptions -> matches(e, exceptions))) {
continue;
}
exceptions.add(e);
log.error("Failed " + operation.getClass().getName(), e);
}
}
synchronized (allFamilyNames) {
for (Map.Entry<Integer, List<Log<String>>> entry : familyNames.get().entrySet()) {
List<Log<String>> list = allFamilyNames.get(entry.getKey());
if (list == null) allFamilyNames.put(entry.getKey(), list = new ArrayList<>());
list.addAll(entry.getValue());
}
for (Map.Entry<Integer, List<Log<Set<String>>>> entry : familyMembers.get().entrySet()) {
List<Log<Set<String>>> list = allFamilyMembers.get(entry.getKey());
if (list == null) allFamilyMembers.put(entry.getKey(), list = new ArrayList<>());
list.addAll(entry.getValue());
}
}
return null;
}));
}
}
Exception failure = exceptions.poll(EXECUTION_TIME, TimeUnit.MILLISECONDS);
if (failure != null) exceptions.addFirst(failure);
running = false;
exec.shutdown();
if (!exec.awaitTermination(1000, TimeUnit.SECONDS)) throw new IllegalStateException();
for (Future<Void> f : futures) {
f.get(); // check for exceptions
}
checkForEmptyPendingPuts();
log.infof("Generated %d timestamps%n", timestampGenerator.get());
AtomicInteger created = new AtomicInteger();
AtomicInteger removed = new AtomicInteger();
ForkJoinPool threadPool = ForkJoinPool.commonPool();
ArrayList<ForkJoinTask<?>> tasks = new ArrayList<>();
for (Map.Entry<Integer, List<Log<String>>> entry : allFamilyNames.entrySet()) {
tasks.add(threadPool.submit(() -> {
int familyId = entry.getKey();
List<Log<String>> list = entry.getValue();
created.incrementAndGet();
NavigableMap<Integer, List<Log<String>>> logByTime = getWritesAtTime(list);
checkCorrectness("family_name-" + familyId + "-", list, logByTime);
if (list.stream().anyMatch(l -> l.type == LogType.WRITE && l.getValue() == null)) {
removed.incrementAndGet();
}
}));
}
for (Map.Entry<Integer, List<Log<Set<String>>>> entry : allFamilyMembers.entrySet()) {
tasks.add(threadPool.submit(() -> {
int familyId = entry.getKey();
List<Log<Set<String>>> list = entry.getValue();
NavigableMap<Integer, List<Log<Set<String>>>> logByTime = getWritesAtTime(list);
checkCorrectness("family_members-" + familyId + "-", list, logByTime);
}));
}
for (ForkJoinTask<?> task : tasks) {
// with heavy logging this may have trouble to complete
task.get(30, TimeUnit.SECONDS);
}
if (!exceptions.isEmpty()) {
for (Exception e : exceptions) {
log.error("Test failure", e);
}
throw new IllegalStateException("There were " + exceptions.size() + " exceptions");
}
log.infof("Created %d families, removed %d%n", created.get(), removed.get());
}
private static class DelayedInvalidators {
final ConcurrentMap map;
final Object key;
public DelayedInvalidators(ConcurrentMap map, Object key) {
this.map = map;
this.key = key;
}
public Object getPendingPutMap() {
return map.get(key);
}
}
protected void checkForEmptyPendingPuts() throws Exception {
Field pp = PutFromLoadValidator.class.getDeclaredField("pendingPuts");
pp.setAccessible(true);
Method getInvalidators = null;
List<DelayedInvalidators> delayed = new LinkedList<>();
for (int i = 0; i < sessionFactories.length; i++) {
SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactories[i];
for (String regionName : sfi.getCache().getCacheRegionNames()) {
PutFromLoadValidator validator = getPutFromLoadValidator(sfi, regionName);
if (validator == null) {
log.warn("No validator for " + regionName);
continue;
}
ConcurrentMap<Object, Object> map = (ConcurrentMap) pp.get(validator);
for (Iterator<Map.Entry<Object, Object>> iterator = map.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry entry = iterator.next();
if (getInvalidators == null) {
getInvalidators = entry.getValue().getClass().getMethod("getInvalidators");
getInvalidators.setAccessible(true);
}
java.util.Collection invalidators = (java.util.Collection) getInvalidators.invoke(entry.getValue());
if (invalidators != null && !invalidators.isEmpty()) {
delayed.add(new DelayedInvalidators(map, entry.getKey()));
}
}
}
}
// poll until all invalidations come
long deadline = System.currentTimeMillis() + 30000;
while (System.currentTimeMillis() < deadline) {
iterateInvalidators(delayed, getInvalidators, (k, i) -> {});
if (delayed.isEmpty()) {
break;
}
Thread.sleep(1000);
}
if (!delayed.isEmpty()) {
iterateInvalidators(delayed, getInvalidators, (k, i) -> log.warnf("Left invalidators on key %s: %s", k, i));
throw new IllegalStateException("Invalidators were not cleared: " + delayed.size());
}
}
private void iterateInvalidators(List<DelayedInvalidators> delayed, Method getInvalidators, BiConsumer<Object, java.util.Collection> invalidatorConsumer) throws IllegalAccessException, InvocationTargetException {
for (Iterator<DelayedInvalidators> iterator = delayed.iterator(); iterator.hasNext(); ) {
DelayedInvalidators entry = iterator.next();
Object pendingPutMap = entry.getPendingPutMap();
if (pendingPutMap == null) {
iterator.remove();
}
else {
java.util.Collection invalidators = (java.util.Collection) getInvalidators.invoke(pendingPutMap);
if (invalidators == null || invalidators.isEmpty()) {
iterator.remove();
}
invalidatorConsumer.accept(entry.key, invalidators);
}
}
}
private boolean hasCause(Throwable throwable, Class<? extends Throwable> clazz) {
if (throwable == null) return false;
Throwable cause = throwable.getCause();
if (throwable == cause) return false;
if (clazz.isInstance(cause)) return true;
return hasCause(cause, clazz);
}
private boolean matches(Throwable throwable, Class[] classes) {
return matches(throwable, classes, 0);
}
private boolean matches(Throwable throwable, Class[] classes, int index) {
return index >= classes.length || (classes[index].isInstance(throwable) && matches(throwable.getCause(), classes, index + 1));
}
protected Operation getOperation() {
ThreadLocalRandom random = ThreadLocalRandom.current();
Operation operation;
int r = random.nextInt(100);
if (r == 0 && INVALIDATE_REGION) operation = new InvalidateCache();
else if (r < 5) operation = new QueryFamilies();
else if (r < 10) operation = new RemoveFamily(r < 6);
else if (r < 20) operation = new UpdateFamily(r < 12, random.nextInt(1, 3));
else if (r < 35) operation = new AddMember(r < 25);
else if (r < 50) operation = new RemoveMember(r < 40);
else operation = new ReadFamily(r < 75);
return operation;
}
private <T> NavigableMap<Integer, List<Log<T>>> getWritesAtTime(List<Log<T>> list) {
NavigableMap<Integer, List<Log<T>>> writes = new TreeMap<>();
for (Log log : list) {
if (log.type != LogType.WRITE) continue;
for (int time = log.before; time <= log.after; ++time) {
List<Log<T>> onTime = writes.get(time);
if (onTime == null) {
writes.put(time, onTime = new ArrayList<>());
}
onTime.add(log);
}
}
return writes;
}
private <T> void checkCorrectness(String dumpPrefix, List<Log<T>> logs, NavigableMap<Integer, List<Log<T>>> writesByTime) {
Collections.sort(logs, WALL_CLOCK_TIME_COMPARATOR);
int nullReads = 0, reads = 0, writes = 0;
for (Log read : logs) {
if (read.type != LogType.READ) {
writes++;
continue;
}
if (read.getValue() == null || isEmptyCollection(read)) nullReads++;
else reads++;
Map<T, Log<T>> possibleValues = new HashMap<>();
for (List<Log<T>> list : writesByTime.subMap(read.before, true, read.after, true).values()) {
for (Log<T> write : list) {
if (read.precedes(write)) continue;
possibleValues.put(write.getValue(), write);
}
}
int startOfLastWriteBeforeRead = 0;
for (Map.Entry<Integer, List<Log<T>>> entry : writesByTime.headMap(read.before, false).descendingMap().entrySet()) {
int time = entry.getKey();
if (time < startOfLastWriteBeforeRead) break;
for (Log<T> write : entry.getValue()) {
if (write.after < read.before && write.before > startOfLastWriteBeforeRead) {
startOfLastWriteBeforeRead = write.before;
}
possibleValues.put(write.getValue(), write);
}
}
if (possibleValues.isEmpty()) {
// the entry was not created at all (first write failed)
break;
}
if (!possibleValues.containsKey(read.getValue())) {
dumpLogs(dumpPrefix, logs);
exceptions.add(new IllegalStateException(String.format("R %s: %d .. %d (%s, %s) -> %s not in %s (%d+)", dumpPrefix,
read.before, read.after, read.threadName, new SimpleDateFormat("HH:mm:ss,SSS").format(new Date(read.wallClockTime)),
read.getValue(), possibleValues.values(), startOfLastWriteBeforeRead)));
break;
}
}
log.infof("Checked %d null reads, %d reads and %d writes%n", nullReads, reads, writes);
}
private <T> void dumpLogs(String prefix, List<Log<T>> logs) {
try {
File f = File.createTempFile(prefix, ".log");
log.info("Dumping logs into " + f.getAbsolutePath());
try (BufferedWriter writer = Files.newBufferedWriter(f.toPath())) {
for (Log<T> log : logs) {
writer.write(log.toString());
writer.write('\n');
}
}
} catch (IOException e) {
log.error("Failed to dump family logs");
}
}
private static boolean isEmptyCollection(Log read) {
return read.getValue() instanceof java.util.Collection && ((java.util.Collection) read.getValue()).isEmpty();
}
private abstract class Operation {
protected final boolean rolledBack;
public Operation(boolean rolledBack) {
this.rolledBack = rolledBack;
}
public abstract void run() throws Exception;
protected void withSession(Consumer<Session> consumer) throws Exception {
int node = threadNode.get();
Session s = sessionFactory(node).openSession();
Transaction tx = s.getTransaction();
tx.begin();
try {
consumer.accept(s);
} catch (Exception e) {
tx.markRollbackOnly();
throw e;
} finally {
try {
if (!rolledBack && tx.getStatus() == TransactionStatus.ACTIVE) {
log.trace("Hibernate commit begin");
tx.commit();
log.trace("Hibernate commit end");
} else {
log.trace("Hibernate rollback begin");
tx.rollback();
log.trace("Hibernate rollback end");
}
} catch (Exception e) {
log.trace("Hibernate commit or rollback failed, status is " + tx.getStatus(), e);
if (tx.getStatus() == TransactionStatus.MARKED_ROLLBACK) {
tx.rollback();
}
throw e;
} finally {
// cannot close before XA commit since force increment requires open connection
s.close();
}
}
}
protected void withRandomFamily(BiConsumer<Session, Family> consumer, Ref<String> familyNameUpdate, Ref<Set<String>> familyMembersUpdate, LockMode lockMode) throws Exception {
int id = randomFamilyId(ThreadLocalRandom.current());
int before = timestampGenerator.getAndIncrement();
log.tracef("Started %s(%d, %s) at %d", getClass().getSimpleName(), id, rolledBack, before);
Log<String> familyNameLog = new Log<>();
Log<Set<String>> familyMembersLog = new Log<>();
boolean failure = false;
try {
withSession(s -> {
Family f = lockMode != null ? s.get(Family.class, id, lockMode) : s.get(Family.class, id);
if (f == null) {
familyNameLog.setValue(null);
familyMembersLog.setValue(Collections.EMPTY_SET);
familyNotFound(id);
} else {
familyNameLog.setValue(f.getName());
familyMembersLog.setValue(membersToNames(f.getMembers()));
consumer.accept(s, f);
}
});
} catch (Exception e) {
failure = true;
throw e;
} finally {
int after = timestampGenerator.getAndIncrement();
recordReadWrite(id, before, after, failure, familyNameUpdate, familyMembersUpdate, familyNameLog, familyMembersLog);
}
}
protected void withRandomFamilies(int numFamilies, BiConsumer<Session, Family[]> consumer, String[] familyNameUpdates, Set<String>[] familyMembersUpdates, LockMode lockMode) throws Exception {
int ids[] = new int[numFamilies];
Log<String>[] familyNameLogs = new Log[numFamilies];
Log<Set<String>>[] familyMembersLogs = new Log[numFamilies];
for (int i = 0; i < numFamilies; ++i) {
ids[i] = randomFamilyId(ThreadLocalRandom.current());
familyNameLogs[i] = new Log<>();
familyMembersLogs[i] = new Log<>();
}
int before = timestampGenerator.getAndIncrement();
log.tracef("Started %s(%s) at %d", getClass().getSimpleName(), Arrays.toString(ids), before);
boolean failure = false;
try {
withSession(s -> {
Family[] families = new Family[numFamilies];
for (int i = 0; i < numFamilies; ++i) {
Family f = lockMode != null ? s.get(Family.class, ids[i], lockMode) : s.get(Family.class, ids[i]);
families[i] = f;
if (f == null) {
familyNameLogs[i].setValue(null);
familyMembersLogs[i].setValue(Collections.EMPTY_SET);
familyNotFound(ids[i]);
} else {
familyNameLogs[i].setValue(f.getName());
familyMembersLogs[i].setValue(membersToNames(f.getMembers()));
}
}
consumer.accept(s, families);
});
} catch (Exception e) {
failure = true;
throw e;
} finally {
int after = timestampGenerator.getAndIncrement();
for (int i = 0; i < numFamilies; ++i) {
recordReadWrite(ids[i], before, after, failure,
familyNameUpdates != null ? Ref.of(familyNameUpdates[i]) : Ref.empty(),
familyMembersUpdates != null ? Ref.of(familyMembersUpdates[i]) : Ref.empty(),
familyNameLogs[i], familyMembersLogs[i]);
}
}
}
private void recordReadWrite(int id, int before, int after, boolean failure, Ref<String> familyNameUpdate, Ref<Set<String>> familyMembersUpdate, Log<String> familyNameLog, Log<Set<String>> familyMembersLog) {
log.tracef("Finished %s at %d", getClass().getSimpleName(), after);
LogType readType, writeType;
if (failure || rolledBack) {
writeType = LogType.WRITE_FAILURE;
readType = LogType.READ_FAILURE;
} else {
writeType = LogType.WRITE;
readType = LogType.READ;
}
familyNameLog.setType(readType).setTimes(before, after);
familyMembersLog.setType(readType).setTimes(before, after);
getRecordList(familyNames, id).add(familyNameLog);
getRecordList(familyMembers, id).add(familyMembersLog);
if (familyNameLog.getValue() != null) {
if (familyNameUpdate.isSet()) {
getRecordList(familyNames, id).add(new Log<>(before, after, familyNameUpdate.get(), writeType, familyNameLog));
}
if (familyMembersUpdate.isSet()) {
getRecordList(familyMembers, id).add(new Log<>(before, after, familyMembersUpdate.get(), writeType, familyMembersLog));
}
}
}
}
private class InsertFamily extends Operation {
public InsertFamily(boolean rolledBack) {
super(rolledBack);
}
@Override
public void run() throws Exception {
Family family = createFamily();
int before = timestampGenerator.getAndIncrement();
log.trace("Started InsertFamily at " + before);
boolean failure = false;
try {
withSession(s -> s.persist(family));
} catch (Exception e) {
failure = true;
throw e;
} finally {
int after = timestampGenerator.getAndIncrement();
log.trace("Finished InsertFamily at " + after + ", " + (failure ? "failed" : "success"));
familyIds.put(family.getId(), new AtomicInteger(NUM_ACCESS_AFTER_REMOVAL));
LogType type = failure || rolledBack ? LogType.WRITE_FAILURE : LogType.WRITE;
getRecordList(familyNames, family.getId()).add(new Log<>(before, after, family.getName(), type));
getRecordList(familyMembers, family.getId()).add(new Log<>(before, after, membersToNames(family.getMembers()), type));
}
}
}
private Set<String> membersToNames(Set<Person> members) {
return members.stream().map(p -> p.getFirstName()).collect(Collectors.toSet());
}
private class ReadFamily extends Operation {
private final boolean evict;
public ReadFamily(boolean evict) {
super(false);
this.evict = evict;
}
@Override
public void run() throws Exception {
withRandomFamily((s, f) -> {
if (evict) {
sessionFactory(threadNode.get()).getCache().evictEntityData(Family.class, f.getId());
}
}, Ref.empty(), Ref.empty(), null);
}
}
private class UpdateFamily extends Operation {
private final int numUpdates;
public UpdateFamily(boolean rolledBack, int numUpdates) {
super(rolledBack);
this.numUpdates = numUpdates;
}
@Override
public void run() throws Exception {
String[] newNames = new String[numUpdates];
for (int i = 0; i < numUpdates; ++i) {
newNames[i] = randomString(ThreadLocalRandom.current());
}
withRandomFamilies(numUpdates, (s, families) -> {
for (int i = 0; i < numUpdates; ++i) {
Family f = families[i];
if (f != null) {
f.setName(newNames[i]);
s.persist(f);
}
}
}, newNames, null, LockMode.OPTIMISTIC_FORCE_INCREMENT);
}
}
private class RemoveFamily extends Operation {
public RemoveFamily(boolean rolledBack) {
super(rolledBack);
}
@Override
public void run() throws Exception {
withRandomFamily((s, f) -> s.delete(f), Ref.of(null), Ref.of(Collections.EMPTY_SET), LockMode.OPTIMISTIC);
}
}
private abstract class MemberOperation extends Operation {
public MemberOperation(boolean rolledBack) {
super(rolledBack);
}
@Override
public void run() throws Exception {
Ref<Set<String>> newMembers = new Ref<>();
withRandomFamily((s, f) -> {
boolean updated = updateMembers(s, ThreadLocalRandom.current(), f);
if (updated) {
newMembers.set(membersToNames(f.getMembers()));
s.persist(f);
}
}, Ref.empty(), newMembers, LockMode.OPTIMISTIC_FORCE_INCREMENT);
}
protected abstract boolean updateMembers(Session s, ThreadLocalRandom random, Family f);
}
private class AddMember extends MemberOperation {
public AddMember(boolean rolledBack) {
super(rolledBack);
}
protected boolean updateMembers(Session s, ThreadLocalRandom random, Family f) {
Set<Person> members = f.getMembers();
if (members.size() < MAX_MEMBERS) {
members.add(createPerson(random, f));
return true;
} else {
return false;
}
}
}
private class RemoveMember extends MemberOperation {
public RemoveMember(boolean rolledBack) {
super(rolledBack);
}
@Override
protected boolean updateMembers(Session s, ThreadLocalRandom random, Family f) {
int numMembers = f.getMembers().size();
if (numMembers > 0) {
Iterator<Person> it = f.getMembers().iterator();
Person person = null;
for (int i = random.nextInt(numMembers); i >= 0; --i) {
person = it.next();
}
it.remove();
if (person != null) {
s.delete(person);
}
return true;
} else {
return false;
}
}
}
private class QueryFamilies extends Operation {
final static int MAX_RESULTS = 10;
public QueryFamilies() {
super(false);
}
@Override
public void run() throws Exception {
String prefix = new StringBuilder(2)
.append((char) ThreadLocalRandom.current().nextInt('A', 'Z' + 1)).append('%').toString();
int[] ids = new int[MAX_RESULTS];
String[] names = new String[MAX_RESULTS];
Set<String>[] members = new Set[MAX_RESULTS];
int before = timestampGenerator.getAndIncrement();
log.tracef("Started QueryFamilies at %d", before);
withSession(s -> {
HibernateCriteriaBuilder cb = s.getCriteriaBuilder();
CriteriaQuery<Family> criteria = cb.createQuery(Family.class);
Root<Family> root = criteria.from(Family.class);
criteria.where(cb.like(root.get(Family_.name), prefix));
List<Family> results = s.createQuery(criteria)
.setMaxResults(MAX_RESULTS)
.setHint(QueryHints.HINT_CACHEABLE, "true")
.getResultList();
int index = 0;
for (Family f : results) {
ids[index] = f.getId();
names[index] = f.getName();
members[index] = membersToNames(f.getMembers());
++index;
}
});
int after = timestampGenerator.getAndIncrement();
log.tracef("Finished QueryFamilies at %d", after);
for (int index = 0; index < MAX_RESULTS; ++index) {
if (names[index] == null) break;
getRecordList(familyNames, ids[index]).add(new Log<>(before, after, names[index], LogType.READ));
getRecordList(familyMembers, ids[index]).add(new Log<>(before, after, members[index], LogType.READ));
}
}
}
private class InvalidateCache extends Operation {
public InvalidateCache() {
super(false);
}
@Override
public void run() throws Exception {
log.trace("Invalidating all caches");
int node = threadNode.get();
sessionFactory(node).getCache().evictAllRegions();
}
}
private PutFromLoadValidator getPutFromLoadValidator(SessionFactoryImplementor sfi, String regionName) throws NoSuchFieldException, IllegalAccessException {
// TODO not sure if this is correct.
CachedDomainDataAccess strategy = sfi.getMetamodel().entityPersister(Family.class).getCacheAccessStrategy();
if (strategy == null) {
return null;
}
Field delegateField = getField(strategy.getClass(), "delegate");
Object delegate = delegateField.get(strategy);
if (delegate == null) {
return null;
}
if (InvalidationCacheAccessDelegate.class.isInstance(delegate)) {
Field validatorField = InvalidationCacheAccessDelegate.class.getDeclaredField("putValidator");
validatorField.setAccessible(true);
return (PutFromLoadValidator) validatorField.get(delegate);
} else {
return null;
}
}
private Field getField(Class<?> clazz, String fieldName) {
Field f = null;
while (clazz != null && clazz != Object.class) {
try {
f = clazz.getDeclaredField(fieldName);
break;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
}
if (f != null) {
f.setAccessible(true);
}
return f;
}
protected SessionFactory sessionFactory(int node) {
return sessionFactories[node];
}
private void familyNotFound(int id) {
AtomicInteger access = familyIds.get(id);
if (access == null) return;
if (access.decrementAndGet() == 0) {
familyIds.remove(id);
}
}
private <T> List<T> getRecordList(ThreadLocal<Map<Integer, List<T>>> tlListMap, int id) {
Map<Integer, List<T>> map = tlListMap.get();
List<T> list = map.get(id);
if (list == null) map.put(id, list = new ArrayList<>());
return list;
}
private int randomFamilyId(ThreadLocalRandom random) {
Map.Entry<Integer, AtomicInteger> first = familyIds.firstEntry();
Map.Entry<Integer, AtomicInteger> last = familyIds.lastEntry();
if (first == null || last == null) return 0;
Map.Entry<Integer, AtomicInteger> ceiling = familyIds.ceilingEntry(random.nextInt(first.getKey(), last.getKey() + 1));
return ceiling == null ? 0 : ceiling.getKey();
}
private static Family createFamily() {
ThreadLocalRandom random = ThreadLocalRandom.current();
String familyName = randomString(random);
Family f = new Family(familyName);
HashSet<Person> members = new HashSet<>();
members.add(createPerson(random, f));
f.setMembers(members);
return f;
}
private static Person createPerson(ThreadLocalRandom random, Family family) {
return new Person(randomString(random), family);
}
private static String randomString(ThreadLocalRandom random) {
StringBuilder sb = new StringBuilder(10);
for (int i = 0; i < 10; ++i) {
sb.append((char) random.nextInt('A', 'Z' + 1));
}
return sb.toString();
}
private enum LogType {
READ('R'), WRITE('W'), READ_FAILURE('L'), WRITE_FAILURE('F');
private final char shortName;
LogType(char shortName) {
this.shortName = shortName;
}
}
private class Log<T> {
int before;
int after;
T value;
LogType type;
Log[] preceding;
String threadName;
long wallClockTime;
public Log(int time) {
this();
this.before = time;
this.after = time;
}
public Log(int before, int after, T value, LogType type, Log<T>... preceding) {
this();
this.before = before;
this.after = after;
this.value = value;
this.type = type;
this.preceding = preceding;
}
public Log() {
threadName = Thread.currentThread().getName();
wallClockTime = System.currentTimeMillis();
}
public Log setType(LogType type) {
this.type = type;
return this;
}
public void setTimes(int before, int after) {
this.before = before;
this.after = after;
}
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public boolean precedes(Log<T> write) {
if (write.preceding == null) return false;
for (Log<T> l : write.preceding) {
if (l == this) return true;
}
return false;
}
@Override
public String toString() {
return String.format("%c: %5d - %5d\t(%s,\t%s)\t%s", type.shortName, before, after,
new SimpleDateFormat("HH:mm:ss,SSS").format(new Date(wallClockTime)), threadName, value);
}
}
private static class Ref<T> {
private static Ref EMPTY = new Ref() {
@Override
public void set(Object value) {
throw new UnsupportedOperationException();
}
};
private boolean set;
private T value;
public static <T> Ref<T> empty() {
return EMPTY;
}
public static <T> Ref<T> of(T value) {
Ref ref = new Ref();
ref.set(value);
return ref;
}
public boolean isSet() {
return set;
}
public T get() {
return value;
}
public void set(T value) {
this.value = value;
this.set = true;
}
}
}
| 48,496
| 39.856782
| 215
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/stress/PutFromLoadStressTestCase.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.stress;
import static org.infinispan.test.hibernate.cache.commons.util.TestingUtil.withTx;
import static org.junit.Assert.assertFalse;
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 java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
import org.hibernate.query.Query;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Age;
import org.infinispan.test.hibernate.cache.commons.tm.NarayanaStandaloneJtaPlatform;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import jakarta.transaction.TransactionManager;
/**
* A stress test for putFromLoad operations
*
* @author Galder Zamarreño
* @since 4.1
*/
@Ignore
public class PutFromLoadStressTestCase {
static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(PutFromLoadStressTestCase.class);
static final int NUM_THREADS = 100;
static final int WARMUP_TIME_SECS = 10;
static final long RUNNING_TIME_SECS = Integer.getInteger("time", 60);
static final long LAUNCH_INTERVAL_MILLIS = 10;
static final int NUM_INSTANCES = 5000;
static SessionFactory sessionFactory;
static TransactionManager tm;
final AtomicBoolean run = new AtomicBoolean(true);
@BeforeClass
public static void beforeClass() {
// Extra options located in src/test/resources/hibernate.properties
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
.applySetting( Environment.USE_SECOND_LEVEL_CACHE, "true" )
.applySetting( Environment.USE_QUERY_CACHE, "true" )
// TODO: Tweak to have a fully local region factory (no transport, cache mode = local, no marshalling, ...etc)
.applySetting(
Environment.CACHE_REGION_FACTORY,
"org.infinispan.hibernate.cache.InfinispanRegionFactory"
)
.applySetting(
Environment.JTA_PLATFORM,
new NarayanaStandaloneJtaPlatform()
)
// Force minimal puts off to simplify stressing putFromLoad logic
.applySetting( Environment.USE_MINIMAL_PUTS, "false" )
.applySetting( Environment.HBM2DDL_AUTO, "create-drop" );
StandardServiceRegistry serviceRegistry = ssrb.build();
MetadataSources metadataSources = new MetadataSources( serviceRegistry )
.addResource( "cache/infinispan/functional/Item.hbm.xml" )
.addResource( "cache/infinispan/functional/Customer.hbm.xml" )
.addResource( "cache/infinispan/functional/Contact.hbm.xml" )
.addAnnotatedClass( Age.class );
Metadata metadata = metadataSources.buildMetadata();
for ( PersistentClass entityBinding : metadata.getEntityBindings() ) {
if ( entityBinding instanceof RootClass ) {
( (RootClass) entityBinding ).setCacheConcurrencyStrategy( "transactional" );
}
}
for ( Collection collectionBinding : metadata.getCollectionBindings() ) {
collectionBinding.setCacheConcurrencyStrategy( "transactional" );
}
sessionFactory = metadata.buildSessionFactory();
tm = com.arjuna.ats.jta.TransactionManager.transactionManager();
}
@AfterClass
public static void afterClass() {
sessionFactory.close();
}
@Test
public void testQueryPerformance() throws Exception {
store();
// doTest(true);
// run.set(true); // Reset run
doTest(false);
}
private void store() throws Exception {
for (int i = 0; i < NUM_INSTANCES; i++) {
final Age age = new Age();
age.setAge(i);
withTx(tm, new Callable<Void>() {
@Override
public Void call() throws Exception {
Session s = sessionFactory.openSession();
s.getTransaction().begin();
s.persist(age);
s.getTransaction().commit();
s.close();
return null;
}
});
}
}
private void doTest(boolean warmup) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
try {
CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS + 1);
List<Future<String>> futures = new ArrayList<Future<String>>(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; i++) {
Future<String> future = executor.submit(
new SelectQueryRunner(barrier, warmup, i + 1));
futures.add(future);
Thread.sleep(LAUNCH_INTERVAL_MILLIS);
}
barrier.await(); // wait for all threads to be ready
long timeout = warmup ? WARMUP_TIME_SECS : RUNNING_TIME_SECS;
TimeUnit unit = TimeUnit.SECONDS;
Thread.sleep(unit.toMillis(timeout)); // Wait for the duration of the test
run.set(false); // Instruct tests to stop doing work
barrier.await(2, TimeUnit.MINUTES); // wait for all threads to finish
log.infof("[%s] All threads finished, check for exceptions", title(warmup));
for (Future<String> future : futures) {
String opsPerMS = future.get();
if (!warmup)
log.infof("[%s] Operations/ms: %s", title(warmup), opsPerMS);
}
log.infof("[%s] All future gets checked", title(warmup));
} catch (Exception e) {
log.errorf(e, "Error in one of the execution threads during %s", title(warmup));
throw e;
} finally {
executor.shutdownNow();
}
}
private String title(boolean warmup) {
return warmup ? "warmup" : "stress";
}
public class SelectQueryRunner implements Callable<String> {
final CyclicBarrier barrier;
final boolean warmup;
final Integer customerId;
public SelectQueryRunner(CyclicBarrier barrier, boolean warmup, Integer customerId) {
this.barrier = barrier;
this.warmup = warmup;
this.customerId = customerId;
}
@Override
public String call() throws Exception {
try {
if (log.isTraceEnabled())
log.tracef("[%s] Wait for all executions paths to be ready to perform calls", title(warmup));
barrier.await();
long start = System.nanoTime();
int runs = 0;
if (log.isTraceEnabled()) {
log.tracef("[%s] Start time: %d", title(warmup), start);
}
queryItems();
long end = System.nanoTime();
long duration = end - start;
if (log.isTraceEnabled())
log.tracef("[%s] End time: %d, duration: %d, runs: %d",
title(warmup), start, duration, runs);
return opsPerMS(duration, runs);
} finally {
if (log.isTraceEnabled())
log.tracef("[%s] Wait for all execution paths to finish", title(warmup));
barrier.await();
}
}
private void deleteCachedItems() throws Exception {
withTx(tm, new Callable<Void>() {
@Override
public Void call() throws Exception {
sessionFactory.getCache().evictEntityData(Age.class);
return null;
}
});
}
private void queryItems() throws Exception {
withTx(tm, new Callable<Void>() {
@Override
public Void call() throws Exception {
Session s = sessionFactory.getCurrentSession();
Query query = s.getNamedQuery(Age.QUERY).setCacheable(true);
List<Age> result = (List<Age>) query.list();
assertFalse(result.isEmpty());
return null;
}
});
}
private String opsPerMS(long nanos, int ops) {
long totalMillis = TimeUnit.NANOSECONDS.toMillis(nanos);
if (totalMillis > 0)
return ops / totalMillis + " ops/ms";
else
return "NAN ops/ms";
}
}
}
| 9,107
| 35.142857
| 124
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/stress/SecondLevelCacheStressTestCase.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.stress;
import static org.infinispan.test.hibernate.cache.commons.util.TestingUtil.withTx;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
import org.hibernate.query.Query;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
import org.infinispan.test.hibernate.cache.commons.stress.entities.Address;
import org.infinispan.test.hibernate.cache.commons.stress.entities.Family;
import org.infinispan.test.hibernate.cache.commons.stress.entities.Person;
import org.infinispan.test.hibernate.cache.commons.tm.NarayanaStandaloneJtaPlatform;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import jakarta.transaction.TransactionManager;
/**
* Stress test for second level cache.
*
* TODO Various:
* - Switch to a JDBC connection pool to avoid too many connections created
* (as well as consuming memory, it's expensive to create)
* - Use barrier associated execution tasks at the beginning and end to track
* down start/end times for runs.
*
* @author Galder Zamarreño
* @since 4.1
*/
@Ignore
public class SecondLevelCacheStressTestCase {
static final int NUM_THREADS = 10;
static final long WARMUP_TIME = TimeUnit.SECONDS.toNanos(Integer.getInteger("warmup-time", 1) * 5);
static final long RUNNING_TIME = TimeUnit.SECONDS.toNanos(Integer.getInteger("time", 1) * 60);
static final boolean PROFILE = Boolean.getBoolean("profile");
static final boolean ALLOCATION = Boolean.getBoolean("allocation");
static final int RUN_COUNT_LIMIT = Integer.getInteger("count", 1000); // max number of runs per operation
static final Random RANDOM = new Random(12345);
String provider;
Set<Integer> updatedIds;
Queue<Integer> removeIds;
SessionFactory sessionFactory;
TransactionManager tm;
volatile int numEntities;
@Before
public void beforeClass() {
provider = getProvider();
updatedIds = ConcurrentHashMap.newKeySet();
removeIds = new ConcurrentLinkedQueue<Integer>();
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().enableAutoClose()
.applySetting( Environment.USE_SECOND_LEVEL_CACHE, "true" )
.applySetting( Environment.USE_QUERY_CACHE, "true" )
.applySetting( Environment.DRIVER, "com.mysql.jdbc.Driver" )
.applySetting( Environment.URL, "jdbc:mysql://localhost:3306/hibernate" )
.applySetting( Environment.DIALECT, "org.hibernate.dialect.MySQL5InnoDBDialect" )
.applySetting( Environment.USER, "root" )
.applySetting( Environment.PASS, "password" )
.applySetting( Environment.HBM2DDL_AUTO, "create-drop" );
// Create database schema in each run
applyCacheSettings( ssrb );
StandardServiceRegistry registry = ssrb.build();
Metadata metadata = buildMetadata( registry );
sessionFactory = metadata.buildSessionFactory();
tm = com.arjuna.ats.jta.TransactionManager.transactionManager();
}
protected String getProvider() {
return "infinispan";
}
protected void applyCacheSettings(StandardServiceRegistryBuilder ssrb) {
ssrb.applySetting( Environment.CACHE_REGION_FACTORY, TestRegionFactoryProvider.load().getRegionFactoryClass().getName() );
ssrb.applySetting( Environment.JTA_PLATFORM, new NarayanaStandaloneJtaPlatform() );
ssrb.applySetting( InfinispanProperties.INFINISPAN_CONFIG_RESOURCE_PROP, "stress-local-infinispan.xml" );
}
@After
public void afterClass() {
sessionFactory.close();
}
@Test
public void testEntityLifecycle() throws InterruptedException {
if (!PROFILE) {
System.out.printf("[provider=%s] Warming up\n", provider);
doEntityLifecycle(true);
// Recreate session factory cleaning everything
afterClass();
beforeClass();
}
System.out.printf("[provider=%s] Testing...\n", provider);
doEntityLifecycle(false);
}
void doEntityLifecycle(boolean isWarmup) {
long runningTimeout = isWarmup ? WARMUP_TIME : RUNNING_TIME;
TotalStats insertPerf = runEntityInsert(runningTimeout);
numEntities = countEntities().intValue();
printResult(isWarmup, "[provider=%s] Inserts/s %10.2f (%d entities)\n",
provider, insertPerf.getOpsPerSec("INSERT"), numEntities);
TotalStats updatePerf = runEntityUpdate(runningTimeout);
List<Integer> updateIdsSeq = new ArrayList<Integer>(updatedIds);
printResult(isWarmup, "[provider=%s] Updates/s %10.2f (%d updates)\n",
provider, updatePerf.getOpsPerSec("UPDATE"), updateIdsSeq.size());
TotalStats findUpdatedPerf =
runEntityFindUpdated(runningTimeout, updateIdsSeq);
printResult(isWarmup, "[provider=%s] Updated finds/s %10.2f\n",
provider, findUpdatedPerf.getOpsPerSec("FIND_UPDATED"));
TotalStats findQueryPerf = runEntityFindQuery(runningTimeout, isWarmup);
printResult(isWarmup, "[provider=%s] Query finds/s %10.2f\n",
provider, findQueryPerf.getOpsPerSec("FIND_QUERY"));
TotalStats findRandomPerf = runEntityFindRandom(runningTimeout);
printResult(isWarmup, "[provider=%s] Random finds/s %10.2f\n",
provider, findRandomPerf.getOpsPerSec("FIND_RANDOM"));
// Get all entity ids
List<Integer> entityIds = new ArrayList<Integer>();
for (int i = 1; i <= numEntities; i++) entityIds.add(i);
// Shuffle them
Collections.shuffle(entityIds);
// Add them to the queue delete consumption
removeIds.addAll(entityIds);
TotalStats deletePerf = runEntityDelete(runningTimeout);
printResult(isWarmup, "[provider=%s] Deletes/s %10.2f\n",
provider, deletePerf.getOpsPerSec("DELETE"));
// TODO Print 2LC statistics...
}
static void printResult(boolean isWarmup, String format, Object... args) {
if (!isWarmup) System.out.printf(format, args);
}
Long countEntities() {
try {
return withTx(tm, new Callable<Long>() {
@Override
public Long call() throws Exception {
Session s = sessionFactory.openSession();
Query query = s.createQuery("select count(*) from Family");
Object result = query.list().get(0);
s.close();
return (Long) result;
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
TotalStats runEntityInsert(long runningTimeout) {
return runSingleWork(runningTimeout, "insert", insertOperation());
}
TotalStats runEntityUpdate(long runningTimeout) {
return runSingleWork(runningTimeout, "update", updateOperation());
}
TotalStats runEntityFindUpdated(long runningTimeout,
List<Integer> updatedIdsSeq) {
return runSingleWork(runningTimeout, "find-updated", findUpdatedOperation(updatedIdsSeq));
}
TotalStats runEntityFindQuery(long runningTimeout, boolean warmup) {
return runSingleWork(runningTimeout, "find-query", findQueryOperation(warmup));
}
TotalStats runEntityFindRandom(long runningTimeout) {
return runSingleWork(runningTimeout, "find-random", findRandomOperation());
}
TotalStats runEntityDelete(long runningTimeout) {
return runSingleWork(runningTimeout, "remove", deleteOperation());
}
TotalStats runSingleWork(long runningTimeout, final String name, Operation op) {
final TotalStats perf = new TotalStats();
ExecutorService exec = Executors.newFixedThreadPool(
NUM_THREADS, new ThreadFactory() {
volatile int i = 0;
@Override
public Thread newThread(Runnable r) {
return new Thread(new ThreadGroup(name),
r, "worker-" + name + "-" + i++);
}
});
try {
List<Future<Void>> futures = new ArrayList<Future<Void>>(NUM_THREADS);
CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS + 1);
for (int i = 0; i < NUM_THREADS; i++)
futures.add(exec.submit(
new WorkerThread(runningTimeout, perf, op, barrier)));
try {
barrier.await(); // wait for all threads to be ready
barrier.await(); // wait for all threads to finish
// Now check whether anything went wrong...
for (Future<Void> future : futures) future.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
return perf;
} finally {
exec.shutdown();
}
}
<T> T captureThrowables(Callable<T> task) throws Exception {
try {
return task.call();
} catch (Throwable t) {
t.printStackTrace();
if (t instanceof Exception)
throw (Exception) t;
else
throw new RuntimeException(t);
}
}
Operation insertOperation() {
return new Operation("INSERT") {
@Override
boolean call(final int run) throws Exception {
return captureThrowables(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return withTx(tm, new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Session s = sessionFactory.openSession();
s.getTransaction().begin();
String name = "Zamarreño-" + run;
Family family = new Family(name);
s.persist(family);
s.getTransaction().commit();
s.close();
return true;
}
});
}
});
}
};
}
Operation updateOperation() {
return new Operation("UPDATE") {
@Override
boolean call(final int run) throws Exception {
return captureThrowables(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return withTx(tm, new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Session s = sessionFactory.openSession();
s.getTransaction().begin();
// Update random entity that has been inserted
int id = RANDOM.nextInt(numEntities) + 1;
Family family = (Family) s.load(Family.class, id);
String newSecondName = "Arrizabalaga-" + run;
family.setSecondName(newSecondName);
s.getTransaction().commit();
s.close();
// Cache updated entities for later read
updatedIds.add(id);
return true;
}
});
}
});
}
};
}
Operation findUpdatedOperation(final List<Integer> updatedIdsSeq) {
return new Operation("FIND_UPDATED") {
@Override
boolean call(final int run) throws Exception {
return captureThrowables(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Session s = sessionFactory.openSession();
int id = updatedIdsSeq.get(RANDOM.nextInt(
updatedIdsSeq.size()));
Family family = (Family) s.load(Family.class, id);
String secondName = family.getSecondName();
assertNotNull(secondName);
assertTrue("Second name not expected: " + secondName,
secondName.startsWith("Arrizabalaga"));
s.close();
return true;
}
});
}
};
}
private Operation findQueryOperation(final boolean isWarmup) {
return new Operation("FIND_QUERY") {
@Override
boolean call(final int run) throws Exception {
return captureThrowables(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Session s = sessionFactory.openSession();
Query query = s.createQuery("from Family")
.setCacheable(true);
int maxResults = isWarmup ? 10 : 100;
query.setMaxResults(maxResults);
List<Family> result = (List<Family>) query.list();
assertEquals(maxResults, result.size());
s.close();
return true;
}
});
}
};
}
private Operation findRandomOperation() {
return new Operation("FIND_RANDOM") {
@Override
boolean call(final int run) throws Exception {
return captureThrowables(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Session s = sessionFactory.openSession();
int id = RANDOM.nextInt(numEntities) + 1;
Family family = (Family) s.load(Family.class, id);
String familyName = family.getName();
// Skip ñ check in order to avoid issues...
assertTrue("Unexpected family: " + familyName ,
familyName.startsWith("Zamarre"));
s.close();
return true;
}
});
}
};
}
private Operation deleteOperation() {
return new Operation("DELETE") {
@Override
boolean call(final int run) throws Exception {
return captureThrowables(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return withTx(tm, new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Session s = sessionFactory.openSession();
s.getTransaction().begin();
// Get each id and remove it
int id = removeIds.poll();
Family family = (Family) s.load(Family.class, id);
String familyName = family.getName();
// Skip ñ check in order to avoid issues...
assertTrue("Unexpected family: " + familyName ,
familyName.startsWith("Zamarre"));
s.delete(family);
s.getTransaction().commit();
s.close();
return true;
}
});
}
});
}
};
}
public static Class[] getAnnotatedClasses() {
return new Class[] {Family.class, Person.class, Address.class};
}
private static Metadata buildMetadata(StandardServiceRegistry registry) {
final String cacheStrategy = "transactional";
MetadataSources metadataSources = new MetadataSources( registry );
for ( Class entityClass : getAnnotatedClasses() ) {
metadataSources.addAnnotatedClass( entityClass );
}
Metadata metadata = metadataSources.buildMetadata();
for ( PersistentClass entityBinding : metadata.getEntityBindings() ) {
if (!entityBinding.isInherited()) {
( (RootClass) entityBinding ).setCacheConcurrencyStrategy( cacheStrategy);
}
}
for ( Collection collectionBinding : metadata.getCollectionBindings() ) {
collectionBinding.setCacheConcurrencyStrategy( cacheStrategy );
}
return metadata;
}
private static abstract class Operation {
final String name;
Operation(String name) {
this.name = name;
}
abstract boolean call(int run) throws Exception;
}
private class WorkerThread implements Callable<Void> {
private final long runningTimeout;
private final TotalStats perf;
private final Operation op;
private final CyclicBarrier barrier;
public WorkerThread(long runningTimeout, TotalStats perf,
Operation op, CyclicBarrier barrier) {
this.runningTimeout = runningTimeout;
this.perf = perf;
this.op = op;
this.barrier = barrier;
}
@Override
public Void call() throws Exception {
// TODO: Extend barrier to capture start time
barrier.await();
try {
long startNanos = System.nanoTime();
long endNanos = startNanos + runningTimeout;
int runs = 0;
long missCount = 0;
while (callOperation(endNanos, runs)) {
boolean hit = op.call(runs);
if (!hit) missCount++;
runs++;
}
// TODO: Extend barrier to capture end time
perf.addStats(op.name, runs,
System.nanoTime() - startNanos, missCount);
} finally {
barrier.await();
}
return null;
}
private boolean callOperation(long endNanos, int runs) {
if (ALLOCATION) {
return runs < RUN_COUNT_LIMIT;
} else {
return (runs & 0x400) != 0 || System.nanoTime() < endNanos;
}
}
}
private static class TotalStats {
private ConcurrentHashMap<String, OpStats> statsMap =
new ConcurrentHashMap<String, OpStats>();
public void addStats(String opName, long opCount,
long runningTime, long missCount) {
OpStats s = new OpStats(opName, opCount, runningTime, missCount);
OpStats old = statsMap.putIfAbsent(opName, s);
boolean replaced = old == null;
while (!replaced) {
old = statsMap.get(opName);
s = new OpStats(old, opCount, runningTime, missCount);
replaced = statsMap.replace(opName, old, s);
}
}
public double getOpsPerSec(String opName) {
OpStats s = statsMap.get(opName);
if (s == null) return 0;
return s.opCount * 1000000000. / s.runningTime * s.threadCount;
}
public double getTotalOpsPerSec() {
long totalOpCount = 0;
long totalRunningTime = 0;
long totalThreadCount = 0;
for (Map.Entry<String, OpStats> e : statsMap.entrySet()) {
OpStats s = e.getValue();
totalOpCount += s.opCount;
totalRunningTime += s.runningTime;
totalThreadCount += s.threadCount;
}
return totalOpCount * 1000000000. / totalRunningTime * totalThreadCount;
}
public double getHitRatio(String opName) {
OpStats s = statsMap.get(opName);
if (s == null) return 0;
return 1 - 1. * s.missCount / s.opCount;
}
public double getTotalHitRatio() {
long totalOpCount = 0;
long totalMissCount = 0;
for (Map.Entry<String, OpStats> e : statsMap.entrySet()) {
OpStats s = e.getValue();
totalOpCount += s.opCount;
totalMissCount += s.missCount;
}
return 1 - 1. * totalMissCount / totalOpCount;
}
}
private static class OpStats {
public final String opName;
public final int threadCount;
public final long opCount;
public final long runningTime;
public final long missCount;
private OpStats(String opName, long opCount,
long runningTime, long missCount) {
this.opName = opName;
this.threadCount = 1;
this.opCount = opCount;
this.runningTime = runningTime;
this.missCount = missCount;
}
private OpStats(OpStats base, long opCount,
long runningTime, long missCount) {
this.opName = base.opName;
this.threadCount = base.threadCount + 1;
this.opCount = base.opCount + opCount;
this.runningTime = base.runningTime + runningTime;
this.missCount = base.missCount + missCount;
}
}
}
| 21,848
| 34.469156
| 128
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/stress/entities/Family.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.stress.entities;
import java.util.HashSet;
import java.util.Set;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Version;
@Entity
public final class Family {
@Id
@GeneratedValue
private int id;
private String name;
private String secondName;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "family", orphanRemoval = true)
private Set<Person> members;
@Version
private int version;
public Family(String name) {
this.name = name;
this.secondName = null;
this.members = new HashSet<Person>();
this.id = 0;
this.version = 0;
}
protected Family() {
this.name = null;
this.secondName = null;
this.members = new HashSet<Person>();
this.id = 0;
this.version = 0;
}
public String getName() {
return name;
}
public Set<Person> getMembers() {
return members;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getVersion() {
return version;
}
public void setName(String name) {
this.name = name;
}
public void setMembers(Set<Person> members) {
if (members == null) {
this.members = new HashSet<Person>();
} else {
this.members = members;
}
}
public void setVersion(Integer version) {
this.version = version;
}
boolean addMember(Person member) {
return members.add(member);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Family family = (Family) o;
// members must not be in the comparison since we would end up in infinite recursive call
if (id != family.id) return false;
if (version != family.version) return false;
if (name != null ? !name.equals(family.name) : family.name != null)
return false;
if (secondName != null ? !secondName.equals(family.secondName) : family.secondName != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (secondName != null ? secondName.hashCode() : 0);
result = 31 * result + id;
result = 31 * result + version;
return result;
}
@Override
public String toString() {
return "Family{" +
"id=" + id +
", name='" + name + '\'' +
", secondName='" + secondName + '\'' +
", members=" + members +
", version=" + version +
'}';
}
}
| 3,243
| 22.852941
| 97
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/stress/entities/Person.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.stress.entities;
import java.util.Date;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Version;
@Entity
public class Person {
@Id
@GeneratedValue
private int id;
private String firstName;
@ManyToOne
private Family family;
private Date birthDate;
@ManyToOne
private Address address;
private boolean checked;
@Version
private int version;
public Person(String firstName, Family family) {
this.firstName = firstName;
this.family = family;
this.birthDate = null;
this.address = null;
this.checked = false;
this.id = 0;
this.version = 0;
this.family.addMember(this);
}
protected Person() {
this.firstName = null;
this.family = null;
this.birthDate = null;
this.address = null;
this.checked = false;
this.id = 0;
this.version = 0;
}
public String getFirstName() {
return firstName;
}
public Family getFamily() {
return family;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
// To skip Hibernate BUG with access.PROPERTY : the rest should be done in DAO
// this.address = address;
// Hibernate BUG : if we update the relation on 2 sides
if (this.address != address) {
if (this.address != null) this.address.remInhabitant(this);
this.address = address;
if (this.address != null) this.address.addInhabitant(this);
}
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getVersion() {
return version;
}
protected void setFirstName(String firstName) {
this.firstName = firstName;
}
protected void setFamily(Family family) {
this.family = family;
}
protected void setVersion(Integer version) {
this.version = version;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (checked != person.checked) return false;
if (id != person.id) return false;
if (version != person.version) return false;
if (address != null ? !address.equals(person.address) : person.address != null)
return false;
if (birthDate != null ? !birthDate.equals(person.birthDate) : person.birthDate != null)
return false;
if (family != null ? !family.equals(person.family) : person.family != null)
return false;
if (firstName != null ? !firstName.equals(person.firstName) : person.firstName != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = firstName != null ? firstName.hashCode() : 0;
result = 31 * result + (family != null ? family.hashCode() : 0);
result = 31 * result + (birthDate != null ? birthDate.hashCode() : 0);
result = 31 * result + (address != null ? address.hashCode() : 0);
result = 31 * result + (checked ? 1 : 0);
result = 31 * result + id;
result = 31 * result + version;
return result;
}
@Override
public String toString() {
return "Person{" +
"address=" + address +
", firstName='" + firstName + '\'' +
", family=" + family +
", birthDate=" + birthDate +
", checked=" + checked +
", id=" + id +
", version=" + version +
'}';
}
}
| 4,252
| 24.620482
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/stress/entities/Address.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.stress.entities;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Version;
@Entity
public final class Address {
@Id
@GeneratedValue
private int id;
private int streetNumber;
private String streetName;
private String cityName;
private String countryName;
private String zipCode;
@OneToMany
private Set<Person> inhabitants;
@Version
private int version;
public Address(int streetNumber, String streetName, String cityName, String countryName) {
this.streetNumber = streetNumber;
this.streetName = streetName;
this.cityName = cityName;
this.countryName = countryName;
this.zipCode = null;
this.inhabitants = new HashSet<Person>();
this.id = 0;
this.version = 0;
}
protected Address() {
this.streetNumber = 0;
this.streetName = null;
this.cityName = null;
this.countryName = null;
this.zipCode = null;
this.inhabitants = new HashSet<Person>();
this.id = 0;
this.version = 0;
}
public int getStreetNumber() {
return streetNumber;
}
public String getStreetName() {
return streetName;
}
public String getCityName() {
return cityName;
}
public String getCountryName() {
return countryName;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public Set<Person> getInhabitants() {
return inhabitants;
}
public boolean addInhabitant(Person inhabitant) {
boolean done = false;
if (inhabitants.add(inhabitant)) {
inhabitant.setAddress(this);
done = true;
}
return done;
}
public boolean remInhabitant(Person inhabitant) {
boolean done = false;
if (inhabitants.remove(inhabitant)) {
inhabitant.setAddress(null);
done = true;
}
return done;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getVersion() {
return version;
}
protected void removeAllInhabitants() {
// inhabitants relation is not CASCADED, we must delete the relation on other side by ourselves
for (Iterator<Person> iterator = inhabitants.iterator(); iterator.hasNext(); ) {
Person p = iterator.next();
p.setAddress(null);
}
}
protected void setStreetNumber(int streetNumber) {
this.streetNumber = streetNumber;
}
protected void setStreetName(String streetName) {
this.streetName = streetName;
}
protected void setCityName(String cityName) {
this.cityName = cityName;
}
protected void setCountryName(String countryName) {
this.countryName = countryName;
}
protected void setInhabitants(Set<Person> inhabitants) {
if (inhabitants == null) {
this.inhabitants = new HashSet<Person>();
} else {
this.inhabitants = inhabitants;
}
}
protected void setVersion(Integer version) {
this.version = version;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Address address = (Address) o;
// inhabitants must not be in the comparison since we would end up in infinite recursion
if (id != address.id) return false;
if (streetNumber != address.streetNumber) return false;
if (version != address.version) return false;
if (cityName != null ? !cityName.equals(address.cityName) : address.cityName != null)
return false;
if (countryName != null ? !countryName.equals(address.countryName) : address.countryName != null)
return false;
if (streetName != null ? !streetName.equals(address.streetName) : address.streetName != null)
return false;
if (zipCode != null ? !zipCode.equals(address.zipCode) : address.zipCode != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = streetNumber;
result = 31 * result + (streetName != null ? streetName.hashCode() : 0);
result = 31 * result + (cityName != null ? cityName.hashCode() : 0);
result = 31 * result + (countryName != null ? countryName.hashCode() : 0);
result = 31 * result + (zipCode != null ? zipCode.hashCode() : 0);
result = 31 * result + id;
result = 31 * result + version;
return result;
}
@Override
public String toString() {
return "Address{" +
"cityName='" + cityName + '\'' +
", streetNumber=" + streetNumber +
", streetName='" + streetName + '\'' +
", countryName='" + countryName + '\'' +
", zipCode='" + zipCode + '\'' +
", inhabitants=" + inhabitants +
", id=" + id +
", version=" + version +
'}';
}
}
| 5,439
| 25.930693
| 103
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/entity/EntityRegionExtraAPITest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.entity;
import org.hibernate.cache.spi.access.AccessType;
import org.infinispan.test.hibernate.cache.commons.AbstractExtraAPITest;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Tests for the "extra API" in EntityRegionAccessStrategy;.
* <p>
* By "extra API" we mean those methods that are superfluous to the
* function of the JBC integration, where the impl is a no-op or a static
* false return value, UnsupportedOperationException, etc.
*
* @author Galder Zamarreño
* @since 3.5
*/
public class EntityRegionExtraAPITest extends AbstractExtraAPITest<Object> {
public static final String VALUE1 = "VALUE1";
public static final String VALUE2 = "VALUE2";
@Override
protected Object getAccessStrategy() {
return TEST_SESSION_ACCESS.entityAccess(environment.getEntityRegion( REGION_NAME, accessType), accessType);
}
@Test
@SuppressWarnings( {"UnnecessaryBoxing"})
public void testAfterInsert() {
boolean retval = testAccessStrategy.afterInsert(SESSION, KEY, VALUE1, Integer.valueOf( 1 ));
assertEquals(accessType == AccessType.NONSTRICT_READ_WRITE, retval);
}
@Test
@SuppressWarnings( {"UnnecessaryBoxing"})
public void testAfterUpdate() {
if (accessType == AccessType.READ_ONLY) {
return;
}
boolean retval = testAccessStrategy.afterUpdate(SESSION, KEY, VALUE2, Integer.valueOf( 1 ), Integer.valueOf( 2 ), new MockSoftLock());
assertEquals(accessType == AccessType.NONSTRICT_READ_WRITE, retval);
}
}
| 1,758
| 33.490196
| 136
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/entity/EntityRegionAccessStrategyTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.entity;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cache.spi.access.SoftLock;
import org.infinispan.commons.test.categories.Smoke;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.test.hibernate.cache.commons.AbstractRegionAccessStrategyTest;
import org.infinispan.test.hibernate.cache.commons.NodeEnvironment;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess.TestRegionAccessStrategy;
import org.infinispan.test.hibernate.cache.commons.util.TestSynchronization;
import org.infinispan.test.hibernate.cache.commons.util.TestingKeyFactory;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* Base class for tests of EntityRegionAccessStrategy impls.
*
* @author Galder Zamarreño
* @since 3.5
*/
@Category(Smoke.class)
public class EntityRegionAccessStrategyTest extends
AbstractRegionAccessStrategyTest<Object> {
protected static int testCount;
@Override
protected Object generateNextKey() {
return TestingKeyFactory.generateEntityCacheKey( KEY_BASE + testCount++ );
}
@Override
protected InfinispanBaseRegion getRegion(NodeEnvironment environment) {
return environment.getEntityRegion(REGION_NAME, accessType);
}
@Override
protected Object getAccessStrategy(InfinispanBaseRegion region) {
return TEST_SESSION_ACCESS.entityAccess(region, accessType);
}
@Test
public void testPutFromLoad() throws Exception {
if (accessType == AccessType.READ_ONLY) {
putFromLoadTestReadOnly(false);
} else {
putFromLoadTest(false, false);
}
}
@Test
public void testPutFromLoadMinimal() throws Exception {
if (accessType == AccessType.READ_ONLY) {
putFromLoadTestReadOnly(true);
} else {
putFromLoadTest(true, false);
}
}
@Test
public void testInsert() throws Exception {
final Object KEY = generateNextKey();
final CountDownLatch readLatch = new CountDownLatch(1);
final CountDownLatch commitLatch = new CountDownLatch(1);
final CountDownLatch completionLatch = new CountDownLatch(2);
CountDownLatch asyncInsertLatch = expectAfterUpdate(KEY);
Thread inserter = new Thread(() -> {
try {
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
withTx(localEnvironment, session, () -> {
assertNull("Correct initial value", testLocalAccessStrategy.get(session, KEY));
doInsert(testLocalAccessStrategy, session, KEY, VALUE1);
readLatch.countDown();
commitLatch.await();
return null;
});
} catch (Exception e) {
log.error("node1 caught exception", e);
node1Exception = e;
} catch (AssertionError e) {
node1Failure = e;
} finally {
completionLatch.countDown();
}
}, "testInsert-inserter");
Thread reader = new Thread(() -> {
try {
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
withTx(localEnvironment, session, () -> {
readLatch.await();
assertNull("Correct initial value", testLocalAccessStrategy.get(session, KEY));
return null;
});
} catch (Exception e) {
log.error("node1 caught exception", e);
node1Exception = e;
} catch (AssertionError e) {
node1Failure = e;
} finally {
commitLatch.countDown();
completionLatch.countDown();
}
}, "testInsert-reader");
inserter.setDaemon(true);
reader.setDaemon(true);
inserter.start();
reader.start();
assertTrue("Threads completed", completionLatch.await(10, TimeUnit.SECONDS));
assertThreadsRanCleanly();
Object s1 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
assertEquals("Correct node1 value", VALUE1, testLocalAccessStrategy.get(s1, KEY));
assertTrue(asyncInsertLatch.await(10, TimeUnit.SECONDS));
Object expected = isUsingInvalidation() ? null : VALUE1;
Object s2 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
assertEquals("Correct node2 value", expected, testRemoteAccessStrategy.get(s2, KEY));
}
protected void doInsert(TestRegionAccessStrategy strategy, Object session, Object key, TestCacheEntry entry) {
strategy.insert(session, key, entry, entry.getVersion());
SESSION_ACCESS.getTransactionCoordinator(session).registerLocalSynchronization(
new TestSynchronization.AfterInsert(strategy, session, key, entry, entry.getVersion()));
}
protected void putFromLoadTestReadOnly(boolean minimal) throws Exception {
final Object KEY = TestingKeyFactory.generateEntityCacheKey( KEY_BASE + testCount++ );
CountDownLatch remotePutFromLoadLatch = expectPutFromLoad(KEY);
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
withTx(localEnvironment, session, () -> {
assertNull(testLocalAccessStrategy.get(session, KEY));
if (minimal)
testLocalAccessStrategy.putFromLoad(session, KEY, VALUE1, SESSION_ACCESS.getTimestamp(session), VALUE1.getVersion(), true);
else
testLocalAccessStrategy.putFromLoad(session, KEY, VALUE1, SESSION_ACCESS.getTimestamp(session), VALUE1.getVersion());
return null;
});
Object s2 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
assertEquals(VALUE1, testLocalAccessStrategy.get(s2, KEY));
Object s3 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
Object expected;
if (isUsingInvalidation()) {
expected = null;
} else {
if (accessType != AccessType.NONSTRICT_READ_WRITE) {
assertTrue(remotePutFromLoadLatch.await(2, TimeUnit.SECONDS));
}
expected = VALUE1;
}
assertEquals(expected, testRemoteAccessStrategy.get(s3, KEY));
}
@Test
public void testUpdate() throws Exception {
log.infof(name.getMethodName());
if (accessType == AccessType.READ_ONLY) {
return;
}
final Object KEY = generateNextKey();
// Set up initial state
Object s1 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
testLocalAccessStrategy.putFromLoad(s1, KEY, VALUE1, SESSION_ACCESS.getTimestamp(s1), VALUE1.getVersion());
Object s2 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
testRemoteAccessStrategy.putFromLoad(s2, KEY, VALUE1, SESSION_ACCESS.getTimestamp(s2), VALUE1.getVersion());
// both nodes are updated, we don't have to wait for any async replication of putFromLoad
CountDownLatch asyncUpdateLatch = expectAfterUpdate(KEY);
final CountDownLatch readLatch = new CountDownLatch(1);
final CountDownLatch commitLatch = new CountDownLatch(1);
final CountDownLatch completionLatch = new CountDownLatch(2);
Thread updater = new Thread(() -> {
try {
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
withTx(localEnvironment, session, () -> {
log.debug("Transaction began, get initial value");
assertEquals("Correct initial value", VALUE1, testLocalAccessStrategy.get(session, KEY));
log.debug("Now update value");
doUpdate(testLocalAccessStrategy, session, KEY, VALUE2);
log.debug("Notify the read latch");
readLatch.countDown();
log.debug("Await commit");
commitLatch.await();
return null;
});
} catch (Exception e) {
log.error("node1 caught exception", e);
node1Exception = e;
} catch (AssertionError e) {
node1Failure = e;
} finally {
if (readLatch.getCount() > 0) {
readLatch.countDown();
}
log.debug("Completion latch countdown");
completionLatch.countDown();
}
}, "testUpdate-updater");
Thread reader = new Thread(() -> {
try {
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
withTx(localEnvironment, session, () -> {
log.debug("Transaction began, await read latch");
readLatch.await();
log.debug("Read latch acquired, verify local access strategy");
// This won't block w/ mvc and will read the old value (if transactional as the transaction
// is not being committed yet, or if non-strict as we do the actual update only after transaction)
// or null if non-transactional
Object expected = isTransactional() || accessType == AccessType.NONSTRICT_READ_WRITE ? VALUE1 : null;
assertEquals("Correct value", expected, testLocalAccessStrategy.get(session, KEY));
return null;
});
} catch (Exception e) {
log.error("node1 caught exception", e);
node1Exception = e;
} catch (AssertionError e) {
node1Failure = e;
} finally {
commitLatch.countDown();
log.debug("Completion latch countdown");
completionLatch.countDown();
}
}, "testUpdate-reader");
updater.setDaemon(true);
reader.setDaemon(true);
updater.start();
reader.start();
assertTrue(completionLatch.await(2, TimeUnit.SECONDS));
assertThreadsRanCleanly();
Object s3 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
assertEquals("Correct node1 value", VALUE2, testLocalAccessStrategy.get(s3, KEY));
assertTrue(asyncUpdateLatch.await(10, TimeUnit.SECONDS));
Object expected = isUsingInvalidation() ? null : VALUE2;
Object s4 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, remoteEnvironment.getRegionFactory());
assertEquals("Correct node2 value", expected, testRemoteAccessStrategy.get(s4, KEY));
}
@Override
protected void doUpdate(TestRegionAccessStrategy strategy, Object session, Object key, TestCacheEntry entry) {
SoftLock softLock = strategy.lockItem(session, key, null);
strategy.update(session, key, entry, null, entry.getVersion());
SESSION_ACCESS.getTransactionCoordinator(session).registerLocalSynchronization(
new TestSynchronization.AfterUpdate(strategy, session, key, entry, entry.getVersion(), softLock));
}
/**
* This test fails in CI too often because it depends on very short timeout. The behaviour is basically
* non-testable as we want to make sure that the "Putter" is always progressing; however, it is sometimes
* progressing in different thread (on different node), and sometimes even in system, sending a message
* over network. Therefore even checking that some OOB/remote thread is in RUNNABLE/RUNNING state is prone
* to spurious failure (and we can't grab the state of all threads atomically).
*/
@Ignore
@Test
public void testContestedPutFromLoad() throws Exception {
if (accessType == AccessType.READ_ONLY) {
return;
}
final Object KEY = TestingKeyFactory.generateEntityCacheKey(KEY_BASE + testCount++);
Object s1 = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
testLocalAccessStrategy.putFromLoad(s1, KEY, VALUE1, SESSION_ACCESS.getTimestamp(s1), VALUE1.getVersion());
final CountDownLatch pferLatch = new CountDownLatch(1);
final CountDownLatch pferCompletionLatch = new CountDownLatch(1);
final CountDownLatch commitLatch = new CountDownLatch(1);
final CountDownLatch completionLatch = new CountDownLatch(1);
Thread blocker = new Thread("Blocker") {
@Override
public void run() {
try {
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
withTx(localEnvironment, session, () -> {
assertEquals("Correct initial value", VALUE1, testLocalAccessStrategy.get(session, KEY));
doUpdate(testLocalAccessStrategy, session, KEY, VALUE2);
pferLatch.countDown();
commitLatch.await();
return null;
});
} catch (Exception e) {
log.error("node1 caught exception", e);
node1Exception = e;
} catch (AssertionError e) {
node1Failure = e;
} finally {
completionLatch.countDown();
}
}
};
Thread putter = new Thread("Putter") {
@Override
public void run() {
try {
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
withTx(localEnvironment, session, () -> {
testLocalAccessStrategy.putFromLoad(session, KEY, VALUE1, SESSION_ACCESS.getTimestamp(session), VALUE1.getVersion());
return null;
});
} catch (Exception e) {
log.error("node1 caught exception", e);
node1Exception = e;
} catch (AssertionError e) {
node1Failure = e;
} finally {
pferCompletionLatch.countDown();
}
}
};
blocker.start();
assertTrue("Active tx has done an update", pferLatch.await(1, TimeUnit.SECONDS));
putter.start();
assertTrue("putFromLoad returns promptly", pferCompletionLatch.await(10, TimeUnit.MILLISECONDS));
commitLatch.countDown();
assertTrue("Threads completed", completionLatch.await(1, TimeUnit.SECONDS));
assertThreadsRanCleanly();
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
assertEquals("Correct node1 value", VALUE2, testLocalAccessStrategy.get(session, KEY));
}
@Test
@Ignore("ISPN-9175")
@Override
public void testRemoveAll() throws Exception {
super.testRemoveAll();
}
}
| 13,972
| 36.360963
| 135
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/entity/EntityRegionImplTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.entity;
import java.util.Properties;
import org.hibernate.cache.spi.access.AccessType;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.test.hibernate.cache.commons.AbstractEntityCollectionRegionTest;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import static org.junit.Assert.assertNotNull;
/**
* Tests of EntityRegionImpl.
*
* @author Galder Zamarreño
* @since 3.5
*/
public class EntityRegionImplTest extends AbstractEntityCollectionRegionTest {
protected static final String CACHE_NAME = "test";
@Override
protected void supportedAccessTypeTest(TestRegionFactory regionFactory, Properties properties) {
InfinispanBaseRegion region = regionFactory.buildEntityRegion("test", accessType);
assertNotNull(TEST_SESSION_ACCESS.entityAccess(region, accessType));
regionFactory.getCacheManager().administration().removeCache(CACHE_NAME);
}
private TestSessionAccess.TestRegionAccessStrategy entityAccess(InfinispanBaseRegion region) {
Object access = TEST_SESSION_ACCESS.entityAccess(region, AccessType.TRANSACTIONAL);
return TEST_SESSION_ACCESS.fromAccess(access);
}
@Override
protected InfinispanBaseRegion createRegion(TestRegionFactory regionFactory, String regionName) {
return regionFactory.buildEntityRegion(regionName, accessType);
}
}
| 1,708
| 36.152174
| 98
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/collection/CollectionRegionAccessExtraAPITest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.collection;
import org.infinispan.test.hibernate.cache.commons.AbstractExtraAPITest;
/**
* @author Galder Zamarreño
* @since 3.5
*/
public class CollectionRegionAccessExtraAPITest extends AbstractExtraAPITest<Object> {
@Override
protected Object getAccessStrategy() {
return TEST_SESSION_ACCESS.collectionAccess(environment.getCollectionRegion( REGION_NAME, accessType), accessType);
}
}
| 687
| 31.761905
| 117
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/collection/CollectionRegionImplTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.collection;
import java.util.Properties;
import org.hibernate.cache.spi.access.AccessType;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.test.hibernate.cache.commons.AbstractEntityCollectionRegionTest;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess.TestRegionAccessStrategy;
import static org.junit.Assert.assertNotNull;
/**
* @author Galder Zamarreño
*/
public class CollectionRegionImplTest extends AbstractEntityCollectionRegionTest {
protected static final String CACHE_NAME = "test";
@Override
protected void supportedAccessTypeTest(TestRegionFactory regionFactory, Properties properties) {
InfinispanBaseRegion region = regionFactory.buildCollectionRegion(CACHE_NAME, accessType);
assertNotNull(TEST_SESSION_ACCESS.collectionAccess(region, accessType));
regionFactory.getCacheManager().administration().removeCache(CACHE_NAME);
}
@Override
protected InfinispanBaseRegion createRegion(TestRegionFactory regionFactory, String regionName) {
return regionFactory.buildCollectionRegion(regionName, accessType);
}
private TestRegionAccessStrategy collectionAccess(InfinispanBaseRegion region) {
Object access = TEST_SESSION_ACCESS.collectionAccess(region, AccessType.TRANSACTIONAL);
return TEST_SESSION_ACCESS.fromAccess(access);
}
}
| 1,700
| 38.55814
| 99
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/collection/CollectionRegionAccessStrategyTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.collection;
import static org.junit.Assert.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.hibernate.cache.spi.access.SoftLock;
import org.infinispan.commons.test.categories.Smoke;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.hibernate.cache.commons.InfinispanDataRegion;
import org.infinispan.hibernate.cache.commons.access.AccessDelegate;
import org.infinispan.hibernate.cache.commons.access.NonTxInvalidationCacheAccessDelegate;
import org.infinispan.hibernate.cache.commons.access.PutFromLoadValidator;
import org.infinispan.hibernate.cache.commons.access.TxInvalidationCacheAccessDelegate;
import org.infinispan.test.hibernate.cache.commons.AbstractRegionAccessStrategyTest;
import org.infinispan.test.hibernate.cache.commons.NodeEnvironment;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess.TestRegionAccessStrategy;
import org.infinispan.test.hibernate.cache.commons.util.TestSynchronization;
import org.infinispan.test.hibernate.cache.commons.util.TestingKeyFactory;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* Base class for tests of CollectionRegionAccessStrategy impls.
*
* @author Galder Zamarreño
* @since 3.5
*/
@Category(Smoke.class)
public class CollectionRegionAccessStrategyTest extends AbstractRegionAccessStrategyTest<Object> {
protected static int testCount;
@Override
protected Object generateNextKey() {
return TestingKeyFactory.generateCollectionCacheKey(KEY_BASE + testCount++);
}
@Override
protected InfinispanBaseRegion getRegion(NodeEnvironment environment) {
return environment.getCollectionRegion(REGION_NAME, accessType);
}
@Override
protected Object getAccessStrategy(InfinispanBaseRegion region) {
return TEST_SESSION_ACCESS.collectionAccess(region, accessType);
}
@Test
public void testPutFromLoadRemoveDoesNotProduceStaleData() throws Exception {
if (!cacheMode.isInvalidation()) {
return;
}
final CountDownLatch pferLatch = new CountDownLatch( 1 );
final CountDownLatch removeLatch = new CountDownLatch( 1 );
// remove the interceptor inserted by default PutFromLoadValidator, we're using different one
PutFromLoadValidator originalValidator = PutFromLoadValidator.removeFromCache(localRegion.getCache());
PutFromLoadValidator mockValidator = spy(originalValidator);
doAnswer(invocation -> {
try {
return invocation.callRealMethod();
} finally {
try {
removeLatch.countDown();
// the remove should be blocked because the putFromLoad has been acquired
// and the remove can continue only after we've inserted the entry
assertFalse(pferLatch.await( 2, TimeUnit.SECONDS ) );
}
catch (InterruptedException e) {
log.debug( "Interrupted" );
Thread.currentThread().interrupt();
}
catch (Exception e) {
log.error( "Error", e );
throw new RuntimeException( "Error", e );
}
}
}).when(mockValidator).acquirePutFromLoadLock(any(), any(), anyLong());
PutFromLoadValidator.addToCache(localRegion.getCache(), mockValidator);
cleanup.add(() -> {
PutFromLoadValidator.removeFromCache(localRegion.getCache());
PutFromLoadValidator.addToCache(localRegion.getCache(), originalValidator);
});
final AccessDelegate delegate = localRegion.getCache().getCacheConfiguration().transaction().transactionMode().isTransactional() ?
new TxInvalidationCacheAccessDelegate((InfinispanDataRegion) localRegion, mockValidator) :
new NonTxInvalidationCacheAccessDelegate((InfinispanDataRegion) localRegion, mockValidator);
ExecutorService executorService = Executors.newCachedThreadPool();
cleanup.add(() -> executorService.shutdownNow());
final String KEY = "k1";
Future<Void> pferFuture = executorService.submit(() -> {
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
delegate.putFromLoad(session, KEY, "v1", SESSION_ACCESS.getTimestamp(session), null);
return null;
});
Future<Void> removeFuture = executorService.submit(() -> {
removeLatch.await();
Object session = TEST_SESSION_ACCESS.mockSession(jtaPlatform, TIME_SERVICE, localEnvironment.getRegionFactory());
withTx(localEnvironment, session, () -> {
delegate.remove(session, KEY);
return null;
});
pferLatch.countDown();
return null;
});
pferFuture.get();
removeFuture.get();
assertFalse(localRegion.getCache().containsKey(KEY));
assertFalse(remoteRegion.getCache().containsKey(KEY));
}
@Test
public void testPutFromLoad() throws Exception {
putFromLoadTest(false, true);
}
@Test
public void testPutFromLoadMinimal() throws Exception {
putFromLoadTest(true, true);
}
@Override
protected void doUpdate(TestRegionAccessStrategy strategy, Object session, Object key, TestCacheEntry entry) {
SoftLock softLock = strategy.lockItem(session, key, null);
strategy.remove(session, key);
SESSION_ACCESS.getTransactionCoordinator(session).registerLocalSynchronization(
new TestSynchronization.UnlockItem(strategy, session, key, softLock));
}
}
| 5,768
| 37.97973
| 132
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/TestingKeyFactory.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.util;
import java.io.Serializable;
public class TestingKeyFactory {
private TestingKeyFactory() {
//Not to be constructed
}
public static Object generateEntityCacheKey(String id) {
return new TestingEntityCacheKey( id );
}
public static Object generateCollectionCacheKey(String id) {
return new TestingEntityCacheKey( id );
}
//For convenience implement both interfaces.
private static class TestingEntityCacheKey implements Serializable {
private final String id;
public TestingEntityCacheKey(String id) {
this.id = id;
}
@Override
public String toString() {
return id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestingEntityCacheKey other = (TestingEntityCacheKey) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
}
| 1,463
| 20.850746
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/BatchModeJtaPlatform.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.util;
import org.hibernate.HibernateException;
import org.hibernate.TransactionException;
import org.hibernate.engine.transaction.internal.jta.JtaStatusHelper;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.infinispan.transaction.tm.BatchModeTransactionManager;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.UserTransaction;
/**
* @author Steve Ebersole
*/
public class BatchModeJtaPlatform implements JtaPlatform {
@Override
public TransactionManager retrieveTransactionManager() {
try {
return BatchModeTransactionManager.getInstance();
}
catch (Exception e) {
throw new HibernateException("Failed getting BatchModeTransactionManager", e);
}
}
@Override
public UserTransaction retrieveUserTransaction() {
throw new UnsupportedOperationException();
}
@Override
public Object getTransactionIdentifier(Transaction transaction) {
return transaction;
}
@Override
public boolean canRegisterSynchronization() {
return JtaStatusHelper.isActive( retrieveTransactionManager() );
}
@Override
public void registerSynchronization(Synchronization synchronization) {
try {
retrieveTransactionManager().getTransaction().registerSynchronization( synchronization );
}
catch (Exception e) {
throw new TransactionException( "Could not obtain transaction from TM" );
}
}
@Override
public int getCurrentStatus() throws SystemException {
return JtaStatusHelper.getStatus( retrieveTransactionManager() );
}
}
| 1,978
| 29.446154
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/TestSessionAccess.java
|
package org.infinispan.test.hibernate.cache.commons.util;
import java.util.Collection;
import java.util.List;
import java.util.ServiceLoader;
import org.hibernate.Transaction;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.util.ControlledTimeService;
public interface TestSessionAccess {
Object mockSessionImplementor();
Object mockSession(Class<? extends JtaPlatform> jtaPlatform, ControlledTimeService timeService, RegionFactory regionFactory);
Transaction beginTransaction(Object session);
TestRegionAccessStrategy fromAccess(Object access);
TestRegion fromRegion(InfinispanBaseRegion region);
List execQueryList(Object session, String query, String[]... params);
List execQueryListAutoFlush(Object session, String query, String[]... params);
List execQueryListCacheable(Object session, String query);
int execQueryUpdateAutoFlush(Object session, String query, String[]... params);
void execQueryUpdate(Object session, String query);
static TestSessionAccess findTestSessionAccess() {
ServiceLoader<TestSessionAccess> loader = ServiceLoader.load(TestSessionAccess.class);
return loader.iterator().next();
}
Object collectionAccess(InfinispanBaseRegion region, AccessType accessType);
Object entityAccess(InfinispanBaseRegion region, AccessType accessType);
InfinispanBaseRegion getRegion(SessionFactoryImplementor sessionFactory, String regionName);
Collection<InfinispanBaseRegion> getAllRegions(SessionFactoryImplementor sessionFactory);
interface TestRegionAccessStrategy {
SoftLock lockItem(Object session, Object key, Object version) throws CacheException;
void unlockItem(Object session, Object key, SoftLock lock) throws CacheException;
boolean afterInsert(Object session, Object key, Object value, Object version) throws CacheException;
boolean afterUpdate(Object session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException;
Object get(Object session, Object key) throws CacheException;
boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException;
boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version) throws CacheException;
void remove(Object session, Object key) throws CacheException;
boolean insert(Object session, Object key, Object value, Object version) throws CacheException;
boolean update(Object session, Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException;
SoftLock lockRegion();
void unlockRegion(SoftLock softLock);
void evict(Object key);
void evictAll();
void removeAll(Object session);
}
interface TestRegion {
Object get(Object session, Object key) throws CacheException;
void put(Object session, Object key, Object value) throws CacheException;
void evict(Object key);
void evictAll();
}
}
| 3,434
| 34.412371
| 152
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/JdbcResourceTransactionMock.java
|
package org.infinispan.test.hibernate.cache.commons.util;
import org.hibernate.resource.transaction.backend.jdbc.spi.JdbcResourceTransaction;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import static org.junit.Assert.assertEquals;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public class JdbcResourceTransactionMock implements JdbcResourceTransaction {
private TransactionStatus status = TransactionStatus.NOT_ACTIVE;
@Override
public void begin() {
assertEquals(TransactionStatus.NOT_ACTIVE, status);
status = TransactionStatus.ACTIVE;
}
@Override
public void commit() {
assertEquals(TransactionStatus.ACTIVE, status);
status = TransactionStatus.COMMITTED;
}
@Override
public void rollback() {
status = TransactionStatus.ROLLED_BACK;
}
@Override
public TransactionStatus getStatus() {
return status;
}
}
| 871
| 23.222222
| 83
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/InfinispanTestingSetup.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.util;
import org.infinispan.commons.test.ThreadLeakChecker;
import org.infinispan.commons.test.TestResourceTracker;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* TestRule that sets the test name so that Infinispan test utilities can track the shutdown of cache managers and thread leaks.
*
* <p>Use as a {@link ClassRule} or {@link Rule}.</p>
*
* <p>Note: {@code BaseUnitTestCase} uses a {@code Timeout} rule that runs each method in a separate thread,
* so tests extending {@code BaseUnitTestCase} must use {@link Rule} or invoke {@link #joinContext()}
* in the test methods.</p>
*
* @author Sanne Grinovero
*/
public final class InfinispanTestingSetup implements TestRule {
private volatile String runningTest;
public InfinispanTestingSetup() {
}
public Statement apply(Statement base, Description d) {
final String methodName = d.getMethodName();
final String testName = methodName == null ? d.getClassName() : d.getClassName() + "#" + d.getMethodName();
runningTest = testName;
return new Statement() {
@Override
public void evaluate() throws Throwable {
TestResourceTracker.testStarted( testName );
ThreadLeakChecker.testStarted( testName );
try {
base.evaluate();
} finally {
TestResourceTracker.testFinished( testName );
ThreadLeakChecker.testFinished( testName );
}
}
};
}
/**
* Make a new thread join the test context.
*/
public void joinContext() {
TestResourceTracker.setThreadTestName( runningTest );
}
}
| 2,108
| 33.016129
| 128
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/CacheTestUtil.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.util;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl;
import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl;
import org.hibernate.service.ServiceRegistry;
/**
* Utilities for cache testing.
*
* @author <a href="brian.stansberry@jboss.com">Brian Stansberry</a>
*/
public class CacheTestUtil {
@SuppressWarnings("unchecked")
public static Map buildBaselineSettings(
String regionPrefix,
boolean use2ndLevel,
boolean useQueries,
Class<? extends JtaPlatform> jtaPlatform) {
Map settings = new HashMap();
settings.put( AvailableSettings.GENERATE_STATISTICS, "true" );
settings.put( AvailableSettings.USE_STRUCTURED_CACHE, "true" );
if (jtaPlatform == null || jtaPlatform == NoJtaPlatform.class) {
settings.put(Environment.TRANSACTION_COORDINATOR_STRATEGY, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class.getName());
settings.put(AvailableSettings.JTA_PLATFORM, NoJtaPlatform.class);
} else {
settings.put(Environment.TRANSACTION_COORDINATOR_STRATEGY, JtaTransactionCoordinatorBuilderImpl.class.getName());
settings.put(AvailableSettings.JTA_PLATFORM, jtaPlatform);
}
settings.put( AvailableSettings.CACHE_REGION_FACTORY, TestRegionFactoryProvider.load().getRegionFactoryClass() );
settings.put( AvailableSettings.CACHE_REGION_PREFIX, regionPrefix );
settings.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, String.valueOf( use2ndLevel ) );
settings.put( AvailableSettings.USE_QUERY_CACHE, String.valueOf( useQueries ) );
return settings;
}
public static StandardServiceRegistryBuilder buildBaselineStandardServiceRegistryBuilder(
String regionPrefix,
boolean use2ndLevel,
boolean useQueries,
Class<? extends JtaPlatform> jtaPlatform) {
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
ssrb.applySettings(
buildBaselineSettings( regionPrefix, use2ndLevel, useQueries, jtaPlatform )
);
return ssrb;
}
public static StandardServiceRegistryBuilder buildCustomQueryCacheStandardServiceRegistryBuilder(
String regionPrefix,
String queryCacheName,
Class<? extends JtaPlatform> jtaPlatform) {
final StandardServiceRegistryBuilder ssrb = buildBaselineStandardServiceRegistryBuilder(
regionPrefix, true, true, jtaPlatform
);
ssrb.applySetting( InfinispanProperties.QUERY_CACHE_RESOURCE_PROP, queryCacheName );
return ssrb;
}
public static <RF extends RegionFactory> RF createRegionFactory(Class<RF> clazz, Properties properties) {
try {
try {
Constructor<RF> constructor = clazz.getConstructor(Properties.class);
return constructor.newInstance(properties);
}
catch (NoSuchMethodException e) {
return clazz.newInstance();
}
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public static TestRegionFactory startRegionFactory(ServiceRegistry serviceRegistry) {
try {
final ConfigurationService cfgService = serviceRegistry.getService( ConfigurationService.class );
final Properties properties = toProperties( cfgService.getSettings() );
TestRegionFactory regionFactory = TestRegionFactoryProvider.load().create(properties);
regionFactory.start( serviceRegistry, properties );
return regionFactory;
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public static TestRegionFactory startRegionFactory(
ServiceRegistry serviceRegistry,
CacheTestSupport testSupport) {
TestRegionFactory factory = startRegionFactory( serviceRegistry );
testSupport.registerFactory( factory );
return factory;
}
public static void stopRegionFactory(
TestRegionFactory factory,
CacheTestSupport testSupport) {
testSupport.unregisterFactory( factory );
factory.stop();
}
public static Properties toProperties(Map map) {
if ( map == null ) {
return null;
}
if ( map instanceof Properties ) {
return (Properties) map;
}
Properties properties = new Properties();
properties.putAll( map );
return properties;
}
/**
* Prevent instantiation.
*/
private CacheTestUtil() {
}
}
| 5,119
| 32.464052
| 130
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/TestingUtil.java
|
package org.infinispan.test.hibernate.cache.commons.util;
import java.util.concurrent.Callable;
import jakarta.transaction.Status;
import jakarta.transaction.TransactionManager;
public class TestingUtil {
private TestingUtil() {
}
/**
* Call an operation within a transaction. This method guarantees that the
* right pattern is used to make sure that the transaction is always either
* committed or rollbacked.
*
* @param tm transaction manager
* @param c callable instance to run within a transaction
* @param <T> type returned from the callable
* @return returns whatever the callable returns
*/
public static <T> T withTx(TransactionManager tm, Callable<T> c) throws Exception {
return withTxCallable(tm, c).call();
}
/**
* Returns a callable that will call the provided callable within a transaction. This method guarantees that the
* right pattern is used to make sure that the transaction is always either committed or rollbacked around
* the callable.
*
* @param tm transaction manager
* @param c callable instance to run within a transaction
* @param <T> tyep of callable to return
* @return The callable to invoke. Note as long as the provided callable is thread safe this callable will be as well
*/
public static <T> Callable<T> withTxCallable(final TransactionManager tm, final Callable<? extends T> c) {
return () -> {
tm.begin();
try {
return c.call();
} catch (Exception e) {
tm.setRollbackOnly();
throw e;
} finally {
if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit();
else tm.rollback();
}
};
}
}
| 1,746
| 33.254902
| 121
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/TestRegionFactory.java
|
package org.infinispan.test.hibernate.cache.commons.util;
import java.util.Properties;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.service.ServiceRegistry;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.hibernate.cache.commons.TimeSource;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.manager.EmbeddedCacheManager;
public interface TestRegionFactory extends TimeSource {
String PREFIX = TestRegionFactory.class.getName() + ".";
String PENDING_PUTS_SIMPLE = PREFIX + "pendingPuts.simple";
String CACHE_MODE = PREFIX + "cacheMode";
String TRANSACTIONAL = PREFIX + "transactional";
String TIME_SERVICE = PREFIX + "timeService";
String MANAGER = PREFIX + "manager";
String AFTER_MANAGER_CREATED = PREFIX + "afterManagerCreated";
String WRAP_CACHE = PREFIX + "wrap.cache";
String CONFIGURATION_HOOK = PREFIX + "configuration.hook";
String STATS = PREFIX + "stats";
void start(ServiceRegistry serviceRegistry, Properties p);
void stop();
void setCacheManager(EmbeddedCacheManager cm);
EmbeddedCacheManager getCacheManager();
String getBaseConfiguration(String regionName);
Configuration getConfigurationOverride(String regionName);
Configuration getPendingPutsCacheConfiguration();
InfinispanBaseRegion buildCollectionRegion(String regionName, AccessType accessType);
InfinispanBaseRegion buildEntityRegion(String regionName, AccessType accessType);
InfinispanBaseRegion buildTimestampsRegion(String regionName);
InfinispanBaseRegion buildQueryResultsRegion(String regionName);
RegionFactory unwrap();
}
| 1,728
| 34.285714
| 88
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/ExpectingInterceptor.java
|
package org.infinispan.test.hibernate.cache.commons.util;
import org.infinispan.AdvancedCache;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.interceptors.InvocationFinallyAction;
import org.infinispan.interceptors.impl.InvocationContextInterceptor;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.function.BiPredicate;
import java.util.function.BooleanSupplier;
import static org.junit.Assert.assertTrue;
public class ExpectingInterceptor extends BaseCustomAsyncInterceptor {
private final static Log log = LogFactory.getLog(ExpectingInterceptor.class);
private final List<Condition> conditions = new LinkedList<>();
private InvocationFinallyAction assertCondition = this::assertCondition;
public static ExpectingInterceptor get(AdvancedCache cache) {
ExpectingInterceptor self = cache.getAsyncInterceptorChain().findInterceptorWithClass(ExpectingInterceptor.class);
if (self != null) {
return self;
}
ExpectingInterceptor ei = new ExpectingInterceptor();
// We are adding this after ICI because we want to handle silent failures, too
assertTrue(cache.getAsyncInterceptorChain().addInterceptorAfter(ei, InvocationContextInterceptor.class));
return ei;
}
public static void cleanup(AdvancedCache... caches) {
for (AdvancedCache c : caches) c.getAsyncInterceptorChain().removeInterceptor(ExpectingInterceptor.class);
}
public synchronized Condition when(BiPredicate<InvocationContext, VisitableCommand> predicate) {
Condition condition = new Condition(predicate, source(), null);
conditions.add(condition);
return condition;
}
public synchronized Condition whenFails(BiPredicate<InvocationContext, VisitableCommand> predicate) {
Condition condition = new Condition(predicate, source(), Boolean.FALSE);
conditions.add(condition);
return condition;
}
private static String source() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement ste = stackTrace[3];
return ste.getFileName() + ":" + ste.getLineNumber();
}
@Override
protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextAndFinally(ctx, command, assertCondition);
}
private void assertCondition(InvocationContext rCtx, VisitableCommand rCommand, Object rv, Throwable throwable) throws Throwable {
boolean succeeded = throwable == null && rCommand.isSuccessful();
log.tracef("After command(successful=%s) %s", succeeded, rCommand);
List<Runnable> toExecute = new ArrayList<>();
synchronized (ExpectingInterceptor.this) {
for (Iterator<Condition> iterator = conditions.iterator(); iterator.hasNext(); ) {
Condition condition = iterator.next();
log.tracef("Testing condition %s", condition);
if ((condition.success == null || condition.success == succeeded) && condition.predicate.test(rCtx, rCommand)) {
assert condition.action != null;
log.trace("Condition succeeded");
toExecute.add(condition.action);
if (condition.removeCheck == null || condition.removeCheck.getAsBoolean()) {
iterator.remove();
}
} else {
log.trace("Condition test failed");
}
}
}
// execute without holding the lock
for (Runnable runnable : toExecute) {
log.tracef("Executing %s", runnable);
runnable.run();
}
}
public class Condition {
private final BiPredicate<InvocationContext, VisitableCommand> predicate;
private final String source;
private final Boolean success;
private BooleanSupplier removeCheck;
private Runnable action;
public Condition(BiPredicate<InvocationContext, VisitableCommand> predicate, String source, Boolean success) {
this.predicate = predicate;
this.source = source;
this.success = success;
}
public Condition run(Runnable action) {
assert this.action == null;
this.action = action;
return this;
}
public Condition countDown(CountDownLatch latch) {
return run(() -> {
log.debugf("Count down latch %s", latch);
latch.countDown();
}).removeWhen(() -> latch.getCount() == 0);
}
public Condition removeWhen(BooleanSupplier check) {
assert this.removeCheck == null;
this.removeCheck = check;
return this;
}
public void cancel() {
synchronized (ExpectingInterceptor.this) {
conditions.remove(this);
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Condition{");
sb.append("source=").append(source);
sb.append(", predicate=").append(predicate);
sb.append(", success=").append(success);
sb.append(", action=").append(action);
sb.append('}');
return sb.toString();
}
}
}
| 5,474
| 37.286713
| 133
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/TxUtil.java
|
package org.infinispan.test.hibernate.cache.commons.util;
import java.util.concurrent.Callable;
import org.hibernate.Session;
import org.hibernate.SessionBuilder;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.infinispan.hibernate.cache.commons.util.Caches;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionManager;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public final class TxUtil {
public static void withTxSession(boolean useJta, SessionFactory sessionFactory, ThrowingConsumer<Session, Exception> consumer) throws Exception {
JtaPlatform jtaPlatform = useJta ? sessionFactory.getSessionFactoryOptions().getServiceRegistry().getService(JtaPlatform.class) : null;
withTxSession(jtaPlatform, sessionFactory.withOptions(), consumer);
}
public static void withTxSession(JtaPlatform jtaPlatform, SessionBuilder sessionBuilder, ThrowingConsumer<Session, Exception> consumer) throws Exception {
if (jtaPlatform != null) {
TransactionManager tm = jtaPlatform.retrieveTransactionManager();
final SessionBuilder sb = sessionBuilder;
Caches.withinTx(tm, () -> {
withSession(sb, s -> {
consumer.accept(s);
// we need to flush the session before close when running with JTA transactions
s.flush();
});
return null;
});
} else {
withSession(sessionBuilder, s -> withResourceLocalTx(s, consumer));
}
}
public static <T> T withTxSessionApply(boolean useJta, SessionFactory sessionFactory, ThrowingFunction<Session, T, Exception> function) throws Exception {
JtaPlatform jtaPlatform = useJta ? sessionFactory.getSessionFactoryOptions().getServiceRegistry().getService(JtaPlatform.class) : null;
return withTxSessionApply(jtaPlatform, sessionFactory.withOptions(), function);
}
public static <T> T withTxSessionApply(JtaPlatform jtaPlatform, SessionBuilder sessionBuilder, ThrowingFunction<Session, T, Exception> function) throws Exception {
if (jtaPlatform != null) {
TransactionManager tm = jtaPlatform.retrieveTransactionManager();
Callable<T> callable = () -> withSessionApply(sessionBuilder, s -> {
T t = function.apply(s);
s.flush();
return t;
});
return Caches.withinTx(tm, callable);
} else {
return withSessionApply(sessionBuilder, s -> withResourceLocalTx(s, function));
}
}
public static <E extends Throwable> void withSession(SessionBuilder sessionBuilder, ThrowingConsumer<Session, E> consumer) throws E {
Session s = sessionBuilder.openSession();
try {
consumer.accept(s);
} finally {
s.close();
}
}
public static <R, E extends Throwable> R withSessionApply(SessionBuilder sessionBuilder, ThrowingFunction<Session, R, E> function) throws E {
Session s = sessionBuilder.openSession();
try {
return function.apply(s);
} finally {
s.close();
}
}
public static void withResourceLocalTx(Session session, ThrowingConsumer<Session, Exception> consumer) throws Exception {
Transaction transaction = session.beginTransaction();
boolean rollingBack = false;
try {
consumer.accept(session);
if (transaction.getStatus() == TransactionStatus.ACTIVE) {
transaction.commit();
} else {
rollingBack = true;
transaction.rollback();
}
} catch (Exception e) {
if (!rollingBack) {
try {
transaction.rollback();
} catch (Exception suppressed) {
e.addSuppressed(suppressed);
}
}
throw e;
}
}
public static <T> T withResourceLocalTx(Session session, ThrowingFunction<Session, T, Exception> consumer) throws Exception {
Transaction transaction = session.beginTransaction();
boolean rollingBack = false;
try {
T t = consumer.apply(session);
if (transaction.getStatus() == TransactionStatus.ACTIVE) {
transaction.commit();
} else {
rollingBack = true;
transaction.rollback();
}
return t;
} catch (Exception e) {
if (!rollingBack) {
try {
transaction.rollback();
} catch (Exception suppressed) {
e.addSuppressed(suppressed);
}
}
throw e;
}
}
public static void markRollbackOnly(boolean useJta, Session s) {
if (useJta) {
JtaPlatform jtaPlatform = s.getSessionFactory().getSessionFactoryOptions().getServiceRegistry().getService(JtaPlatform.class);
TransactionManager tm = jtaPlatform.retrieveTransactionManager();
try {
tm.setRollbackOnly();
} catch (SystemException e) {
throw new RuntimeException(e);
}
} else {
s.getTransaction().markRollbackOnly();
}
}
public interface ThrowingConsumer<T, E extends Throwable> {
void accept(T t) throws E;
}
public interface ThrowingFunction<T, R, E extends Throwable> {
R apply(T t) throws E;
}
}
| 4,849
| 31.77027
| 164
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/TestRegionFactoryProvider.java
|
package org.infinispan.test.hibernate.cache.commons.util;
import java.util.Properties;
import java.util.ServiceLoader;
import org.hibernate.Cache;
import org.hibernate.cache.spi.RegionFactory;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
public interface TestRegionFactoryProvider {
TestRegionFactoryProvider INSTANCE = ServiceLoader.load(TestRegionFactoryProvider.class).iterator().next();
static TestRegionFactoryProvider load() {
return INSTANCE;
}
Class<? extends RegionFactory> getRegionFactoryClass();
Class<? extends RegionFactory> getClusterAwareClass();
TestRegionFactory create(Properties properties);
TestRegionFactory wrap(RegionFactory regionFactory);
TestRegionFactory findRegionFactory(Cache cache);
InfinispanBaseRegion findTimestampsRegion(Cache cache);
boolean supportTransactionalCaches();
}
| 881
| 27.451613
| 110
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/CacheTestSupport.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.util;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.infinispan.Cache;
/**
* Support class for tracking and cleaning up objects used in tests.
*
* @author <a href="brian.stansberry@jboss.com">Brian Stansberry</a>
*/
public class CacheTestSupport {
private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack";
private Set<Cache> caches = new HashSet<>();
private Set<TestRegionFactory> factories = new HashSet<>();
private Exception exception;
private String preferIPv4Stack;
public void registerCache(Cache cache) {
caches.add(cache);
}
public void registerFactory(TestRegionFactory factory) {
factories.add(factory);
}
public void unregisterCache(Cache cache) {
caches.remove( cache );
}
public void unregisterFactory(TestRegionFactory factory) {
factories.remove( factory );
}
public void setUp() throws Exception {
// Try to ensure we use IPv4; otherwise cluster formation is very slow
preferIPv4Stack = System.getProperty(PREFER_IPV4STACK);
System.setProperty(PREFER_IPV4STACK, "true");
cleanUp();
throwStoredException();
}
public void tearDown() throws Exception {
if (preferIPv4Stack == null)
System.clearProperty(PREFER_IPV4STACK);
else
System.setProperty(PREFER_IPV4STACK, preferIPv4Stack);
cleanUp();
throwStoredException();
}
private void cleanUp() {
for (Iterator<TestRegionFactory> it = factories.iterator(); it.hasNext(); ) {
try {
it.next().stop();
}
catch (Exception e) {
storeException(e);
}
finally {
it.remove();
}
}
factories.clear();
for (Iterator<Cache> it = caches.iterator(); it.hasNext(); ) {
try {
it.next().stop();
}
catch (Exception e) {
storeException(e);
}
finally {
it.remove();
}
}
caches.clear();
}
private void storeException(Exception e) {
if (this.exception == null) {
this.exception = e;
}
}
private void throwStoredException() throws Exception {
if (exception != null) {
Exception toThrow = exception;
exception = null;
throw toThrow;
}
}
}
| 2,826
| 25.669811
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/TestSynchronization.java
|
package org.infinispan.test.hibernate.cache.commons.util;
import org.hibernate.cache.spi.access.SoftLock;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess.TestRegionAccessStrategy;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public abstract class TestSynchronization implements jakarta.transaction.Synchronization {
protected final Object session;
protected final Object key;
protected final Object value;
protected final Object version;
public TestSynchronization(Object session, Object key, Object value, Object version) {
this.session = session;
this.key = key;
this.value = value;
this.version = version;
}
@Override
public void beforeCompletion() {
}
public static class AfterInsert extends TestSynchronization {
private final TestRegionAccessStrategy strategy;
public AfterInsert(TestRegionAccessStrategy strategy, Object session, Object key, Object value, Object version) {
super(session, key, value, version);
this.strategy = strategy;
}
@Override
public void afterCompletion(int status) {
strategy.afterInsert(session, key, value, version);
}
}
public static class AfterUpdate extends TestSynchronization {
private final TestRegionAccessStrategy strategy;
private final SoftLock lock;
public AfterUpdate(TestRegionAccessStrategy strategy, Object session, Object key, Object value, Object version, SoftLock lock) {
super(session, key, value, version);
this.strategy = strategy;
this.lock = lock;
}
@Override
public void afterCompletion(int status) {
strategy.afterUpdate(session, key, value, version, null, lock);
}
}
public static class UnlockItem extends TestSynchronization {
private final TestRegionAccessStrategy strategy;
private final SoftLock lock;
public UnlockItem(TestRegionAccessStrategy strategy, Object session, Object key, SoftLock lock) {
super(session, key, null, null);
this.strategy = strategy;
this.lock = lock;
}
@Override
public void afterCompletion(int status) {
strategy.unlockItem(session, key, lock);
}
}
}
| 2,089
| 27.630137
| 130
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/TestConfigurationHook.java
|
package org.infinispan.test.hibernate.cache.commons.util;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.DEF_PENDING_PUTS_RESOURCE;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.DEF_TIMESTAMPS_RESOURCE;
import java.util.Map;
import java.util.Properties;
import org.infinispan.commons.executors.CachedThreadPoolExecutorFactory;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.TransportConfigurationBuilder;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.commons.test.TestResourceTracker;
import org.infinispan.transaction.TransactionMode;
public class TestConfigurationHook {
private final boolean transactional;
private final CacheMode cacheMode;
private final boolean pendingPutsSimple;
private final boolean stats;
public TestConfigurationHook(Properties properties) {
transactional = (boolean) properties.getOrDefault(TestRegionFactory.TRANSACTIONAL, false);
cacheMode = (CacheMode) properties.getOrDefault(TestRegionFactory.CACHE_MODE, null);
pendingPutsSimple = (boolean) properties.getOrDefault(TestRegionFactory.PENDING_PUTS_SIMPLE, true);
stats = (boolean) properties.getOrDefault(TestRegionFactory.STATS, false);
}
public void amendConfiguration(ConfigurationBuilderHolder holder) {
TransportConfigurationBuilder transport = holder.getGlobalConfigurationBuilder().transport();
transport.nodeName(TestResourceTracker.getNextNodeName());
transport.clusterName(TestResourceTracker.getCurrentTestName());
// minimize number of threads using unlimited cached thread pool
transport.remoteCommandThreadPool().threadPoolFactory(CachedThreadPoolExecutorFactory.create());
transport.transportThreadPool().threadPoolFactory(CachedThreadPoolExecutorFactory.create());
for (Map.Entry<String, ConfigurationBuilder> cfg : holder.getNamedConfigurationBuilders().entrySet()) {
amendCacheConfiguration(cfg.getKey(), cfg.getValue());
}
// disable simple cache for testing as we need to insert interceptors
if (!pendingPutsSimple) {
holder.getNamedConfigurationBuilders().get(DEF_PENDING_PUTS_RESOURCE).simpleCache(false);
}
}
public void amendCacheConfiguration(String cacheName, ConfigurationBuilder configurationBuilder) {
if (cacheName.equals(DEF_PENDING_PUTS_RESOURCE)) {
return;
}
if (transactional) {
if (!cacheName.endsWith("query") && !cacheName.equals(DEF_TIMESTAMPS_RESOURCE) && !cacheName.endsWith(DEF_PENDING_PUTS_RESOURCE)) {
configurationBuilder.transaction().transactionMode(TransactionMode.TRANSACTIONAL).useSynchronization(true);
}
} else {
configurationBuilder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL);
}
if (cacheMode != null) {
if (configurationBuilder.clustering().cacheMode().isInvalidation()) {
configurationBuilder.clustering().cacheMode(cacheMode);
}
}
if (stats) {
configurationBuilder.statistics().available(true).enable();
}
}
}
| 3,264
| 47.014706
| 140
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/util/ClassLoaderAwareCache.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.util;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import java.lang.annotation.Annotation;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import org.infinispan.AdvancedCache;
import org.infinispan.cache.impl.AbstractDelegatingAdvancedCache;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited;
import org.infinispan.notifications.cachelistener.event.Event;
import org.infinispan.stats.Stats;
/**
* @author Paul Ferraro
*/
public class ClassLoaderAwareCache<K, V> extends AbstractDelegatingAdvancedCache<K, V> {
final WeakReference<ClassLoader> classLoaderRef;
public ClassLoaderAwareCache(AdvancedCache<K, V> cache, ClassLoader classLoader) {
super(cache);
this.classLoaderRef = new WeakReference<ClassLoader>(classLoader);
extractInterceptorChain(cache).removeInterceptor(ClassLoaderAwareCommandInterceptor.class);
extractInterceptorChain(cache).addInterceptor(new ClassLoaderAwareCommandInterceptor(), 0);
}
@Override
public AdvancedCache rewrap(AdvancedCache newDelegate) {
return new ClassLoaderAwareCache(newDelegate, classLoaderRef.get());
}
@Override
public Stats getStats() {
return this.getAdvancedCache().getStats();
}
@Override
public void stop() {
super.stop();
this.classLoaderRef.clear();
}
@Override
public CompletionStage<Void> addListenerAsync(Object listener) {
return super.addListenerAsync(new ClassLoaderAwareListener(listener, this));
}
void setContextClassLoader(final ClassLoader classLoader) {
Thread.currentThread().setContextClassLoader(classLoader);
}
class ClassLoaderAwareCommandInterceptor extends BaseAsyncInterceptor {
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
// FIXME The listener is not guaranteed to run on the same thread
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
ClassLoaderAwareCache.this.setContextClassLoader(ClassLoaderAwareCache.this.classLoaderRef.get());
return invokeNextAndFinally(ctx, command, (rCtx, rCommand, rv, throwable) -> {
ClassLoaderAwareCache.this.setContextClassLoader(classLoader);
});
}
}
static final Map<Class<? extends Annotation>, Event.Type> events = new HashMap<Class<? extends Annotation>, Event.Type>();
static {
events.put(CacheEntryActivated.class, Event.Type.CACHE_ENTRY_ACTIVATED);
events.put(CacheEntryCreated.class, Event.Type.CACHE_ENTRY_CREATED);
events.put(CacheEntryInvalidated.class, Event.Type.CACHE_ENTRY_INVALIDATED);
events.put(CacheEntryLoaded.class, Event.Type.CACHE_ENTRY_LOADED);
events.put(CacheEntryModified.class, Event.Type.CACHE_ENTRY_MODIFIED);
events.put(CacheEntryPassivated.class, Event.Type.CACHE_ENTRY_PASSIVATED);
events.put(CacheEntryRemoved.class, Event.Type.CACHE_ENTRY_REMOVED);
events.put(CacheEntryVisited.class, Event.Type.CACHE_ENTRY_VISITED);
}
@Listener
public static class ClassLoaderAwareListener {
private final Object listener;
private final Map<Event.Type, List<Method>> methods = new EnumMap<Event.Type, List<Method>>(Event.Type.class);
private final ClassLoaderAwareCache cache;
public ClassLoaderAwareListener(Object listener, ClassLoaderAwareCache cache) {
this.listener = listener;
this.cache = cache;
for (Method method : listener.getClass().getMethods()) {
for (Map.Entry<Class<? extends Annotation>, Event.Type> entry : events.entrySet()) {
Class<? extends Annotation> annotation = entry.getKey();
if (method.isAnnotationPresent(annotation)) {
List<Method> methods = this.methods.get(entry.getValue());
if (methods == null) {
methods = new LinkedList<Method>();
this.methods.put(entry.getValue(), methods);
}
methods.add(method);
}
}
}
}
@CacheEntryActivated
@CacheEntryCreated
@CacheEntryInvalidated
@CacheEntryLoaded
@CacheEntryModified
@CacheEntryPassivated
@CacheEntryRemoved
@CacheEntryVisited
public void event(Event event) throws Throwable {
List<Method> methods = this.methods.get(event.getType());
if (methods != null) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
ClassLoader visible = (ClassLoader) cache.classLoaderRef.get();
cache.setContextClassLoader(visible);
try {
for (Method method : this.methods.get(event.getType())) {
try {
method.invoke(this.listener, event);
}
catch (InvocationTargetException e) {
throw e.getCause();
}
}
}
finally {
cache.setContextClassLoader(classLoader);
}
}
}
public int hashCode() {
return this.listener.hashCode();
}
public boolean equals(Object object) {
if (object == null) return false;
if (object instanceof ClassLoaderAwareCache.ClassLoaderAwareListener) {
@SuppressWarnings("unchecked")
ClassLoaderAwareListener listener = (ClassLoaderAwareListener) object;
return this.listener.equals(listener.listener);
}
return this.listener.equals(object);
}
}
}
| 6,974
| 39.789474
| 125
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/timestamp/TimestampsRegionImplTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.timestamp;
import java.util.Properties;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.infinispan.commons.test.categories.Smoke;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.test.hibernate.cache.commons.AbstractGeneralDataRegionTest;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Account;
import org.infinispan.test.hibernate.cache.commons.functional.entities.AccountHolder;
import org.infinispan.test.hibernate.cache.commons.functional.classloader.SelectedClassnameClassLoader;
import org.infinispan.test.hibernate.cache.commons.util.CacheTestUtil;
import org.infinispan.test.hibernate.cache.commons.util.ClassLoaderAwareCache;
import org.infinispan.AdvancedCache;
import org.infinispan.context.Flag;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited;
import org.infinispan.notifications.cachelistener.event.Event;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* Tests of TimestampsRegionImpl.
*
* @author Galder Zamarreño
* @since 3.5
*/
@Category(Smoke.class)
public class TimestampsRegionImplTest extends AbstractGeneralDataRegionTest {
@Override
protected InfinispanBaseRegion createRegion(TestRegionFactory regionFactory, String regionName) {
return regionFactory.buildTimestampsRegion(regionName);
}
@Test
public void testClearTimestampsRegionInIsolated() throws Exception {
StandardServiceRegistryBuilder ssrb = createStandardServiceRegistryBuilder();
final StandardServiceRegistry registry = ssrb.build();
final StandardServiceRegistry registry2 = ssrb.build();
try {
final Properties properties = CacheTestUtil.toProperties( ssrb.getSettings() );
TestRegionFactory regionFactory = CacheTestUtil.startRegionFactory(
registry,
getCacheTestSupport()
);
TestRegionFactory regionFactory2 = CacheTestUtil.startRegionFactory(
registry2,
getCacheTestSupport()
);
InfinispanBaseRegion region = regionFactory.buildTimestampsRegion(REGION_PREFIX + "/timestamps");
InfinispanBaseRegion region2 = regionFactory2.buildTimestampsRegion(REGION_PREFIX + "/timestamps");
Account acct = new Account();
acct.setAccountHolder(new AccountHolder());
region.getCache().withFlags(Flag.FORCE_SYNCHRONOUS).put(acct, "boo");
}
finally {
StandardServiceRegistryBuilder.destroy( registry );
StandardServiceRegistryBuilder.destroy( registry2 );
}
}
@Override
protected StandardServiceRegistryBuilder createStandardServiceRegistryBuilder() {
StandardServiceRegistryBuilder ssrb = super.createStandardServiceRegistryBuilder();
ssrb.applySetting(TestRegionFactory.WRAP_CACHE, (Function<AdvancedCache, AdvancedCache>) cache ->
new ClassLoaderAwareCache(cache, Thread.currentThread().getContextClassLoader()) {
@Override
public void addListener(Object listener) {
super.addListener(new MockClassLoaderAwareListener(listener, this));
}
@Override
public CompletionStage<Void> addListenerAsync(Object listener) {
return super.addListenerAsync(new MockClassLoaderAwareListener(listener, this));
}
}
);
return ssrb;
}
@Listener
public static class MockClassLoaderAwareListener extends ClassLoaderAwareCache.ClassLoaderAwareListener {
MockClassLoaderAwareListener(Object listener, ClassLoaderAwareCache cache) {
super(listener, cache);
}
@CacheEntryActivated
@CacheEntryCreated
@CacheEntryInvalidated
@CacheEntryLoaded
@CacheEntryModified
@CacheEntryPassivated
@CacheEntryRemoved
@CacheEntryVisited
public void event(Event event) throws Throwable {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
String notFoundPackage = "org.infinispan.test.hibernate.cache.functional.entities";
String[] notFoundClasses = { notFoundPackage + ".Account", notFoundPackage + ".AccountHolder" };
SelectedClassnameClassLoader visible = new SelectedClassnameClassLoader(null, null, notFoundClasses, cl);
Thread.currentThread().setContextClassLoader(visible);
super.event(event);
Thread.currentThread().setContextClassLoader(cl);
}
}
}
| 5,331
| 39.70229
| 108
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/access/PutFromLoadValidatorUnitTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.access;
import static org.infinispan.commons.test.Exceptions.expectException;
import static org.infinispan.test.hibernate.cache.commons.util.TestingUtil.withTx;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.boot.ServiceRegistryTestingImpl;
import org.hibernate.testing.junit4.CustomRunner;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.test.TestResourceTracker;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.hibernate.cache.commons.access.PutFromLoadValidator;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.test.hibernate.cache.commons.functional.cluster.DualNodeJtaTransactionManagerImpl;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import org.infinispan.util.ControlledTimeService;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.transaction.TransactionManager;
/**
* Tests of {@link PutFromLoadValidator}.
*
* @author Brian Stansberry
* @author Galder Zamarreño
* @version $Revision: $
*/
@RunWith(CustomRunner.class)
public class PutFromLoadValidatorUnitTest {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(
PutFromLoadValidatorUnitTest.class);
private static final ControlledTimeService TIME_SERVICE = new ControlledTimeService();
protected static final TestSessionAccess TEST_SESSION_ACCESS = TestSessionAccess.findTestSessionAccess();
private static ServiceRegistryTestingImpl serviceRegistry;
private Object KEY1 = "KEY1";
private TransactionManager tm;
private EmbeddedCacheManager cm;
private AdvancedCache<Object, Object> cache;
private List<Runnable> cleanup = new ArrayList<>();
private PutFromLoadValidator testee;
@BeforeClassOnce
public void setUp() throws Exception {
TestResourceTracker.testStarted(getClass().getSimpleName());
serviceRegistry = ServiceRegistryTestingImpl.forUnitTesting();
tm = DualNodeJtaTransactionManagerImpl.getInstance("test");
cm = TestCacheManagerFactory.createCacheManager(true);
cache = cm.getCache().getAdvancedCache();
}
@AfterClassOnce
public void stop() {
tm = null;
cm.stop();
serviceRegistry.destroy();
TestResourceTracker.testFinished(getClass().getSimpleName());
}
@After
public void tearDown() throws Exception {
cleanup.forEach(Runnable::run);
cleanup.clear();
try {
DualNodeJtaTransactionManagerImpl.cleanupTransactions();
}
finally {
DualNodeJtaTransactionManagerImpl.cleanupTransactionManagers();
}
cache.clear();
cm.getCache(cache.getName() + "-" + InfinispanProperties.DEF_PENDING_PUTS_RESOURCE).clear();
testee.removePendingPutsCache();
}
private static TestRegionFactory regionFactory(EmbeddedCacheManager cm) {
Properties properties = new Properties();
properties.put(TestRegionFactory.TIME_SERVICE, TIME_SERVICE);
TestRegionFactory regionFactory = TestRegionFactoryProvider.load().create(properties);
regionFactory.setCacheManager(cm);
regionFactory.start(serviceRegistry, properties);
return regionFactory;
}
@Test
public void testNakedPut() {
nakedPutTest(false);
}
@Test
public void testNakedPutTransactional() {
nakedPutTest(true);
}
private void nakedPutTest(final boolean transactional) {
TestRegionFactory regionFactory = regionFactory(cm);
testee = new PutFromLoadValidator(cache, regionFactory, regionFactory.getPendingPutsCacheConfiguration());
exec(transactional, new NakedPut(testee, true));
}
@Test
public void testRegisteredPut() {
registeredPutTest(false);
}
@Test
public void testRegisteredPutTransactional() {
registeredPutTest(true);
}
private void registeredPutTest(final boolean transactional) {
TestRegionFactory regionFactory = regionFactory(cm);
testee = new PutFromLoadValidator(cache, regionFactory, regionFactory.getPendingPutsCacheConfiguration());
exec(transactional, new RegularPut(testee));
}
@Test
public void testNakedPutAfterKeyRemoval() {
nakedPutAfterRemovalTest(false, false);
}
@Test
public void testNakedPutAfterKeyRemovalTransactional() {
nakedPutAfterRemovalTest(true, false);
}
@Test
public void testNakedPutAfterRegionRemoval() {
nakedPutAfterRemovalTest(false, true);
}
@Test
public void testNakedPutAfterRegionRemovalTransactional() {
nakedPutAfterRemovalTest(true, true);
}
private void nakedPutAfterRemovalTest(final boolean transactional,
final boolean removeRegion) {
TestRegionFactory regionFactory = regionFactory(cm);
testee = new PutFromLoadValidator(cache, regionFactory, regionFactory.getPendingPutsCacheConfiguration());
Invalidation invalidation = new Invalidation(testee, removeRegion);
// the naked put can succeed because it has txTimestamp after invalidation
NakedPut nakedPut = new NakedPut(testee, true);
exec(transactional, invalidation, nakedPut);
}
@Test
public void testRegisteredPutAfterKeyRemoval() {
registeredPutAfterRemovalTest(false, false);
}
@Test
public void testRegisteredPutAfterKeyRemovalTransactional() {
registeredPutAfterRemovalTest(true, false);
}
@Test
public void testRegisteredPutAfterRegionRemoval() {
registeredPutAfterRemovalTest(false, true);
}
@Test
public void testRegisteredPutAfterRegionRemovalTransactional() {
registeredPutAfterRemovalTest(true, true);
}
private void registeredPutAfterRemovalTest(final boolean transactional,
final boolean removeRegion) {
TestRegionFactory regionFactory = regionFactory(cm);
testee = new PutFromLoadValidator(cache, regionFactory, regionFactory.getPendingPutsCacheConfiguration());
Invalidation invalidation = new Invalidation(testee, removeRegion);
RegularPut regularPut = new RegularPut(testee);
exec(transactional, invalidation, regularPut);
}
@Test
public void testRegisteredPutWithInterveningKeyRemoval() {
registeredPutWithInterveningRemovalTest(false, false);
}
@Test
public void testRegisteredPutWithInterveningKeyRemovalTransactional() {
registeredPutWithInterveningRemovalTest(true, false);
}
@Test
public void testRegisteredPutWithInterveningRegionRemoval() {
registeredPutWithInterveningRemovalTest(false, true);
}
@Test
public void testRegisteredPutWithInterveningRegionRemovalTransactional() {
registeredPutWithInterveningRemovalTest(true, true);
}
private void registeredPutWithInterveningRemovalTest(
final boolean transactional, final boolean removeRegion) {
TestRegionFactory regionFactory = regionFactory(cm);
testee = new PutFromLoadValidator(cache, regionFactory, regionFactory.getPendingPutsCacheConfiguration());
try {
long txTimestamp = TIME_SERVICE.wallClockTime();
if (transactional) {
tm.begin();
}
Object session1 = TEST_SESSION_ACCESS.mockSessionImplementor();
Object session2 = TEST_SESSION_ACCESS.mockSessionImplementor();
testee.registerPendingPut(session1, KEY1, txTimestamp);
if (removeRegion) {
testee.beginInvalidatingRegion();
} else {
testee.beginInvalidatingKey(session2, KEY1);
}
PutFromLoadValidator.Lock lock = testee.acquirePutFromLoadLock(session1, KEY1, txTimestamp);
try {
assertNull(lock);
}
finally {
if (lock != null) {
testee.releasePutFromLoadLock(KEY1, lock);
}
if (removeRegion) {
testee.endInvalidatingRegion();
} else {
testee.endInvalidatingKey(session2, KEY1);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void testMultipleRegistrations() throws Exception {
multipleRegistrationtest(false);
}
@Test
public void testMultipleRegistrationsTransactional() throws Exception {
multipleRegistrationtest(true);
}
private void multipleRegistrationtest(final boolean transactional) throws Exception {
TestRegionFactory regionFactory = regionFactory(cm);
testee = new PutFromLoadValidator(cache, regionFactory, regionFactory.getPendingPutsCacheConfiguration());
final CountDownLatch registeredLatch = new CountDownLatch(3);
final CountDownLatch finishedLatch = new CountDownLatch(3);
final AtomicInteger success = new AtomicInteger();
Runnable r = () -> {
try {
long txTimestamp = TIME_SERVICE.wallClockTime();
if (transactional) {
tm.begin();
}
Object session = TEST_SESSION_ACCESS.mockSessionImplementor();
testee.registerPendingPut(session, KEY1, txTimestamp);
registeredLatch.countDown();
registeredLatch.await(5, TimeUnit.SECONDS);
PutFromLoadValidator.Lock lock = testee.acquirePutFromLoadLock(session, KEY1, txTimestamp);
if (lock != null) {
try {
log.trace("Put from load lock acquired for key = " + KEY1);
success.incrementAndGet();
} finally {
testee.releasePutFromLoadLock(KEY1, lock);
}
} else {
log.trace("Unable to acquired putFromLoad lock for key = " + KEY1);
}
finishedLatch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
};
ExecutorService executor = Executors.newFixedThreadPool(3);
cleanup.add(() -> executor.shutdownNow());
// Start with a removal so the "isPutValid" calls will fail if
// any of the concurrent activity isn't handled properly
testee.beginInvalidatingRegion();
testee.endInvalidatingRegion();
TIME_SERVICE.advance(1);
// Do the registration + isPutValid calls
executor.execute(r);
executor.execute(r);
executor.execute(r);
assertTrue(finishedLatch.await(5, TimeUnit.SECONDS));
assertEquals("All threads succeeded", 3, success.get());
}
@Test
public void testInvalidateKeyBlocksForInProgressPut() throws Exception {
invalidationBlocksForInProgressPutTest(true);
}
@Test
public void testInvalidateRegionBlocksForInProgressPut() throws Exception {
invalidationBlocksForInProgressPutTest(false);
}
private void invalidationBlocksForInProgressPutTest(final boolean keyOnly) throws Exception {
TestRegionFactory regionFactory = regionFactory(cm);
testee = new PutFromLoadValidator(cache, regionFactory, regionFactory.getPendingPutsCacheConfiguration());
final CountDownLatch removeLatch = new CountDownLatch(1);
final CountDownLatch pferLatch = new CountDownLatch(1);
final AtomicReference<Object> cache = new AtomicReference<>("INITIAL");
Callable<Boolean> pferCallable = () -> {
long txTimestamp = TIME_SERVICE.wallClockTime();
Object session = TEST_SESSION_ACCESS.mockSessionImplementor();
testee.registerPendingPut(session, KEY1, txTimestamp);
PutFromLoadValidator.Lock lock = testee.acquirePutFromLoadLock(session, KEY1, txTimestamp);
if (lock != null) {
try {
removeLatch.countDown();
pferLatch.await();
cache.set("PFER");
return Boolean.TRUE;
}
finally {
testee.releasePutFromLoadLock(KEY1, lock);
}
}
return Boolean.FALSE;
};
Callable<Void> invalidateCallable = () -> {
removeLatch.await();
if (keyOnly) {
Object session = TEST_SESSION_ACCESS.mockSessionImplementor();
testee.beginInvalidatingKey(session, KEY1);
} else {
testee.beginInvalidatingRegion();
}
cache.set(null);
return null;
};
ExecutorService executor = Executors.newCachedThreadPool();
cleanup.add(() -> executor.shutdownNow());
Future<Boolean> pferFuture = executor.submit(pferCallable);
Future<Void> invalidateFuture = executor.submit(invalidateCallable);
expectException(TimeoutException.class, () -> invalidateFuture.get(1, TimeUnit.SECONDS));
pferLatch.countDown();
assertTrue(pferFuture.get(5, TimeUnit.SECONDS));
invalidateFuture.get(5, TimeUnit.SECONDS);
assertNull(cache.get());
}
protected void exec(boolean transactional, Callable<?>... callables) {
try {
if (transactional) {
for (Callable<?> c : callables) {
withTx(tm, c);
}
} else {
for (Callable<?> c : callables) {
c.call();
}
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private class Invalidation implements Callable<Void> {
private PutFromLoadValidator putFromLoadValidator;
private boolean removeRegion;
public Invalidation(PutFromLoadValidator putFromLoadValidator, boolean removeRegion) {
this.putFromLoadValidator = putFromLoadValidator;
this.removeRegion = removeRegion;
}
@Override
public Void call() throws Exception {
if (removeRegion) {
boolean success = putFromLoadValidator.beginInvalidatingRegion();
assertTrue(success);
putFromLoadValidator.endInvalidatingRegion();
} else {
Object session = TEST_SESSION_ACCESS.mockSessionImplementor();
boolean success = putFromLoadValidator.beginInvalidatingKey(session, KEY1);
assertTrue(success);
success = putFromLoadValidator.endInvalidatingKey(session, KEY1);
assertTrue(success);
}
// if we go for the timestamp-based approach, invalidation in the same millisecond
// as the registerPendingPut/acquirePutFromLoad lock results in failure.
TIME_SERVICE.advance(1);
return null;
}
}
private class RegularPut implements Callable<Void> {
private PutFromLoadValidator putFromLoadValidator;
public RegularPut(PutFromLoadValidator putFromLoadValidator) {
this.putFromLoadValidator = putFromLoadValidator;
}
@Override
public Void call() throws Exception {
try {
long txTimestamp = TIME_SERVICE.wallClockTime(); // this should be acquired before UserTransaction.begin()
Object session = TEST_SESSION_ACCESS.mockSessionImplementor();
putFromLoadValidator.registerPendingPut(session, KEY1, txTimestamp);
PutFromLoadValidator.Lock lock = putFromLoadValidator.acquirePutFromLoadLock(session, KEY1, txTimestamp);
try {
assertNotNull(lock);
} finally {
if (lock != null) {
putFromLoadValidator.releasePutFromLoadLock(KEY1, lock);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
}
private class NakedPut implements Callable<Void> {
private final PutFromLoadValidator testee;
private final boolean expectSuccess;
public NakedPut(PutFromLoadValidator testee, boolean expectSuccess) {
this.testee = testee;
this.expectSuccess = expectSuccess;
}
@Override
public Void call() throws Exception {
try {
long txTimestamp = TIME_SERVICE.wallClockTime(); // this should be acquired before UserTransaction.begin()
Object session = TEST_SESSION_ACCESS.mockSessionImplementor();
PutFromLoadValidator.Lock lock = testee.acquirePutFromLoadLock(session, KEY1, txTimestamp);
try {
if (expectSuccess) {
assertNotNull(lock);
} else {
assertNull(lock);
}
}
finally {
if (lock != null) {
testee.releasePutFromLoadLock(KEY1, lock);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
}
@Test
@TestForIssue(jiraKey = "HHH-9928")
public void testGetForNullReleasePuts() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.simpleCache(true).expiration().maxIdle(500);
Configuration ppCfg = cb.build();
testee = new PutFromLoadValidator(cache, TIME_SERVICE::wallClockTime, cm, ppCfg);
for (int i = 0; i < 100; ++i) {
try {
withTx(tm, () -> {
Object session = TEST_SESSION_ACCESS.mockSessionImplementor();
testee.registerPendingPut(session, KEY1, 0);
return null;
});
TIME_SERVICE.advance(10);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
String ppName = cm.getCache().getName() + "-" + InfinispanProperties.DEF_PENDING_PUTS_RESOURCE;
Map ppCache = cm.getCache(ppName, false);
assertNotNull(ppCache);
Object pendingPutMap = ppCache.get(KEY1);
assertNotNull(pendingPutMap);
int size;
try {
Method sizeMethod = pendingPutMap.getClass().getMethod("size");
sizeMethod.setAccessible(true);
size = (Integer) sizeMethod.invoke(pendingPutMap);
} catch (Exception e) {
throw new RuntimeException(e);
}
// some of the pending puts need to be expired by now
assertTrue(size < 100);
// but some are still registered
assertTrue(size > 0);
}
}
| 17,677
| 31.919926
| 110
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/tm/XaTransactionImpl.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.tm;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
/**
* XaResourceCapableTransactionImpl.
*
* @author Galder Zamarreño
* @since 3.5
*/
public class XaTransactionImpl implements Transaction {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(XaTransactionImpl.class);
private int status;
private LinkedList synchronizations;
private Connection connection; // the only resource we care about is jdbc connection
private final XaTransactionManagerImpl jtaTransactionManager;
private List<XAResource> enlistedResources = new ArrayList<XAResource>();
private Xid xid = new XaResourceCapableTransactionXid();
private ConnectionProvider connectionProvider;
public XaTransactionImpl(XaTransactionManagerImpl jtaTransactionManager) {
this.jtaTransactionManager = jtaTransactionManager;
this.status = Status.STATUS_ACTIVE;
}
public XaTransactionImpl(XaTransactionManagerImpl jtaTransactionManager, Xid xid) {
this.jtaTransactionManager = jtaTransactionManager;
this.status = Status.STATUS_ACTIVE;
this.xid = xid;
}
public int getStatus() {
return status;
}
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException,
IllegalStateException, SystemException {
if (status == Status.STATUS_MARKED_ROLLBACK) {
log.trace("on commit, status was marked for rollback-only");
rollback();
} else {
status = Status.STATUS_PREPARING;
if ( synchronizations != null ) {
for ( int i = 0; i < synchronizations.size(); i++ ) {
Synchronization s = (Synchronization) synchronizations.get( i );
s.beforeCompletion();
}
}
if (!runXaResourcePrepare()) {
status = Status.STATUS_ROLLING_BACK;
} else {
status = Status.STATUS_PREPARED;
}
status = Status.STATUS_COMMITTING;
if (connection != null) {
try {
connection.commit();
connectionProvider.closeConnection(connection);
connection = null;
} catch (SQLException sqle) {
status = Status.STATUS_UNKNOWN;
throw new SystemException();
}
}
runXaResourceCommitTx();
status = Status.STATUS_COMMITTED;
if ( synchronizations != null ) {
for ( int i = 0; i < synchronizations.size(); i++ ) {
Synchronization s = (Synchronization) synchronizations.get( i );
s.afterCompletion( status );
}
}
// status = Status.STATUS_NO_TRANSACTION;
jtaTransactionManager.endCurrent(this);
}
}
public void rollback() throws IllegalStateException, SystemException {
status = Status.STATUS_ROLLING_BACK;
runXaResourceRollback();
status = Status.STATUS_ROLLEDBACK;
if (connection != null) {
try {
connection.rollback();
connection.close();
} catch (SQLException sqle) {
status = Status.STATUS_UNKNOWN;
throw new SystemException();
}
}
if (synchronizations != null) {
for (int i = 0; i < synchronizations.size(); i++) {
Synchronization s = (Synchronization) synchronizations.get(i);
if (s != null)
s.afterCompletion(status);
}
}
// status = Status.STATUS_NO_TRANSACTION;
jtaTransactionManager.endCurrent(this);
}
public void setRollbackOnly() throws IllegalStateException, SystemException {
status = Status.STATUS_MARKED_ROLLBACK;
}
public void registerSynchronization(Synchronization synchronization) throws RollbackException,
IllegalStateException, SystemException {
// todo : find the spec-allowable statuses during which synch can be registered...
if (synchronizations == null) {
synchronizations = new LinkedList();
}
synchronizations.add(synchronization);
}
public void enlistConnection(Connection connection, ConnectionProvider connectionProvider) {
if (this.connection != null) {
throw new IllegalStateException("Connection already registered");
}
this.connection = connection;
this.connectionProvider = connectionProvider;
}
public Connection getEnlistedConnection() {
return connection;
}
public boolean enlistResource(XAResource xaResource) throws RollbackException, IllegalStateException,
SystemException {
enlistedResources.add(new WrappedXaResource(xaResource));
try {
xaResource.start(xid, 0);
} catch (XAException e) {
log.error("Got an exception", e);
throw new SystemException(e.getMessage());
}
return true;
}
public boolean delistResource(XAResource xaResource, int i) throws IllegalStateException, SystemException {
throw new SystemException("not supported");
}
public Collection<XAResource> getEnlistedResources() {
return enlistedResources;
}
private boolean runXaResourcePrepare() throws SystemException {
Collection<XAResource> resources = getEnlistedResources();
for (XAResource res : resources) {
try {
res.prepare(xid);
} catch (XAException e) {
log.trace("The resource wants to rollback!", e);
return false;
} catch (Throwable th) {
log.error("Unexpected error from resource manager!", th);
throw new SystemException(th.getMessage());
}
}
return true;
}
private void runXaResourceRollback() {
Collection<XAResource> resources = getEnlistedResources();
for (XAResource res : resources) {
try {
res.rollback(xid);
} catch (XAException e) {
log.warn("Error while rolling back",e);
}
}
}
private boolean runXaResourceCommitTx() throws HeuristicMixedException {
Collection<XAResource> resources = getEnlistedResources();
for (XAResource res : resources) {
try {
res.commit(xid, false);//todo we only support one phase commit for now, change this!!!
} catch (XAException e) {
log.warn("exception while committing",e);
throw new HeuristicMixedException(e.getMessage());
}
}
return true;
}
private static class XaResourceCapableTransactionXid implements Xid {
private static AtomicInteger txIdCounter = new AtomicInteger(0);
private int id = txIdCounter.incrementAndGet();
public int getFormatId() {
return id;
}
public byte[] getGlobalTransactionId() {
throw new IllegalStateException("TODO - please implement me!!!"); //todo implement!!!
}
public byte[] getBranchQualifier() {
throw new IllegalStateException("TODO - please implement me!!!"); //todo implement!!!
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"id=" + id +
'}';
}
}
private class WrappedXaResource implements XAResource {
private final XAResource xaResource;
private int prepareResult;
public WrappedXaResource(XAResource xaResource) {
this.xaResource = xaResource;
}
@Override
public void commit(Xid xid, boolean b) throws XAException {
// Commit only if not read only.
if (prepareResult != XAResource.XA_RDONLY)
xaResource.commit(xid, b);
else
log.tracef("Not committing {0} due to readonly.", xid);
}
@Override
public void end(Xid xid, int i) throws XAException {
xaResource.end(xid, i);
}
@Override
public void forget(Xid xid) throws XAException {
xaResource.forget(xid);
}
@Override
public int getTransactionTimeout() throws XAException {
return xaResource.getTransactionTimeout();
}
@Override
public boolean isSameRM(XAResource xaResource) throws XAException {
return xaResource.isSameRM(xaResource);
}
@Override
public int prepare(Xid xid) throws XAException {
prepareResult = xaResource.prepare(xid);
return prepareResult;
}
@Override
public Xid[] recover(int i) throws XAException {
return xaResource.recover(i);
}
@Override
public void rollback(Xid xid) throws XAException {
xaResource.rollback(xid);
}
@Override
public boolean setTransactionTimeout(int i) throws XAException {
return xaResource.setTransactionTimeout(i);
}
@Override
public void start(Xid xid, int i) throws XAException {
xaResource.start(xid, i);
}
}
}
| 10,016
| 30.8
| 119
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/tm/NarayanaStandaloneJtaPlatform.java
|
package org.infinispan.test.hibernate.cache.commons.tm;
import org.hibernate.engine.transaction.jta.platform.internal.AbstractJtaPlatform;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatformException;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.UserTransaction;
public class NarayanaStandaloneJtaPlatform extends AbstractJtaPlatform {
public NarayanaStandaloneJtaPlatform() {
}
@Override
protected TransactionManager locateTransactionManager() {
try {
return com.arjuna.ats.jta.TransactionManager.transactionManager();
} catch (Exception e) {
throw new JtaPlatformException("Could not obtain JBoss Transactions transaction manager instance", e);
}
}
@Override
protected UserTransaction locateUserTransaction() {
try {
return com.arjuna.ats.jta.UserTransaction.userTransaction();
} catch (Exception e) {
throw new JtaPlatformException("Could not obtain JBoss Transactions user transaction instance", e);
}
}
}
| 1,060
| 30.205882
| 111
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/tm/JtaPlatformImpl.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.tm;
import org.hibernate.TransactionException;
import org.hibernate.engine.transaction.internal.jta.JtaStatusHelper;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.UserTransaction;
/**
* @author Steve Ebersole
*/
public class JtaPlatformImpl implements JtaPlatform {
@Override
public TransactionManager retrieveTransactionManager(){
return XaTransactionManagerImpl.getInstance();
}
@Override
public UserTransaction retrieveUserTransaction() {
throw new TransactionException( "UserTransaction not used in these tests" );
}
@Override
public Object getTransactionIdentifier(Transaction transaction) {
return transaction;
}
@Override
public boolean canRegisterSynchronization() {
return JtaStatusHelper.isActive( XaTransactionManagerImpl.getInstance() );
}
@Override
public void registerSynchronization(Synchronization synchronization) {
try {
XaTransactionManagerImpl.getInstance().getTransaction().registerSynchronization( synchronization );
}
catch (Exception e) {
throw new TransactionException( "Could not obtain transaction from TM" );
}
}
@Override
public int getCurrentStatus() throws SystemException {
return JtaStatusHelper.getStatus( XaTransactionManagerImpl.getInstance() );
}
}
| 1,753
| 29.241379
| 102
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/tm/JBossStandaloneJtaExampleTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.tm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NameNotFoundException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.stat.Statistics;
import org.hibernate.testing.ServiceRegistryBuilder;
import org.hibernate.testing.jta.JtaAwareConnectionProviderImpl;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Item;
import org.infinispan.test.hibernate.cache.commons.util.InfinispanTestingSetup;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup;
import org.jboss.util.naming.NonSerializableFactory;
import org.jnp.interfaces.NamingContext;
import org.jnp.server.Main;
import org.jnp.server.NamingServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import jakarta.transaction.Status;
import jakarta.transaction.UserTransaction;
/**
* This is an example test based on http://community.jboss.org/docs/DOC-14617 that shows how to interact with
* Hibernate configured with Infinispan second level cache provider using JTA transactions.
*
* In this test, an XADataSource wrapper is in use where we have associated our transaction manager to it so that
* commits/rollbacks are propagated to the database as well.
*
* @author Galder Zamarreño
* @since 3.5
*/
public class JBossStandaloneJtaExampleTest {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(JBossStandaloneJtaExampleTest.class);
private static final JBossStandaloneJTAManagerLookup lookup = new JBossStandaloneJTAManagerLookup();
Context ctx;
Main jndiServer;
private ServiceRegistry serviceRegistry;
@Rule
public final InfinispanTestingSetup infinispanTestIdentifier = new InfinispanTestingSetup();
@Before
public void setUp() throws Exception {
jndiServer = startJndiServer();
ctx = createJndiContext();
// Inject configuration to initialise transaction manager from config classloader
lookup.init(new GlobalConfigurationBuilder().build());
bindTransactionManager();
bindUserTransaction();
}
@After
public void tearDown() throws Exception {
try {
unbind("UserTransaction", ctx);
unbind("java:/TransactionManager", ctx);
ctx.close();
jndiServer.stop();
}
finally {
if ( serviceRegistry != null ) {
ServiceRegistryBuilder.destroy( serviceRegistry );
}
}
}
@Test
public void testPersistAndLoadUnderJta() throws Exception {
Item item;
SessionFactory sessionFactory = buildSessionFactory();
try {
UserTransaction ut = (UserTransaction) ctx.lookup("UserTransaction");
ut.begin();
try {
Session session = sessionFactory.openSession();
assertEquals(TransactionStatus.ACTIVE, session.getTransaction().getStatus());
item = new Item("anItem", "An item owned by someone");
session.persist(item);
// IMO the flush should not be necessary, but session.close() does not flush
// and the item is not persisted.
session.flush();
session.close();
} catch(Exception e) {
ut.setRollbackOnly();
throw e;
} finally {
if (ut.getStatus() == Status.STATUS_ACTIVE)
ut.commit();
else
ut.rollback();
}
ut = (UserTransaction) ctx.lookup("UserTransaction");
ut.begin();
try {
Session session = sessionFactory.openSession();
assertEquals(TransactionStatus.ACTIVE, session.getTransaction().getStatus());
Item found = (Item) session.load(Item.class, item.getId());
Statistics stats = session.getSessionFactory().getStatistics();
log.info(stats.toString());
assertEquals(item.getDescription(), found.getDescription());
assertEquals(0, stats.getSecondLevelCacheMissCount());
assertEquals(1, stats.getSecondLevelCacheHitCount());
session.delete(found);
// IMO the flush should not be necessary, but session.close() does not flush
// and the item is not deleted.
session.flush();
session.close();
} catch(Exception e) {
ut.setRollbackOnly();
throw e;
} finally {
if (ut.getStatus() == Status.STATUS_ACTIVE)
ut.commit();
else
ut.rollback();
}
ut = (UserTransaction) ctx.lookup("UserTransaction");
ut.begin();
try {
Session session = sessionFactory.openSession();
assertEquals(TransactionStatus.ACTIVE, session.getTransaction().getStatus());
assertNull(session.get(Item.class, item.getId()));
session.close();
} catch(Exception e) {
ut.setRollbackOnly();
throw e;
} finally {
if (ut.getStatus() == Status.STATUS_ACTIVE)
ut.commit();
else
ut.rollback();
}
} finally {
if (sessionFactory != null)
sessionFactory.close();
}
}
private Main startJndiServer() throws Exception {
// Create an in-memory jndi
NamingServer namingServer = new NamingServer();
NamingContext.setLocal(namingServer);
Main namingMain = new Main();
namingMain.setInstallGlobalService(true);
namingMain.setPort( -1 );
namingMain.start();
return namingMain;
}
private Context createJndiContext() throws Exception {
Properties props = new Properties();
props.put( Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory" );
props.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
return new InitialContext(props);
}
private void bindTransactionManager() throws Exception {
// as JBossTransactionManagerLookup extends JNDITransactionManagerLookup we must also register the TransactionManager
bind("java:/TransactionManager", lookup.getTransactionManager(), lookup.getTransactionManager().getClass(), ctx);
}
private void bindUserTransaction() throws Exception {
// also the UserTransaction must be registered on jndi: org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory#getUserTransaction() requires this
bind( "UserTransaction", lookup.getUserTransaction(), lookup.getUserTransaction().getClass(), ctx );
}
/**
* Helper method that binds the a non serializable object to the JNDI tree.
*
* @param jndiName Name under which the object must be bound
* @param who Object to bind in JNDI
* @param classType Class type under which should appear the bound object
* @param ctx Naming context under which we bind the object
* @throws Exception Thrown if a naming exception occurs during binding
*/
private void bind(String jndiName, Object who, Class classType, Context ctx) throws Exception {
// Ah ! This service isn't serializable, so we use a helper class
NonSerializableFactory.bind(jndiName, who);
Name n = ctx.getNameParser("").parse(jndiName);
while (n.size() > 1) {
String ctxName = n.get(0);
try {
ctx = (Context) ctx.lookup(ctxName);
} catch (NameNotFoundException e) {
log.debug("Creating subcontext:" + ctxName);
ctx = ctx.createSubcontext(ctxName);
}
n = n.getSuffix(1);
}
// The helper class NonSerializableFactory uses address type nns, we go on to
// use the helper class to bind the service object in JNDI
StringRefAddr addr = new StringRefAddr("nns", jndiName);
Reference ref = new Reference(classType.getName(), addr, NonSerializableFactory.class.getName(), null);
ctx.rebind(n.get(0), ref);
}
private void unbind(String jndiName, Context ctx) throws Exception {
NonSerializableFactory.unbind(jndiName);
ctx.unbind(jndiName);
}
private SessionFactory buildSessionFactory() {
// Extra options located in src/test/resources/hibernate.properties
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
.applySetting( Environment.DIALECT, "HSQL" )
.applySetting( Environment.HBM2DDL_AUTO, "create-drop" )
.applySetting( Environment.CONNECTION_PROVIDER, JtaAwareConnectionProviderImpl.class.getName() )
.applySetting( Environment.JNDI_CLASS, "org.jnp.interfaces.NamingContextFactory" )
.applySetting( Environment.TRANSACTION_COORDINATOR_STRATEGY, JtaTransactionCoordinatorBuilderImpl.class.getName() )
.applySetting( Environment.CURRENT_SESSION_CONTEXT_CLASS, "jta" )
.applySetting( Environment.USE_SECOND_LEVEL_CACHE, "true" )
.applySetting( Environment.USE_QUERY_CACHE, "true" )
.applySetting( Environment.JTA_PLATFORM, new NarayanaStandaloneJtaPlatform() )
.applySetting( Environment.CACHE_REGION_FACTORY, TestRegionFactoryProvider.load().getRegionFactoryClass().getName() );
StandardServiceRegistry serviceRegistry = ssrb.build();
MetadataSources metadataSources = new MetadataSources( serviceRegistry );
metadataSources.addResource("org/infinispan/test/hibernate/cache/commons/functional/entities/Item.hbm.xml");
Metadata metadata = metadataSources.buildMetadata();
for ( PersistentClass entityBinding : metadata.getEntityBindings() ) {
if ( entityBinding instanceof RootClass ) {
RootClass rootClass = (RootClass) entityBinding;
rootClass.setCacheConcurrencyStrategy( "transactional" );
rootClass.setCachingExplicitlyRequested(true);
}
}
for ( Collection collectionBinding : metadata.getCollectionBindings() ) {
collectionBinding.setCacheConcurrencyStrategy( "transactional" );
}
return metadata.buildSessionFactory();
}
}
| 10,521
| 37.683824
| 160
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/tm/XaTransactionManagerImpl.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.tm;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.InvalidTransactionException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
/**
* XaResourceCapableTransactionManagerImpl.
*
* @author Galder Zamarreño
* @since 3.5
*/
public class XaTransactionManagerImpl implements TransactionManager {
private static final XaTransactionManagerImpl INSTANCE = new XaTransactionManagerImpl();
private final ThreadLocal<XaTransactionImpl> currentTransaction = new ThreadLocal<>();
public static XaTransactionManagerImpl getInstance() {
return INSTANCE;
}
public int getStatus() throws SystemException {
XaTransactionImpl currentTransaction = this.currentTransaction.get();
return currentTransaction == null ? Status.STATUS_NO_TRANSACTION : currentTransaction.getStatus();
}
public Transaction getTransaction() throws SystemException {
return currentTransaction.get();
}
public XaTransactionImpl getCurrentTransaction() {
return currentTransaction.get();
}
public void begin() throws NotSupportedException, SystemException {
if (currentTransaction.get() != null) throw new IllegalStateException("Transaction already started.");
currentTransaction.set(new XaTransactionImpl(this));
}
public Transaction suspend() throws SystemException {
Transaction suspended = currentTransaction.get();
currentTransaction.remove();
return suspended;
}
public void resume(Transaction transaction) throws InvalidTransactionException, IllegalStateException,
SystemException {
currentTransaction.set((XaTransactionImpl) transaction);
}
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException,
SecurityException, IllegalStateException, SystemException {
XaTransactionImpl currentTransaction = this.currentTransaction.get();
if (currentTransaction == null) {
throw new IllegalStateException("no current transaction to commit");
}
currentTransaction.commit();
}
public void rollback() throws IllegalStateException, SecurityException, SystemException {
XaTransactionImpl currentTransaction = this.currentTransaction.get();
if (currentTransaction == null) {
throw new IllegalStateException("no current transaction");
}
currentTransaction.rollback();
}
public void setRollbackOnly() throws IllegalStateException, SystemException {
XaTransactionImpl currentTransaction = this.currentTransaction.get();
if (currentTransaction == null) {
throw new IllegalStateException("no current transaction");
}
currentTransaction.setRollbackOnly();
}
public void setTransactionTimeout(int i) throws SystemException {
}
void endCurrent(Transaction transaction) {
currentTransaction.remove();
}
}
| 3,462
| 36.236559
| 108
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/tm/XaConnectionProvider.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.tm;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.service.UnknownUnwrapTypeException;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.Stoppable;
import org.hibernate.testing.env.ConnectionProviderBuilder;
/**
* XaConnectionProvider.
*
* Note: Does not implement {@link Stoppable} because we don't want to stop the global provider
* cached in {@link #DEFAULT_CONNECTION_PROVIDER}.
*
* @author Galder Zamarreño
* @since 3.5
*/
public class XaConnectionProvider implements ConnectionProvider {
private final static ConnectionProvider DEFAULT_CONNECTION_PROVIDER = ConnectionProviderBuilder.buildConnectionProvider();
private final ConnectionProvider actualConnectionProvider;
private boolean isTransactional;
public XaConnectionProvider() {
this(DEFAULT_CONNECTION_PROVIDER);
}
public XaConnectionProvider(ConnectionProvider connectionProvider) {
this.actualConnectionProvider = connectionProvider;
}
public ConnectionProvider getActualConnectionProvider() {
return actualConnectionProvider;
}
@Override
public boolean isUnwrappableAs(Class unwrapType) {
return XaConnectionProvider.class.isAssignableFrom( unwrapType ) ||
ConnectionProvider.class.equals( unwrapType ) ||
actualConnectionProvider.getClass().isAssignableFrom( unwrapType );
}
@Override
@SuppressWarnings( {"unchecked"})
public <T> T unwrap(Class<T> unwrapType) {
if ( XaConnectionProvider.class.isAssignableFrom( unwrapType ) ) {
return (T) this;
}
else if ( ConnectionProvider.class.isAssignableFrom( unwrapType ) ||
actualConnectionProvider.getClass().isAssignableFrom( unwrapType ) ) {
return (T) getActualConnectionProvider();
}
else {
throw new UnknownUnwrapTypeException( unwrapType );
}
}
public void configure(Properties props) throws HibernateException {
}
public Connection getConnection() throws SQLException {
XaTransactionImpl currentTransaction = XaTransactionManagerImpl.getInstance().getCurrentTransaction();
if ( currentTransaction == null ) {
isTransactional = false;
return actualConnectionProvider.getConnection();
}
else {
isTransactional = true;
Connection connection = currentTransaction.getEnlistedConnection();
if ( connection == null ) {
connection = actualConnectionProvider.getConnection();
currentTransaction.enlistConnection( connection, actualConnectionProvider );
}
return connection;
}
}
public void closeConnection(Connection conn) throws SQLException {
if ( !isTransactional ) {
actualConnectionProvider.closeConnection(conn);
}
}
public void close() throws HibernateException {
if ( actualConnectionProvider instanceof Stoppable ) {
((Stoppable) actualConnectionProvider).stop();
}
}
public boolean supportsAggressiveRelease() {
return true;
}
}
| 3,234
| 30.407767
| 123
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/query/QueryStalenessTest.java
|
package org.infinispan.test.hibernate.cache.commons.query;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.CustomRunner;
import org.infinispan.commons.test.TestResourceTracker;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Person;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.util.ControlledTimeService;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(CustomRunner.class)
public class QueryStalenessTest {
ControlledTimeService timeService = new ControlledTimeService();
SessionFactory sf1, sf2;
@BeforeClassOnce
public void init() {
TestResourceTracker.testStarted(getClass().getSimpleName());
sf1 = createSessionFactory();
sf2 = createSessionFactory();
}
@AfterClassOnce
public void destroy() {
sf1.close();
sf2.close();
TestResourceTracker.testFinished(getClass().getSimpleName());
}
public SessionFactory createSessionFactory() {
Configuration configuration = new Configuration()
.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true")
.setProperty(Environment.USE_QUERY_CACHE, "true")
.setProperty(Environment.CACHE_REGION_FACTORY, TestRegionFactoryProvider.load().getRegionFactoryClass().getName())
.setProperty(Environment.DEFAULT_CACHE_CONCURRENCY_STRATEGY, "transactional")
.setProperty("hibernate.allow_update_outside_transaction", "true") // only applies in 5.2
.setProperty("javax.persistence.sharedCache.mode", "ALL")
.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
Properties testProperties = new Properties();
testProperties.put(TestRegionFactory.TIME_SERVICE, timeService);
configuration.addProperties(testProperties);
configuration.addAnnotatedClass(Person.class);
return configuration.buildSessionFactory();
}
// TEST disabled until https://hibernate.atlassian.net/browse/HHH-15150 can be resolved
@Test
@TestForIssue(jiraKey = "HHH-10677")
public void testLocalQueryInvalidatedImmediatelly() {
// Session s1 = sf1.openSession();
// Person person = new Person("John", "Smith", 29);
// s1.persist(person);
// s1.flush();
// s1.close();
//
// InfinispanBaseRegion timestampsRegion = TestRegionFactoryProvider.load().findTimestampsRegion((CacheImplementor) sf1.getCache());
// DistributionInfo distribution = timestampsRegion.getCache().getDistributionManager().getCacheTopology().getDistribution(Person.class.getSimpleName());
// SessionFactory qsf = distribution.isPrimary() ? sf2 : sf1;
//
// // The initial insert invalidates the queries for 60s to the future
// timeService.advance(60001);
//
// Session s2 = qsf.openSession();
//
// HibernateCriteriaBuilder cb = s2.getCriteriaBuilder();
// CriteriaQuery<Person> criteria = cb.createQuery(Person.class);
// Root<Person> root = criteria.from(Person.class);
// criteria.where(cb.le(root.get(Person_.age), 29));
//
// List<Person> list1 = s2.createQuery(criteria)
// .setHint(QueryHints.HINT_CACHEABLE, "true")
// .getResultList();
//
// assertEquals(1, list1.size());
// s2.close();
//
// Session s3 = qsf.openSession();
// Person p2 = s3.load(Person.class, person.getName());
// p2.setAge(30);
// s3.persist(p2);
// s3.flush();
// List<Person> list2 = s3.createQuery(criteria)
// .setHint("org.hibernate.cacheable", "true")
// .getResultList();
// assertEquals(0, list2.size());
// s3.close();
}
}
| 4,001
| 39.836735
| 158
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/query/QueryRegionImplTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.query;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.infinispan.commons.test.categories.Smoke;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.hibernate.testing.TestForIssue;
import org.infinispan.test.hibernate.cache.commons.AbstractGeneralDataRegionTest;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.CacheTestUtil;
import org.junit.Test;
import junit.framework.AssertionFailedError;
import org.infinispan.AdvancedCache;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited;
import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent;
import org.infinispan.util.concurrent.IsolationLevel;
import org.jboss.logging.Logger;
import org.junit.experimental.categories.Category;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Tests of QueryResultRegionImpl.
*
* @author Galder Zamarreño
* @since 3.5
*/
@Category(Smoke.class)
public class QueryRegionImplTest extends AbstractGeneralDataRegionTest {
private static final Logger log = Logger.getLogger( QueryRegionImplTest.class );
@Override
protected InfinispanBaseRegion createRegion(
TestRegionFactory regionFactory,
String regionName) {
return regionFactory.buildQueryResultsRegion(regionName);
}
@Override
protected StandardServiceRegistryBuilder createStandardServiceRegistryBuilder() {
return CacheTestUtil.buildCustomQueryCacheStandardServiceRegistryBuilder( REGION_PREFIX, "replicated-query", jtaPlatform );
}
private interface RegionConsumer {
void accept(SessionFactory sessionFactory, InfinispanBaseRegion region) throws Exception;
}
private void withQueryRegion(RegionConsumer callable) throws Exception {
withSessionFactoriesAndRegions(1, (sessionFactories, regions) -> callable.accept(sessionFactories.get(0), regions.get(0)));
}
@Test
public void testPutDoesNotBlockGet() throws Exception {
withQueryRegion((sessionFactory, region) -> {
withSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).put(session, KEY, VALUE1));
assertEquals(VALUE1, callWithSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY)));
final CountDownLatch readerLatch = new CountDownLatch(1);
final CountDownLatch writerLatch = new CountDownLatch(1);
final CountDownLatch completionLatch = new CountDownLatch(1);
final ExceptionHolder holder = new ExceptionHolder();
Thread reader = new Thread() {
@Override
public void run() {
try {
assertNotEquals(VALUE2, callWithSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY)));
} catch (AssertionFailedError e) {
holder.addAssertionFailure(e);
} catch (Exception e) {
holder.addException(e);
} finally {
readerLatch.countDown();
}
}
};
Thread writer = new Thread() {
@Override
public void run() {
try {
withSession(sessionFactory, session -> {
TEST_SESSION_ACCESS.fromRegion(region).put(session, KEY, VALUE2);
writerLatch.await();
});
} catch (Exception e) {
holder.addException(e);
} finally {
completionLatch.countDown();
}
}
};
reader.setDaemon(true);
writer.setDaemon(true);
writer.start();
assertFalse("Writer is blocking", completionLatch.await(100, TimeUnit.MILLISECONDS));
// Start the reader
reader.start();
assertTrue("Reader finished promptly", readerLatch.await(100, TimeUnit.MILLISECONDS));
writerLatch.countDown();
assertTrue("Reader finished promptly", completionLatch.await(100, TimeUnit.MILLISECONDS));
assertEquals(VALUE2, callWithSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY)));
});
}
@Test
public void testGetDoesNotBlockPut() throws Exception {
withQueryRegion((sessionFactory, region) -> {
withSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).put( session, KEY, VALUE1 ));
assertEquals(VALUE1, callWithSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).get( session, KEY )));
final AdvancedCache cache = region.getCache();
final CountDownLatch blockerLatch = new CountDownLatch( 1 );
final CountDownLatch writerLatch = new CountDownLatch( 1 );
final CountDownLatch completionLatch = new CountDownLatch( 1 );
final ExceptionHolder holder = new ExceptionHolder();
Thread reader = new Thread() {
@Override
public void run() {
GetBlocker blocker = new GetBlocker( blockerLatch, KEY );
try {
cache.addListener( blocker );
withSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY ));
}
catch (Exception e) {
holder.addException(e);
}
finally {
cache.removeListener( blocker );
}
}
};
Thread writer = new Thread() {
@Override
public void run() {
try {
writerLatch.await();
withSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).put( session, KEY, VALUE2 ));
}
catch (Exception e) {
holder.addException(e);
}
finally {
completionLatch.countDown();
}
}
};
reader.setDaemon( true );
writer.setDaemon( true );
boolean unblocked = false;
try {
reader.start();
writer.start();
assertFalse( "Reader is blocking", completionLatch.await( 100, TimeUnit.MILLISECONDS ) );
// Start the writer
writerLatch.countDown();
assertTrue( "Writer finished promptly", completionLatch.await( 100, TimeUnit.MILLISECONDS ) );
blockerLatch.countDown();
unblocked = true;
if ( IsolationLevel.REPEATABLE_READ.equals( cache.getCacheConfiguration().locking().isolationLevel() ) ) {
assertEquals( VALUE1, callWithSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).get( session, KEY )) );
}
else {
assertEquals( VALUE2, callWithSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).get( session, KEY )) );
}
holder.checkExceptions();
}
finally {
if ( !unblocked ) {
blockerLatch.countDown();
}
}
});
}
protected interface SessionConsumer {
void accept(Object session) throws Exception;
}
protected interface SessionCallable<T> {
T call(Object session) throws Exception;
}
protected <T> T callWithSession(SessionFactory sessionFactory, SessionCallable<T> callable) throws Exception {
Session session = sessionFactory.openSession();
Transaction tx = session.getTransaction();
tx.begin();
try {
T retval = callable.call(session);
tx.commit();
return retval;
} catch (Exception e) {
tx.rollback();
throw e;
} finally {
session.close();
}
}
protected void withSession(SessionFactory sessionFactory, SessionConsumer consumer) throws Exception {
callWithSession(sessionFactory, session -> { consumer.accept(session); return null;} );
}
@Test
@TestForIssue(jiraKey = "HHH-7898")
public void testPutDuringPut() throws Exception {
withQueryRegion((sessionFactory, region) -> {
withSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).put(session, KEY, VALUE1));
assertEquals(VALUE1, callWithSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY) ));
final AdvancedCache cache = region.getCache();
CountDownLatch blockerLatch = new CountDownLatch(1);
CountDownLatch triggerLatch = new CountDownLatch(1);
ExceptionHolder holder = new ExceptionHolder();
Thread blocking = new Thread() {
@Override
public void run() {
PutBlocker blocker = null;
try {
blocker = new PutBlocker(blockerLatch, triggerLatch, KEY);
cache.addListener(blocker);
withSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).put(session, KEY, VALUE2));
} catch (Exception e) {
holder.addException(e);
} finally {
if (blocker != null) {
cache.removeListener(blocker);
}
if (triggerLatch.getCount() > 0) {
triggerLatch.countDown();
}
}
}
};
Thread blocked = new Thread() {
@Override
public void run() {
try {
triggerLatch.await();
// this should silently fail
withSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).put(session, KEY, VALUE3));
} catch (Exception e) {
holder.addException(e);
}
}
};
blocking.setName("blocking-thread");
blocking.start();
blocked.setName("blocked-thread");
blocked.start();
blocked.join();
blockerLatch.countDown();
blocking.join();
holder.checkExceptions();
assertEquals(VALUE2, callWithSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY)));
});
}
@Test
public void testQueryUpdate() throws Exception {
withQueryRegion((sessionFactory, region) -> {
ExceptionHolder holder = new ExceptionHolder();
CyclicBarrier barrier = new CyclicBarrier(2);
withSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).put(session, KEY, VALUE1));
Thread updater = new Thread() {
@Override
public void run() {
try {
withSession(sessionFactory, (session) -> {
assertEquals(VALUE1, TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY));
TEST_SESSION_ACCESS.fromRegion(region).put(session, KEY, VALUE2);
assertEquals(VALUE2, TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY));
barrier.await(5, TimeUnit.SECONDS);
barrier.await(5, TimeUnit.SECONDS);
TEST_SESSION_ACCESS.fromRegion(region).put(session, KEY, VALUE3);
assertEquals(VALUE3, TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY));
barrier.await(5, TimeUnit.SECONDS);
barrier.await(5, TimeUnit.SECONDS);
});
} catch (AssertionFailedError e) {
holder.addAssertionFailure(e);
barrier.reset();
} catch (Exception e) {
holder.addException(e);
barrier.reset();
}
}
};
Thread reader = new Thread() {
@Override
public void run() {
try {
withSession(sessionFactory, (session) -> {
assertEquals(VALUE1, TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY));
barrier.await(5, TimeUnit.SECONDS);
assertEquals(VALUE1, TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY));
barrier.await(5, TimeUnit.SECONDS);
barrier.await(5, TimeUnit.SECONDS);
assertEquals(VALUE1, TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY));
barrier.await(5, TimeUnit.SECONDS);
});
} catch (AssertionFailedError e) {
holder.addAssertionFailure(e);
barrier.reset();
} catch (Exception e) {
holder.addException(e);
barrier.reset();
}
}
};
updater.start();
reader.start();
updater.join();
reader.join();
holder.checkExceptions();
assertEquals(VALUE3, callWithSession(sessionFactory, session -> TEST_SESSION_ACCESS.fromRegion(region).get(session, KEY)));
});
}
@Test
@TestForIssue(jiraKey = "HHH-10163")
public void testEvictAll() throws Exception {
withQueryRegion((sessionFactory, region) -> {
withSession(sessionFactory, s -> TEST_SESSION_ACCESS.fromRegion(region).put(s, KEY, VALUE1));
withSession(sessionFactory, s -> assertEquals(VALUE1, TEST_SESSION_ACCESS.fromRegion(region).get(s, KEY)));
TEST_SESSION_ACCESS.fromRegion(region).evictAll();
withSession(sessionFactory, s -> assertNull(TEST_SESSION_ACCESS.fromRegion(region).get(s, KEY)));
assertTrue(region.getCache().isEmpty());
});
}
@Listener
public class GetBlocker {
private final CountDownLatch latch;
private final Object key;
GetBlocker(CountDownLatch latch, Object key) {
this.latch = latch;
this.key = key;
}
@CacheEntryVisited
public void nodeVisisted(CacheEntryVisitedEvent event) {
if ( event.isPre() && event.getKey().equals( key ) ) {
try {
latch.await();
}
catch (InterruptedException e) {
log.error( "Interrupted waiting for latch", e );
}
}
}
}
@Listener
public class PutBlocker {
private final CountDownLatch blockLatch, triggerLatch;
private final Object key;
private boolean enabled = true;
PutBlocker(CountDownLatch blockLatch, CountDownLatch triggerLatch, Object key) {
this.blockLatch = blockLatch;
this.triggerLatch = triggerLatch;
this.key = key;
}
@CacheEntryModified
public void nodeVisisted(CacheEntryModifiedEvent event) {
// we need isPre since lock is acquired in the commit phase
if ( !event.isPre() && event.getKey().equals( key ) ) {
try {
synchronized (this) {
if (enabled) {
triggerLatch.countDown();
enabled = false;
blockLatch.await();
}
}
}
catch (InterruptedException e) {
log.error( "Interrupted waiting for latch", e );
}
}
}
}
private class ExceptionHolder {
private final List<Exception> exceptions = Collections.synchronizedList(new ArrayList<>());
private final List<AssertionFailedError> assertionFailures = Collections.synchronizedList(new ArrayList<>());
public void addException(Exception e) {
exceptions.add(e);
}
public void addAssertionFailure(AssertionFailedError e) {
assertionFailures.add(e);
}
public void checkExceptions() throws Exception {
for (AssertionFailedError a : assertionFailures) {
throw a;
}
for (Exception e : exceptions) {
throw e;
}
}
}
}
| 14,620
| 30.993435
| 132
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/NonTxQueryTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.hibernate.stat.Statistics;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Person;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.util.ControlledTimeService;
import org.junit.Test;
public class NonTxQueryTest extends SingleNodeTest {
protected static final ControlledTimeService TIME_SERVICE = new ControlledTimeService();
@Override
public List<Object[]> getParameters() {
return getParameters(true, true, true, true, true);
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[]{Person.class};
}
@Override
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(TestRegionFactory.TIME_SERVICE, TIME_SERVICE);
}
@Test
public void testNonTransactionalQuery() throws Exception {
Person john = new Person("John", "Black", 26);
Person peter = new Person("Peter", "White", 32);
withTxSession(s -> {
s.persist(john);
s.persist(peter);
});
// Delay added to guarantee that query cache results won't be considered
// as not up to date due to persist session and query results from first
// query happening simultaneously.
TIME_SERVICE.advance(60001);
Statistics statistics = sessionFactory().getStatistics();
statistics.clear();
withSession(s -> {
queryPersons(s);
assertEquals(1, statistics.getQueryCacheMissCount());
assertEquals(1, statistics.getQueryCachePutCount());
});
statistics.clear();
withSession(s -> {
queryPersons(s);
// assertEquals(2, statistics.getSecondLevelCacheHitCount());
assertEquals(1, statistics.getQueryCacheHitCount());
});
}
public void queryPersons(Session s) {
Query<Person> query = s.createQuery("from Person")
.setCacheable(true);
List<Person> result = query.list();
assertEquals(2, result.size());
}
}
| 2,254
| 28.285714
| 91
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/SingleNodeTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.concurrent.Callable;
import org.hibernate.Session;
import org.hibernate.SessionBuilder;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.infinispan.hibernate.cache.commons.util.Caches;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import org.infinispan.test.hibernate.cache.commons.util.TxUtil;
import jakarta.transaction.TransactionManager;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public abstract class SingleNodeTest extends AbstractFunctionalTest {
protected static final TestSessionAccess TEST_SESSION_ACCESS = TestSessionAccess.findTestSessionAccess();
@Override
protected void afterSessionFactoryBuilt(SessionFactoryImplementor sessionFactory) {
super.afterSessionFactoryBuilt(sessionFactory);
JtaPlatform jtaPlatform = sessionFactory().getServiceRegistry().getService(JtaPlatform.class);
assertNotNull(jtaPlatform);
assertEquals(jtaPlatformClass, jtaPlatform.getClass());
}
protected void withTxSession(TxUtil.ThrowingConsumer<Session, Exception> consumer) throws Exception {
withTxSession(sessionFactory().withOptions(), consumer);
}
protected void withTxSession(SessionBuilder sessionBuilder, TxUtil.ThrowingConsumer<Session, Exception> consumer) throws Exception {
JtaPlatform jtaPlatform = useJta ? sessionFactory().getServiceRegistry().getService(JtaPlatform.class) : null;
TxUtil.withTxSession(jtaPlatform, sessionBuilder, consumer);
}
protected <T> T withTxSessionApply(TxUtil.ThrowingFunction<Session, T, Exception> function) throws Exception {
JtaPlatform jtaPlatform = useJta ? sessionFactory().getServiceRegistry().getService(JtaPlatform.class) : null;
return TxUtil.withTxSessionApply(jtaPlatform, sessionFactory().withOptions(), function);
}
protected <T> T withTx(Callable<T> callable) throws Exception {
if (useJta) {
TransactionManager tm = sessionFactory().getServiceRegistry().getService(JtaPlatform.class).retrieveTransactionManager();
return Caches.withinTx(tm, () -> callable.call());
} else {
return callable.call();
}
}
public <E extends Throwable> void withSession(TxUtil.ThrowingConsumer<Session, E> consumer) throws E {
TxUtil.withSession(sessionFactory().withOptions(), consumer);
}
public <R, E extends Throwable> R withSessionApply(TxUtil.ThrowingFunction<Session, R, E> function) throws E {
return TxUtil.withSessionApply(sessionFactory().withOptions(), function);
}
}
| 2,682
| 40.276923
| 133
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/MultiTenancyTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.hibernate.testing.env.ConnectionProviderBuilder;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.context.Flag;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Item;
import org.infinispan.test.hibernate.cache.commons.tm.XaConnectionProvider;
import org.junit.Test;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public class MultiTenancyTest extends SingleNodeTest {
private static final String DB1 = "db1";
private static final String DB2 = "db2";
private final XaConnectionProvider db1
= new XaConnectionProvider(ConnectionProviderBuilder.buildConnectionProvider(DB1));
private final XaConnectionProvider db2
= new XaConnectionProvider(ConnectionProviderBuilder.buildConnectionProvider(DB2));
@Override
public List<Object[]> getParameters() {
return Collections.singletonList(READ_ONLY_INVALIDATION);
}
@Override
protected void addSettings(Map settings) {
super.addSettings( settings );
settings.put( Environment.CACHE_KEYS_FACTORY, DefaultCacheKeysFactory.SHORT_NAME );
}
@Override
protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) {
super.configureStandardServiceRegistryBuilder(ssrb);
ssrb.addService(MultiTenantConnectionProvider.class, new AbstractMultiTenantConnectionProvider() {
@Override
protected ConnectionProvider getAnyConnectionProvider() {
return db1;
}
@Override
protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
if (DB1.equals(tenantIdentifier)) return db1;
if (DB2.equals(tenantIdentifier)) return db2;
throw new IllegalArgumentException();
}
});
}
@Override
protected void configureSessionFactoryBuilder(SessionFactoryBuilder sfb) {
super.configureSessionFactoryBuilder(sfb);
sfb.applyMultiTenancy(true);
}
@Override
protected void cleanupTest() throws Exception {
db1.close();
db2.close();
}
@Test
public void testMultiTenancy() throws Exception {
final Item item = new Item("my item", "description" );
withTxSession(sessionFactory().withOptions().tenantIdentifier(DB1), s -> s.persist(item));
for (int i = 0; i < 5; ++i) { // make sure we get something cached
withTxSession(sessionFactory().withOptions().tenantIdentifier(DB1), s -> {
Item item2 = s.get(Item.class, item.getId());
assertNotNull(item2);
assertEquals(item.getName(), item2.getName());
});
}
// The table ITEMS is not created in DB2 - we would get just an exception
// for (int i = 0; i < 5; ++i) { // make sure we get something cached
// withTx(tm, new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// Session s = sessionFactory().withOptions().tenantIdentifier(DB2).openSession();
// s.getTransaction().begin();
// Item item2 = s.get(Item.class, id);
// s.getTransaction().commit();
// s.close();
// assertNull(item2);
// return null;
// }
// });
// }
InfinispanBaseRegion region = TEST_SESSION_ACCESS.getRegion(sessionFactory(), Item.class.getName());
AdvancedCache localCache = region.getCache().withFlags(Flag.CACHE_MODE_LOCAL);
assertEquals(1, localCache.size());
try (CloseableIterator iterator = localCache.keySet().iterator()) {
assertEquals("CacheKeyImplementation", iterator.next().getClass().getSimpleName());
}
}
}
| 4,418
| 36.769231
| 104
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/CustomConfigTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.testing.TestForIssue;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import org.junit.Test;
import jakarta.persistence.Cacheable;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@TestForIssue(jiraKey = "ISPN-8836")
public class CustomConfigTest extends AbstractFunctionalTest {
public static final TestSessionAccess TEST_SESSION_ACCESS = TestSessionAccess.findTestSessionAccess();
@Override
public List<Object[]> getParameters() {
return Collections.singletonList(READ_WRITE_REPLICATED);
}
@Override
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(AvailableSettings.CACHE_REGION_PREFIX, ""); // force no prefix
settings.put(InfinispanProperties.INFINISPAN_CONFIG_RESOURCE_PROP, "alternative-infinispan-configs.xml");
// myregion does not have this setting, should produce a warning
settings.put(InfinispanProperties.PREFIX + "otherregion" + InfinispanProperties.CONFIG_SUFFIX, "otherregion");
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] { TestEntity.class, OtherTestEntity.class };
}
@Test
public void testCacheWithRegionName() {
InfinispanBaseRegion myregion = TEST_SESSION_ACCESS.getRegion(sessionFactory(), "myregion");
InfinispanBaseRegion otherregion = TEST_SESSION_ACCESS.getRegion(sessionFactory(), "otherregion");
assertEquals("myregion", myregion.getCache().getName());
assertEquals("otherregion", otherregion.getCache().getName());
}
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "myregion")
public class TestEntity {
@Id
long id;
String foobar;
}
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "otherregion")
public class OtherTestEntity {
@Id
long id;
String foobar;
}
}
| 2,425
| 32.694444
| 116
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/AbstractFunctionalTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.infinispan.test.TestingUtil.wrapInboundInvocationHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.function.Predicate;
import org.hibernate.Session;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cache.internal.SimpleCacheKeysFactory;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.mapping.BasicValue;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.RootClass;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl;
import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl;
import org.hibernate.testing.BeforeClassOnce;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.hibernate.testing.junit4.CustomParameterized;
import org.infinispan.AdvancedCache;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.hibernate.cache.commons.util.EndInvalidationCommand;
import org.infinispan.hibernate.cache.commons.util.FutureUpdate;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.hibernate.cache.commons.util.TombstoneUpdate;
import org.infinispan.remoting.inboundhandler.AbstractDelegatingHandler;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler;
import org.infinispan.remoting.inboundhandler.Reply;
import org.infinispan.test.hibernate.cache.commons.tm.JtaPlatformImpl;
import org.infinispan.test.hibernate.cache.commons.tm.XaConnectionProvider;
import org.infinispan.test.hibernate.cache.commons.util.ExpectingInterceptor;
import org.infinispan.test.hibernate.cache.commons.util.InfinispanTestingSetup;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.test.hibernate.cache.commons.util.TxUtil;
import org.junit.After;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
* @author Galder Zamarreño
* @since 3.5
*/
@RunWith(CustomParameterized.class)
public abstract class AbstractFunctionalTest extends BaseNonConfigCoreFunctionalTestCase {
protected static final Object[] TRANSACTIONAL = new Object[]{"transactional", JtaPlatformImpl.class, JtaTransactionCoordinatorBuilderImpl.class, XaConnectionProvider.class, AccessType.TRANSACTIONAL, CacheMode.INVALIDATION_SYNC, false, false };
protected static final Object[] READ_WRITE_INVALIDATION = new Object[]{"read-write", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.READ_WRITE, CacheMode.INVALIDATION_SYNC, false, false };
protected static final Object[] READ_ONLY_INVALIDATION = new Object[]{"read-only", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.READ_ONLY, CacheMode.INVALIDATION_SYNC, false, false };
protected static final Object[] READ_WRITE_REPLICATED = new Object[]{"read-write", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.READ_WRITE, CacheMode.REPL_SYNC, false, false };
protected static final Object[] READ_WRITE_REPLICATED_STATS = new Object[]{"read-write", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.READ_WRITE, CacheMode.REPL_SYNC, false, true };
protected static final Object[] READ_ONLY_REPLICATED = new Object[]{"read-only", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.READ_ONLY, CacheMode.REPL_SYNC, false, false };
protected static final Object[] READ_ONLY_REPLICATED_STATS = new Object[]{"read-only", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.READ_ONLY, CacheMode.REPL_SYNC, false, true };
protected static final Object[] READ_WRITE_DISTRIBUTED = new Object[]{"read-write", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.READ_WRITE, CacheMode.DIST_SYNC, false, false };
protected static final Object[] READ_WRITE_DISTRIBUTED_STATS = new Object[]{"read-write", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.READ_WRITE, CacheMode.DIST_SYNC, false, true };
protected static final Object[] READ_ONLY_DISTRIBUTED = new Object[]{"read-only", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.READ_ONLY, CacheMode.DIST_SYNC, false, false };
protected static final Object[] READ_ONLY_DISTRIBUTED_STATS = new Object[]{"read-only", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.READ_ONLY, CacheMode.DIST_SYNC, false, true };
protected static final Object[] NONSTRICT_REPLICATED = new Object[]{"nonstrict", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.NONSTRICT_READ_WRITE, CacheMode.REPL_SYNC, true, false };
protected static final Object[] NONSTRICT_REPLICATED_STATS = new Object[]{"nonstrict", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.NONSTRICT_READ_WRITE, CacheMode.REPL_SYNC, true, true };
protected static final Object[] NONSTRICT_DISTRIBUTED = new Object[]{"nonstrict", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.NONSTRICT_READ_WRITE, CacheMode.DIST_SYNC, true, false };
protected static final Object[] NONSTRICT_DISTRIBUTED_STATS = new Object[]{"nonstrict", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.NONSTRICT_READ_WRITE, CacheMode.DIST_SYNC, true, true };
// We need to use @ClassRule here since in @BeforeClassOnce startUp we're preparing the session factory,
// constructing CacheManager along - and there we check that the test has the name already set
@ClassRule
public static final InfinispanTestingSetup infinispanTestIdentifier = new InfinispanTestingSetup();
@Parameterized.Parameter(value = 0)
public String mode;
@Parameterized.Parameter(value = 1)
public Class<? extends JtaPlatform> jtaPlatformClass;
@Parameterized.Parameter(value = 2)
public Class<?> transactionCoordinatorBuilderClass;
@Parameterized.Parameter(value = 3)
public Class<? extends ConnectionProvider> connectionProviderClass;
@Parameterized.Parameter(value = 4)
public AccessType accessType;
@Parameterized.Parameter(value = 5)
public CacheMode cacheMode;
@Parameterized.Parameter(value = 6)
public boolean addVersions;
@Parameterized.Parameter(value = 7)
public boolean stats;
protected boolean useJta;
protected List<Runnable> cleanup = new ArrayList<>();
@CustomParameterized.Order(0)
@Parameterized.Parameters(name = "{0}, {5}, stats={7}")
public abstract List<Object[]> getParameters();
public List<Object[]> getParameters(boolean tx, boolean rw, boolean ro, boolean nonstrict, boolean stats) {
ArrayList<Object[]> parameters = new ArrayList<>();
if (tx) {
parameters.add(TRANSACTIONAL);
}
if (rw) {
parameters.add(READ_WRITE_INVALIDATION);
parameters.add(READ_WRITE_REPLICATED);
parameters.add(READ_WRITE_DISTRIBUTED);
if (stats) {
parameters.add(READ_WRITE_REPLICATED_STATS);
parameters.add(READ_WRITE_DISTRIBUTED_STATS);
}
}
if (ro) {
parameters.add(READ_ONLY_INVALIDATION);
parameters.add(READ_ONLY_REPLICATED);
parameters.add(READ_ONLY_DISTRIBUTED);
if (stats) {
parameters.add(READ_ONLY_REPLICATED_STATS);
parameters.add(READ_ONLY_DISTRIBUTED_STATS);
}
}
if (nonstrict) {
parameters.add(NONSTRICT_REPLICATED);
parameters.add(NONSTRICT_DISTRIBUTED);
if (stats) {
parameters.add(NONSTRICT_REPLICATED_STATS);
parameters.add(NONSTRICT_DISTRIBUTED_STATS);
}
}
return parameters;
}
@BeforeClassOnce
public void setUseJta() {
useJta = jtaPlatformClass != NoJtaPlatform.class;
}
@Override
protected void prepareTest() throws Exception {
infinispanTestIdentifier.joinContext();
}
@After
public void runCleanup() {
cleanup.forEach(Runnable::run);
cleanup.clear();
}
@Override
protected String getBaseForMappings() {
return "org/infinispan/test/";
}
@Override
public String[] getMappings() {
return new String[] {
"hibernate/cache/commons/functional/entities/Item.hbm.xml",
"hibernate/cache/commons/functional/entities/Customer.hbm.xml",
"hibernate/cache/commons/functional/entities/Contact.hbm.xml"
};
}
@Override
protected void afterMetadataBuilt(Metadata metadata) {
if (addVersions) {
for (PersistentClass clazz : metadata.getEntityBindings()) {
if (clazz.getVersion() != null) {
continue;
}
try {
clazz.getMappedClass().getMethod("getVersion");
clazz.getMappedClass().getMethod("setVersion", long.class);
} catch (NoSuchMethodException e) {
continue;
}
RootClass rootClazz = clazz.getRootClass();
Property versionProperty = new Property();
versionProperty.setName("version");
SimpleValue value = new BasicValue(((MetadataImplementor) metadata).getTypeConfiguration().getMetadataBuildingContext(), rootClazz.getTable());
value.setTypeName("long");
Column column = new Column();
column.setValue(value);
column.setName("version");
value.addColumn(column);
rootClazz.getTable().addColumn(column);
versionProperty.setValue(value);
rootClazz.setVersion(versionProperty);
rootClazz.addProperty(versionProperty);
}
}
}
@Override
public String getCacheConcurrencyStrategy() {
return accessType.getExternalName();
}
protected boolean getUseQueryCache() {
return true;
}
@Override
@SuppressWarnings("unchecked")
protected void addSettings(Map settings) {
super.addSettings( settings );
settings.put( Environment.USE_SECOND_LEVEL_CACHE, "true" );
settings.put( Environment.GENERATE_STATISTICS, "true" );
settings.put( Environment.USE_QUERY_CACHE, String.valueOf( getUseQueryCache() ) );
settings.put( Environment.CACHE_REGION_FACTORY, TestRegionFactoryProvider.load().getRegionFactoryClass().getName() );
settings.put( Environment.CACHE_KEYS_FACTORY, SimpleCacheKeysFactory.SHORT_NAME );
settings.put( TestRegionFactory.TRANSACTIONAL, useTransactionalCache() );
settings.put( TestRegionFactory.CACHE_MODE, cacheMode);
settings.put( TestRegionFactory.STATS, stats);
settings.put( AvailableSettings.JTA_PLATFORM, jtaPlatformClass.getName() );
settings.put( Environment.TRANSACTION_COORDINATOR_STRATEGY, transactionCoordinatorBuilderClass.getName() );
if ( connectionProviderClass != null) {
settings.put(Environment.CONNECTION_PROVIDER, connectionProviderClass.getName());
}
}
protected void markRollbackOnly(Session session) {
TxUtil.markRollbackOnly(useJta, session);
}
protected CountDownLatch expectAfterUpdate(AdvancedCache cache, int numUpdates) {
return expectReadWriteKeyCommand(cache, FutureUpdate.class::isInstance, numUpdates);
}
protected CountDownLatch expectEvict(AdvancedCache cache, int numUpdates) {
return expectReadWriteKeyCommand(cache, f -> f instanceof TombstoneUpdate && ((TombstoneUpdate) f).getValue() == null, numUpdates);
}
protected CountDownLatch expectReadWriteKeyCommand(AdvancedCache cache, Predicate<Object> valuePredicate, int numUpdates) {
if (!cacheMode.isInvalidation()) {
CountDownLatch latch = new CountDownLatch(numUpdates);
ExpectingInterceptor.get(cache)
.when((ctx, cmd) -> cmd instanceof ReadWriteKeyCommand && valuePredicate.test(((ReadWriteKeyCommand) cmd).getFunction()))
.countDown(latch);
cleanup.add(() -> ExpectingInterceptor.cleanup(cache));
return latch;
} else {
return new CountDownLatch(0);
}
}
protected CountDownLatch expectAfterEndInvalidation(AdvancedCache cache, int numInvalidates) {
CountDownLatch latch = new CountDownLatch(numInvalidates);
wrapInboundInvocationHandler(cache, handler -> new ExpectingInboundInvocationHandler(handler, latch));
return latch;
}
protected void removeAfterEndInvalidationHandler(AdvancedCache cache) {
wrapInboundInvocationHandler(cache, handler -> ((ExpectingInboundInvocationHandler) handler).getDelegate());
}
protected boolean useTransactionalCache() {
return TestRegionFactoryProvider.load().supportTransactionalCaches() && accessType == AccessType.TRANSACTIONAL;
}
private static final class ExpectingInboundInvocationHandler extends AbstractDelegatingHandler {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider
.getLog(ExpectingInboundInvocationHandler.class);
final CountDownLatch latch;
public ExpectingInboundInvocationHandler(PerCacheInboundInvocationHandler delegate, CountDownLatch latch) {
super(delegate);
this.latch = latch;
}
@Override
public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) {
if (command instanceof EndInvalidationCommand) {
delegate.handle(command, response -> {
latch.countDown();
log.tracef("Latch after count down %s", latch);
reply.reply(response);
}, order);
} else {
delegate.handle(command, reply, order);
}
}
PerCacheInboundInvocationHandler getDelegate() {
return delegate;
}
}
}
| 14,634
| 45.60828
| 244
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/EqualityTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import org.hibernate.stat.Statistics;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Name;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Person;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Persons should be correctly indexed since we can use Type for comparison
*
* @author Radim Vansa <rvansa@redhat.com>
*/
public class EqualityTest extends SingleNodeTest {
@Override
public List<Object[]> getParameters() {
return getParameters(true, true, true, true, true);
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] { Person.class };
}
@Test
public void testEqualityFromType() throws Exception {
Person john = new Person("John", "Black", 26);
Person peter = new Person("Peter", "White", 32);
withTxSession(s -> {
s.persist(john);
s.persist(peter);
});
Statistics statistics = sessionFactory().getStatistics();
statistics.clear();
for (int i = 0; i < 5; ++i) {
withTxSession(s -> {
Person p1 = s.get(Person.class, john.getName());
assertPersonEquals(john, p1);
Person p2 = s.get(Person.class, peter.getName());
assertPersonEquals(peter, p2);
Person p3 = s.get(Person.class, new Name("Foo", "Bar"));
assertNull(p3);
});
}
assertTrue(statistics.getSecondLevelCacheHitCount() > 0);
assertTrue(statistics.getSecondLevelCacheMissCount() > 0);
}
private static void assertPersonEquals(Person expected, Person person) {
assertNotNull(person);
assertNotNull(person.getName());
assertEquals(expected.getName().getFirstName(), person.getName().getFirstName());
assertEquals(expected.getName().getLastName(), person.getName().getLastName());
assertEquals(expected.getAge(), person.getAge());
}
}
| 2,064
| 29.820896
| 85
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/ReadOnlyTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Map;
import org.hibernate.stat.Statistics;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Item;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.util.ControlledTimeService;
import org.junit.Test;
/**
* Parent tests for both transactional and
* read-only tests are defined in this class.
*
* @author Galder Zamarreño
* @since 4.1
*/
public class ReadOnlyTest extends SingleNodeTest {
protected static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(ReadOnlyTest.class);
protected static final ControlledTimeService TIME_SERVICE = new ControlledTimeService();
@Override
public List<Object[]> getParameters() {
return getParameters(false, false, true, true, true);
}
@Test
public void testEmptySecondLevelCacheEntry() {
sessionFactory().getCache().evictCollectionData(Item.class.getName() + ".items");
Statistics stats = sessionFactory().getStatistics();
stats.clear();
InfinispanBaseRegion region = TEST_SESSION_ACCESS.getRegion(sessionFactory(), Item.class.getName() + ".items");
assertEquals(0, region.getElementCountInMemory());
}
@Test
public void testInsertDeleteEntity() throws Exception {
final Statistics stats = sessionFactory().getStatistics();
stats.clear();
final Item item = new Item( "chris", "Chris's Item" );
withTxSession(s -> s.persist(item));
log.info("Entry persisted, let's load and delete it.");
withTxSession(s -> {
Item found = s.load(Item.class, item.getId());
log.info(stats.toString());
assertEquals(item.getDescription(), found.getDescription());
assertEquals(0, stats.getSecondLevelCacheMissCount());
assertEquals(1, stats.getSecondLevelCacheHitCount());
s.delete(found);
});
}
@Test
public void testInsertClearCacheDeleteEntity() throws Exception {
final Statistics stats = sessionFactory().getStatistics();
stats.clear();
final Item item = new Item( "chris", "Chris's Item" );
withTxSession(s -> s.persist(item));
assertEquals(0, stats.getSecondLevelCacheMissCount());
assertEquals(0, stats.getSecondLevelCacheHitCount());
assertEquals(1, stats.getSecondLevelCachePutCount());
log.info("Entry persisted, let's load and delete it.");
cleanupCache();
TIME_SERVICE.advance(1);
withTxSession(s -> {
Item found = s.load(Item.class, item.getId());
log.info(stats.toString());
assertEquals(item.getDescription(), found.getDescription());
assertEquals(1, stats.getSecondLevelCacheMissCount());
assertEquals(0, stats.getSecondLevelCacheHitCount());
assertEquals(2, stats.getSecondLevelCachePutCount());
s.delete(found);
});
}
@Override
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(TestRegionFactory.TIME_SERVICE, TIME_SERVICE);
}
}
| 3,354
| 32.55
| 114
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/QualifierTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.hibernate.cfg.AvailableSettings;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import org.junit.Test;
public class QualifierTest extends AbstractFunctionalTest {
public static final String FOO_BAR = "foo.bar";
@Override
public List<Object[]> getParameters() {
return Collections.singletonList(READ_WRITE_DISTRIBUTED);
}
@Override
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(AvailableSettings.CACHE_REGION_PREFIX, FOO_BAR);
}
@Test
public void testRegionNamesQualified() {
TestRegionFactory factory = TestRegionFactoryProvider.INSTANCE.findRegionFactory(sessionFactory().getCache());
EmbeddedCacheManager cacheManager = factory.getCacheManager();
for (String cacheName : cacheManager.getCacheNames()) {
assertTrue(cacheName.startsWith(FOO_BAR));
}
// In Hibernate < 5.3 the region factory got qualified names and couldn't use any unqualified form
if (!TestRegionFactoryProvider.INSTANCE.getRegionFactoryClass().getName().contains(".v51.")) {
for (InfinispanBaseRegion region : TestSessionAccess.findTestSessionAccess().getAllRegions(sessionFactory())) {
assertFalse(region.getName().startsWith(FOO_BAR));
}
}
}
}
| 1,833
| 38.021277
| 120
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/ReadWriteTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Cache;
import org.hibernate.Hibernate;
import org.hibernate.NaturalIdLoadAccess;
import org.hibernate.Session;
import org.hibernate.cache.spi.entry.CacheEntry;
import org.hibernate.jpa.QueryHints;
import org.hibernate.query.criteria.HibernateCriteriaBuilder;
import org.hibernate.stat.CacheRegionStatistics;
import org.hibernate.stat.Statistics;
import org.hibernate.testing.TestForIssue;
import org.infinispan.commons.util.ByRef;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Citizen;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Citizen_;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Item;
import org.infinispan.test.hibernate.cache.commons.functional.entities.NaturalIdOnManyToOne;
import org.infinispan.test.hibernate.cache.commons.functional.entities.OtherItem;
import org.infinispan.test.hibernate.cache.commons.functional.entities.State;
import org.infinispan.test.hibernate.cache.commons.functional.entities.State_;
import org.infinispan.test.hibernate.cache.commons.functional.entities.VersionedItem;
import org.junit.After;
import org.junit.Test;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
/**
* Functional entity transactional tests.
*
* @author Galder Zamarreño
* @since 3.5
*/
public class ReadWriteTest extends ReadOnlyTest {
@Override
public List<Object[]> getParameters() {
return getParameters(true, true, false, true, true);
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {
Citizen.class, State.class,
NaturalIdOnManyToOne.class
};
}
@After
public void cleanupData() throws Exception {
super.cleanupCache();
withTxSession(s -> {
TEST_SESSION_ACCESS.execQueryUpdate(s, "delete NaturalIdOnManyToOne");
TEST_SESSION_ACCESS.execQueryUpdate(s, "delete Citizen");
TEST_SESSION_ACCESS.execQueryUpdate(s, "delete State" );
});
}
@Test
public void testCollectionCache() throws Exception {
final Statistics stats = sessionFactory().getStatistics();
stats.clear();
final Item item = new Item( "chris", "Chris's Item" );
final Item another = new Item( "another", "Owned Item" );
item.addItem( another );
withTxSession(s -> {
s.persist( item );
s.persist( another );
});
// The collection has been removed, but we can't add it again immediately using putFromLoad
TIME_SERVICE.advance(1);
withTxSession(s -> {
Item loaded = s.load( Item.class, item.getId() );
assertEquals( 1, loaded.getItems().size() );
});
String itemsRegionName = Item.class.getName() + ".items";
CacheRegionStatistics cStats = stats.getCacheRegionStatistics(itemsRegionName);
assertEquals( 1, cStats.getElementCountInMemory() );
withTxSession(s -> {
Item loadedWithCachedCollection = (Item) s.load( Item.class, item.getId() );
stats.logSummary();
assertEquals( item.getName(), loadedWithCachedCollection.getName() );
assertEquals( item.getItems().size(), loadedWithCachedCollection.getItems().size() );
assertEquals( 1, cStats.getHitCount() );
assertEquals( 1, TEST_SESSION_ACCESS.getRegion(sessionFactory(), itemsRegionName).getElementCountInMemory());
Item itemElement = loadedWithCachedCollection.getItems().iterator().next();
itemElement.setOwner( null );
loadedWithCachedCollection.getItems().clear();
s.delete( itemElement );
s.delete( loadedWithCachedCollection );
});
}
@Test
@TestForIssue( jiraKey = "HHH-9231" )
public void testAddNewOneToManyElementInitFlushLeaveCacheConsistent() throws Exception {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics cStats = stats.getCacheRegionStatistics(Item.class.getName() + ".items");
ByRef<Long> itemId = new ByRef<>(null);
saveItem(itemId);
// create an element for item.itsms
Item itemElement = new Item();
itemElement.setName( "element" );
itemElement.setDescription( "element item" );
withTxSession(s -> {
Item item = s.get( Item.class, itemId.get() );
assertFalse( Hibernate.isInitialized( item.getItems() ) );
// Add an element to item.items (a Set); it will initialize the Set.
item.addItem( itemElement );
assertTrue( Hibernate.isInitialized( item.getItems() ) );
s.persist( itemElement );
s.flush();
markRollbackOnly(s);
});
withTxSession(s -> {
Item item = s.get( Item.class, itemId.get() );
Hibernate.initialize( item.getItems() );
assertTrue( item.getItems().isEmpty() );
s.delete( item );
});
}
@Test
@TestForIssue( jiraKey = "HHH-9231" )
public void testAddNewOneToManyElementNoInitFlushLeaveCacheConsistent() throws Exception {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics cStats = stats.getCacheRegionStatistics(Item.class.getName() + ".items");
ByRef<Long> itemId = new ByRef<>(null);
saveItem(itemId);
// create an element for item.bagOfItems
Item itemElement = new Item();
itemElement.setName( "element" );
itemElement.setDescription( "element item" );
withTxSession(s -> {
Item item = s.get( Item.class, itemId.get() );
assertFalse( Hibernate.isInitialized( item.getItems() ) );
// Add an element to item.bagOfItems (a bag); it will not initialize the bag.
item.addItemToBag( itemElement );
assertFalse( Hibernate.isInitialized( item.getBagOfItems() ) );
s.persist( itemElement );
s.flush();
markRollbackOnly(s);
});
withTxSession(s -> {
Item item = s.get( Item.class, itemId.get() );
Hibernate.initialize( item.getItems() );
assertTrue( item.getItems().isEmpty() );
s.delete( item );
});
}
@Test
public void testAddNewOneToManyElementNoInitFlushInitLeaveCacheConsistent() throws Exception {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
ByRef<Long> itemId = new ByRef<>(null);
saveItem(itemId);
// create an element for item.bagOfItems
Item itemElement = new Item();
itemElement.setName( "element" );
itemElement.setDescription( "element item" );
withTxSession(s -> {
Item item = s.get(Item.class, itemId.get());
assertFalse(Hibernate.isInitialized(item.getBagOfItems()));
// Add an element to item.bagOfItems (a bag); it will not initialize the bag.
item.addItemToBag(itemElement);
assertFalse(Hibernate.isInitialized(item.getBagOfItems()));
s.persist(itemElement);
s.flush();
// Now initialize the collection; it will contain the uncommitted itemElement.
Hibernate.initialize(item.getBagOfItems());
markRollbackOnly(s);
});
withTxSession(s -> {
Item item = s.get(Item.class, itemId.get());
// Because of HHH-9231, the following will fail due to ObjectNotFoundException because the
// collection will be read from the cache and it still contains the uncommitted element,
// which cannot be found.
Hibernate.initialize(item.getBagOfItems());
assertTrue(item.getBagOfItems().isEmpty());
s.delete(item);
});
}
protected void saveItem(ByRef<Long> itemId) throws Exception {
withTxSession(s -> {
Item item = new Item();
item.setName( "steve" );
item.setDescription( "steve's item" );
s.save( item );
itemId.set(item.getId());
});
}
@Test
public void testAddNewManyToManyPropertyRefNoInitFlushInitLeaveCacheConsistent() throws Exception {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics cStats = stats.getCacheRegionStatistics(Item.class.getName() + ".items");
ByRef<Long> otherItemId = new ByRef<>(null);
withTxSession(s -> {
OtherItem otherItem = new OtherItem();
otherItem.setName( "steve" );
s.save( otherItem );
otherItemId.set(otherItem.getId());
});
// create an element for otherItem.bagOfItems
Item item = new Item();
item.setName( "element" );
item.setDescription( "element Item" );
withTxSession(s -> {
OtherItem otherItem = s.get( OtherItem.class, otherItemId.get() );
assertFalse( Hibernate.isInitialized( otherItem.getBagOfItems() ) );
// Add an element to otherItem.bagOfItems (a bag); it will not initialize the bag.
otherItem.addItemToBag( item );
assertFalse( Hibernate.isInitialized( otherItem.getBagOfItems() ) );
s.persist( item );
s.flush();
// Now initialize the collection; it will contain the uncommitted itemElement.
// The many-to-many uses a property-ref
Hibernate.initialize( otherItem.getBagOfItems() );
markRollbackOnly(s);
});
withTxSession(s -> {
OtherItem otherItem = s.get( OtherItem.class, otherItemId.get() );
// Because of HHH-9231, the following will fail due to ObjectNotFoundException because the
// collection will be read from the cache and it still contains the uncommitted element,
// which cannot be found.
Hibernate.initialize( otherItem.getBagOfItems() );
assertTrue( otherItem.getBagOfItems().isEmpty() );
s.delete( otherItem );
});
}
@Test
public void testStaleWritesLeaveCacheConsistent() throws Exception {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
ByRef<VersionedItem> itemRef = new ByRef<>(null);
withTxSession(s -> {
VersionedItem item = new VersionedItem();
item.setName( "steve" );
item.setDescription( "steve's item" );
s.save( item );
itemRef.set(item);
});
final VersionedItem item = itemRef.get();
Long initialVersion = item.getVersion();
// manually revert the version property
item.setVersion( new Long( item.getVersion().longValue() - 1 ) );
try {
withTxSession(s -> s.update(item));
fail("expected stale write to fail");
}
catch (Exception e) {
log.debug("Rollback was expected", e);
}
// check the version value in the cache...
Object entry = getEntry(VersionedItem.class.getName(), item.getId());
assertNotNull(entry);
Long cachedVersionValue = (Long) ((CacheEntry) entry).getVersion();
assertNotNull(cachedVersionValue);
assertEquals(initialVersion.longValue(), cachedVersionValue.longValue());
withTxSession(s -> {
VersionedItem item2 = s.load( VersionedItem.class, item.getId() );
s.delete( item2 );
});
}
@Test
@TestForIssue( jiraKey = "HHH-5690")
public void testPersistEntityFlushRollbackNotInEntityCache() throws Exception {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics slcs = stats.getCacheRegionStatistics(Item.class.getName());
ByRef<Long> itemId = new ByRef<>(null);
withTxSession(s -> {
Item item = new Item();
item.setName("steve");
item.setDescription("steve's item");
s.persist(item);
s.flush();
itemId.set(item.getId());
// assertNotNull( slcs.getEntries().get( item.getId() ) );
markRollbackOnly(s);
});
// item should not be in entity cache.
assertEquals(0, getNumberOfItems());
withTxSession(s -> {
Item item = s.get( Item.class, itemId.get() );
assertNull( item );
});
}
@Test
@TestForIssue( jiraKey = "HHH-5690")
public void testPersistEntityFlushEvictGetRollbackNotInEntityCache() throws Exception {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics slcs = stats.getCacheRegionStatistics(Item.class.getName());
ByRef<Long> itemId = new ByRef<>(null);
withTxSession(s -> {
Item item = new Item();
item.setName("steve");
item.setDescription("steve's item");
s.persist(item);
s.flush();
itemId.set(item.getId());
// item is cached on insert.
// assertNotNull( slcs.getEntries().get( item.getId() ) );
s.evict(item);
assertEquals(slcs.getHitCount(), 0);
item = s.get(Item.class, item.getId());
assertNotNull(item);
// assertEquals( slcs.getHitCount(), 1 );
// assertNotNull( slcs.getEntries().get( item.getId() ) );
markRollbackOnly(s);
});
// item should not be in entity cache.
//slcs = stats.getSecondLevelCacheStatistics( Item.class.getName() );
assertEquals(0, getNumberOfItems());
withTxSession(s -> {
Item item = s.get(Item.class, itemId.get());
assertNull(item);
});
}
@Test
public void testQueryCacheInvalidation() throws Exception {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics slcs = stats.getCacheRegionStatistics(Item.class.getName());
sessionFactory().getCache().evictEntityData(Item.class);
TIME_SERVICE.advance(1);
assertEquals(0, slcs.getPutCount());
assertEquals(0, slcs.getElementCountInMemory());
assertEquals(0, getNumberOfItems());
ByRef<Long> idRef = new ByRef<>(null);
withTxSession(s -> {
Item item = new Item();
item.setName( "widget" );
item.setDescription( "A really top-quality, full-featured widget." );
s.persist( item );
idRef.set( item.getId() );
});
assertEquals( 1, slcs.getPutCount() );
assertEquals( 1, slcs.getElementCountInMemory() );
assertEquals( 1, getNumberOfItems());
withTxSession(s -> {
Item item = s.get(Item.class, idRef.get());
assertEquals(slcs.getHitCount(), 1);
assertEquals(slcs.getMissCount(), 0);
item.setDescription("A bog standard item");
});
assertEquals(slcs.getPutCount(), 2);
CacheEntry entry = getEntry(Item.class.getName(), idRef.get());
Serializable[] ser = entry.getDisassembledState();
assertEquals("widget", ser[4]);
assertEquals("A bog standard item", ser[2]);
withTxSession(s -> {
Item item = s.load(Item.class, idRef.get());
s.delete(item);
});
}
@Test
public void testQueryCache() throws Exception {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
Item item = new Item( "chris", "Chris's Item" );
withTxSession(s -> s.persist( item ));
// Delay added to guarantee that query cache results won't be considered
// as not up to date due to persist session and query results from first
// query happening simultaneously.
TIME_SERVICE.advance(60001);
withTxSession(s -> TEST_SESSION_ACCESS.execQueryListCacheable(s, "from Item"));
withTxSession(s -> {
TEST_SESSION_ACCESS.execQueryListCacheable(s, "from Item" );
assertEquals( 1, stats.getQueryCacheHitCount() );
TEST_SESSION_ACCESS.execQueryUpdate(s, "delete from Item");
});
}
@Test
public void testQueryCacheHitInSameTransaction() throws Exception {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
Item item = new Item( "galder", "Galder's Item" );
withTxSession(s -> s.persist( item ));
// Delay added to guarantee that query cache results won't be considered
// as not up to date due to persist session and query results from first
// query happening simultaneously.
TIME_SERVICE.advance(60001);
withTxSession(s -> {
TEST_SESSION_ACCESS.execQueryListCacheable(s, "from Item" );
TEST_SESSION_ACCESS.execQueryListCacheable(s, "from Item" );
assertEquals(1, stats.getQueryCacheHitCount());
});
withTxSession(s -> TEST_SESSION_ACCESS.execQueryUpdate(s, "delete from Item"));
}
@Test
public void testNaturalIdCached() throws Exception {
saveSomeCitizens();
// Clear the cache before the transaction begins
cleanupCache();
TIME_SERVICE.advance(1);
withTxSession(s -> {
State france = ReadWriteTest.this.getState(s, "Ile de France");
HibernateCriteriaBuilder cb = s.getCriteriaBuilder();
CriteriaQuery<Citizen> criteria = cb.createQuery(Citizen.class);
Root<Citizen> root = criteria.from(Citizen.class);
criteria.where(cb.equal(root.get(Citizen_.ssn), "1234"), cb.equal(root.get(Citizen_.state), france));
Statistics stats = sessionFactory().getStatistics();
stats.setStatisticsEnabled(true);
stats.clear();
assertEquals(
"Cache hits should be empty", 0, stats
.getNaturalIdCacheHitCount()
);
TypedQuery<Citizen> typedQuery = s.createQuery(criteria)
.setHint(QueryHints.HINT_CACHEABLE, "true");
// first query
List results = typedQuery
.getResultList();
assertEquals(1, results.size());
assertEquals("NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount());
assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
assertEquals("NaturalId Cache Puts", 1, stats.getNaturalIdCachePutCount());
assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
// query a second time - result should be cached in session
typedQuery.getResultList();
assertEquals("NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount());
assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
assertEquals("NaturalId Cache Puts", 1, stats.getNaturalIdCachePutCount());
assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
// cleanup
markRollbackOnly(s);
});
}
@Test
public void testNaturalIdLoaderCached() throws Exception {
final Statistics stats = sessionFactory().getStatistics();
stats.setStatisticsEnabled( true );
stats.clear();
assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() );
assertEquals( "NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount() );
assertEquals( "NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount() );
assertEquals( "NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount() );
saveSomeCitizens();
assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() );
assertEquals( "NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount() );
assertEquals( "NaturalId Cache Puts", 2, stats.getNaturalIdCachePutCount() );
assertEquals( "NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount() );
//Try NaturalIdLoadAccess after insert
final Citizen citizen = withTxSessionApply(s -> {
State france = ReadWriteTest.this.getState(s, "Ile de France");
NaturalIdLoadAccess<Citizen> naturalIdLoader = s.byNaturalId(Citizen.class);
naturalIdLoader.using("ssn", "1234").using("state", france);
//Not clearing naturalId caches, should be warm from entity loading
stats.clear();
// first query
Citizen c = naturalIdLoader.load();
assertNotNull(c);
assertEquals("NaturalId Cache Hits", 1, stats.getNaturalIdCacheHitCount());
assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
assertEquals("NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount());
assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
// cleanup
markRollbackOnly(s);
return c;
});
// TODO: Clear caches manually via cache manager (it's faster!!)
cleanupCache();
TIME_SERVICE.advance(1);
stats.setStatisticsEnabled( true );
stats.clear();
//Try NaturalIdLoadAccess
withTxSession(s -> {
// first query
Citizen loadedCitizen = (Citizen) s.get( Citizen.class, citizen.getId() );
assertNotNull( loadedCitizen );
assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() );
assertEquals( "NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount() );
assertEquals( "NaturalId Cache Puts", 1, stats.getNaturalIdCachePutCount() );
assertEquals( "NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount() );
// cleanup
markRollbackOnly(s);
});
// Try NaturalIdLoadAccess after load
withTxSession(s -> {
State france = ReadWriteTest.this.getState(s, "Ile de France");
NaturalIdLoadAccess naturalIdLoader = s.byNaturalId(Citizen.class);
naturalIdLoader.using( "ssn", "1234" ).using( "state", france );
//Not clearing naturalId caches, should be warm from entity loading
stats.setStatisticsEnabled( true );
stats.clear();
// first query
Citizen loadedCitizen = (Citizen) naturalIdLoader.load();
assertNotNull( loadedCitizen );
assertEquals( "NaturalId Cache Hits", 1, stats.getNaturalIdCacheHitCount() );
assertEquals( "NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount() );
assertEquals( "NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount() );
assertEquals( "NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount() );
// cleanup
markRollbackOnly(s);
});
}
@Test
public void testEntityCacheContentsAfterEvictAll() throws Exception {
final List<Citizen> citizens = saveSomeCitizens();
withTxSession(s -> {
Cache cache = s.getSessionFactory().getCache();
Statistics stats = sessionFactory().getStatistics();
CacheRegionStatistics slcStats = stats.getCacheRegionStatistics(Citizen.class.getName());
assertTrue("2lc entity cache is expected to contain Citizen id = " + citizens.get(0).getId(),
cache.containsEntity(Citizen.class, citizens.get(0).getId()));
assertTrue("2lc entity cache is expected to contain Citizen id = " + citizens.get(1).getId(),
cache.containsEntity(Citizen.class, citizens.get(1).getId()));
assertEquals(2, slcStats.getPutCount());
cache.evictAll();
TIME_SERVICE.advance(1);
assertEquals(0, slcStats.getElementCountInMemory());
assertFalse("2lc entity cache is expected to not contain Citizen id = " + citizens.get(0).getId(),
cache.containsEntity(Citizen.class, citizens.get(0).getId()));
assertFalse("2lc entity cache is expected to not contain Citizen id = " + citizens.get(1).getId(),
cache.containsEntity(Citizen.class, citizens.get(1).getId()));
Citizen citizen = s.load(Citizen.class, citizens.get(0).getId());
assertNotNull(citizen);
assertNotNull(citizen.getFirstname()); // proxy gets resolved
assertEquals(1, slcStats.getMissCount());
// cleanup
markRollbackOnly(s);
});
}
@Test
public void testMultipleEvictAll() throws Exception {
final List<Citizen> citizens = saveSomeCitizens();
withTxSession(s -> {
Cache cache = s.getSessionFactory().getCache();
cache.evictAll();
cache.evictAll();
});
withTxSession(s -> {
Cache cache = s.getSessionFactory().getCache();
cache.evictAll();
s.delete(s.load(Citizen.class, citizens.get(0).getId()));
s.delete(s.load(Citizen.class, citizens.get(1).getId()));
});
}
private List<Citizen> saveSomeCitizens() throws Exception {
final Citizen c1 = new Citizen();
c1.setFirstname( "Emmanuel" );
c1.setLastname( "Bernard" );
c1.setSsn( "1234" );
final State france = new State();
france.setName( "Ile de France" );
c1.setState( france );
final Citizen c2 = new Citizen();
c2.setFirstname( "Gavin" );
c2.setLastname( "King" );
c2.setSsn( "000" );
final State australia = new State();
australia.setName( "Australia" );
c2.setState( australia );
withTxSession(s -> {
s.persist( australia );
s.persist( france );
s.persist( c1 );
s.persist( c2 );
});
List<Citizen> citizens = new ArrayList<>(2);
citizens.add(c1);
citizens.add(c2);
return citizens;
}
private State getState(Session s, String name) {
HibernateCriteriaBuilder cb = s.getCriteriaBuilder();
CriteriaQuery<State> criteria = cb.createQuery(State.class);
Root<State> root = criteria.from(State.class);
criteria.where(cb.equal(root.get(State_.name), name));
return s.createQuery(criteria)
.setHint(QueryHints.HINT_CACHEABLE, "true")
.getResultList().get(0);
}
private int getNumberOfItems() {
return (int) TEST_SESSION_ACCESS.getRegion(sessionFactory(), Item.class.getName()).getElementCountInMemory();
}
private CacheEntry getEntry(String regionName, Long key) {
return (CacheEntry) TEST_SESSION_ACCESS.getRegion(sessionFactory(), regionName).getCache().get(key);
}
}
| 24,138
| 32.90309
| 112
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/TombstoneTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.hibernate.testing.TestForIssue;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.distribution.BlockingInterceptor;
import org.infinispan.hibernate.cache.commons.util.Tombstone;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Item;
import org.junit.Test;
/**
* Tests specific to tombstone-based caches
*
* @author Radim Vansa <rvansa@redhat.com>
*/
public class TombstoneTest extends AbstractNonInvalidationTest {
@Override
public List<Object[]> getParameters() {
return Arrays.asList(READ_WRITE_REPLICATED, READ_WRITE_DISTRIBUTED);
}
@Test
public void testTombstoneExpiration() throws Exception {
CyclicBarrier loadBarrier = new CyclicBarrier(2);
CountDownLatch flushLatch = new CountDownLatch(2);
CountDownLatch commitLatch = new CountDownLatch(1);
Future<Boolean> first = removeFlushWait(itemId, loadBarrier, null, flushLatch, commitLatch);
Future<Boolean> second = removeFlushWait(itemId, loadBarrier, null, flushLatch, commitLatch);
awaitOrThrow(flushLatch);
// Second remove fails due to being unable to lock entry *before* writing the tombstone
assertTombstone(1);
commitLatch.countDown();
first.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
second.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
// after commit, the tombstone should still be in memory for some time (though, updatable)
assertTombstone(1);
TIME_SERVICE.advance(timeout + 1);
assertEmptyCache();
}
@Test
public void testTwoUpdates1() throws Exception {
CyclicBarrier loadBarrier = new CyclicBarrier(2);
CountDownLatch preFlushLatch = new CountDownLatch(1);
CountDownLatch flushLatch1 = new CountDownLatch(1);
CountDownLatch flushLatch2 = new CountDownLatch(1);
CountDownLatch commitLatch1 = new CountDownLatch(1);
CountDownLatch commitLatch2 = new CountDownLatch(1);
// Note: this is a single node case, we don't have to deal with async replication
Future<Boolean> update1 = updateFlushWait(itemId, loadBarrier, null, flushLatch1, commitLatch1);
Future<Boolean> update2 = updateFlushWait(itemId, loadBarrier, preFlushLatch, flushLatch2, commitLatch2);
awaitOrThrow(flushLatch1);
assertTombstone(1);
preFlushLatch.countDown();
awaitOrThrow(flushLatch2);
// Second update fails due to being unable to lock entry *before* writing the tombstone
assertTombstone(1);
commitLatch2.countDown();
assertFalse(update2.get(WAIT_TIMEOUT, TimeUnit.SECONDS));
assertTombstone(1);
commitLatch1.countDown();
assertTrue(update1.get(WAIT_TIMEOUT, TimeUnit.SECONDS));
assertSingleCacheEntry();
}
@Test
public void testTwoUpdates2() throws Exception {
CyclicBarrier loadBarrier = new CyclicBarrier(2);
CountDownLatch preFlushLatch = new CountDownLatch(1);
CountDownLatch flushLatch1 = new CountDownLatch(1);
CountDownLatch flushLatch2 = new CountDownLatch(1);
CountDownLatch commitLatch1 = new CountDownLatch(1);
CountDownLatch commitLatch2 = new CountDownLatch(1);
// Note: this is a single node case, we don't have to deal with async replication
Future<Boolean> update1 = updateFlushWait(itemId, loadBarrier, null, flushLatch1, commitLatch1);
Future<Boolean> update2 = updateFlushWait(itemId, loadBarrier, preFlushLatch, flushLatch2, commitLatch2);
awaitOrThrow(flushLatch1);
assertCacheContains(Tombstone.class);
preFlushLatch.countDown();
awaitOrThrow(flushLatch2);
// Second update fails due to being unable to lock entry *before* writing the tombstone
assertTombstone(1);
commitLatch1.countDown();
assertTrue(update1.get(WAIT_TIMEOUT, TimeUnit.SECONDS));
assertSingleCacheEntry();
commitLatch2.countDown();
assertFalse(update2.get(WAIT_TIMEOUT, TimeUnit.SECONDS));
assertSingleCacheEntry();
TIME_SERVICE.advance(TIMEOUT + 1);
assertSingleCacheEntry();
}
@Test
public void testRemoveUpdateExpiration() throws Exception {
CyclicBarrier loadBarrier = new CyclicBarrier(2);
CountDownLatch preFlushLatch = new CountDownLatch(1);
CountDownLatch flushLatch = new CountDownLatch(1);
CountDownLatch commitLatch = new CountDownLatch(1);
Future<Boolean> first = removeFlushWait(itemId, loadBarrier, null, flushLatch, commitLatch);
Future<Boolean> second = updateFlushWait(itemId, loadBarrier, preFlushLatch, null, commitLatch);
awaitOrThrow(flushLatch);
// Second update fails due to being unable to lock entry *before* writing the tombstone
assertTombstone(1);
preFlushLatch.countDown();
commitLatch.countDown();
first.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
second.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
assertTombstone(1);
TIME_SERVICE.advance(timeout + 1);
assertEmptyCache();
}
@Test
public void testUpdateRemoveExpiration() throws Exception {
CyclicBarrier loadBarrier = new CyclicBarrier(2);
CountDownLatch preFlushLatch = new CountDownLatch(1);
CountDownLatch flushLatch = new CountDownLatch(1);
CountDownLatch commitLatch = new CountDownLatch(1);
Future<Boolean> first = updateFlushWait(itemId, loadBarrier, null, flushLatch, commitLatch);
Future<Boolean> second = removeFlushWait(itemId, loadBarrier, preFlushLatch, null, commitLatch);
awaitOrThrow(flushLatch);
assertTombstone(1);
preFlushLatch.countDown();
commitLatch.countDown();
first.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
boolean removeSucceeded = second.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
if (removeSucceeded) {
assertCacheContains(Tombstone.class);
TIME_SERVICE.advance(timeout + 1);
assertEmptyCache();
} else {
assertSingleCacheEntry();
TIME_SERVICE.advance(timeout + 1);
assertSingleCacheEntry();
}
}
@Test
public void testUpdateEvictExpiration() throws Exception {
CyclicBarrier loadBarrier = new CyclicBarrier(2);
CountDownLatch preEvictLatch = new CountDownLatch(1);
CountDownLatch postEvictLatch = new CountDownLatch(1);
CountDownLatch flushLatch = new CountDownLatch(1);
CountDownLatch commitLatch = new CountDownLatch(1);
Future<Boolean> first = updateFlushWait(itemId, loadBarrier, null, flushLatch, commitLatch);
Future<Boolean> second = evictWait(itemId, loadBarrier, preEvictLatch, postEvictLatch);
awaitOrThrow(flushLatch);
assertTombstone(1);
preEvictLatch.countDown();
awaitOrThrow(postEvictLatch);
assertTombstone(1);
commitLatch.countDown();
first.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
second.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
assertSingleCacheEntry();
TIME_SERVICE.advance(timeout + 1);
assertSingleCacheEntry();
}
@Test
public void testEvictUpdate() throws Exception {
CyclicBarrier loadBarrier = new CyclicBarrier(2);
CountDownLatch preFlushLatch = new CountDownLatch(1);
CountDownLatch postEvictLatch = new CountDownLatch(1);
CountDownLatch flushLatch = new CountDownLatch(1);
CountDownLatch commitLatch = new CountDownLatch(1);
Future<Boolean> first = evictWait(itemId, loadBarrier, null, postEvictLatch);
Future<Boolean> second = updateFlushWait(itemId, loadBarrier, preFlushLatch, flushLatch, commitLatch);
awaitOrThrow(postEvictLatch);
assertEmptyCache();
preFlushLatch.countDown();
awaitOrThrow(flushLatch);
// The tombstone from update has overwritten the eviction tombstone as it has timestamp = now + 60s
assertTombstone(1);
commitLatch.countDown();
first.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
second.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
// Since evict was executed during the update, we cannot insert the entry into cache
assertSingleCacheEntry();
TIME_SERVICE.advance(timeout + 1);
assertSingleCacheEntry();
}
@Test
public void testEvictUpdate2() throws Exception {
CountDownLatch flushLatch = new CountDownLatch(1);
CountDownLatch commitLatch = new CountDownLatch(1);
sessionFactory().getCache().evictEntityData(Item.class, itemId);
// When the cache was empty, the tombstone is not stored
assertEmptyCache();
TIME_SERVICE.advance(1);
Future<Boolean> update = updateFlushWait(itemId, null, null, flushLatch, commitLatch);
awaitOrThrow(flushLatch);
assertTombstone(1);
commitLatch.countDown();
update.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
assertSingleCacheEntry();
TIME_SERVICE.advance(timeout + 2);
assertSingleCacheEntry();
}
@Test
public void testEvictPutFromLoad() throws Exception {
sessionFactory().getCache().evictEntityData(Item.class, itemId);
assertEmptyCache();
TIME_SERVICE.advance(1);
assertItemDescription("Original item");
assertSingleCacheEntry();
TIME_SERVICE.advance(timeout + 2);
assertSingleCacheEntry();
}
protected void assertItemDescription(String expected) throws Exception {
assertEquals(expected, withTxSessionApply(s -> s.load(Item.class, itemId).getDescription()));
}
@Test
public void testPutFromLoadDuringUpdate() throws Exception {
CountDownLatch flushLatch = new CountDownLatch(1);
CountDownLatch commitLatch = new CountDownLatch(1);
CyclicBarrier putFromLoadBarrier = new CyclicBarrier(2);
// We cannot just do load during update because that could be blocked in DB
Future<?> putFromLoad = blockedPutFromLoad(putFromLoadBarrier);
Future<Boolean> update = updateFlushWait(itemId, null, null, flushLatch, commitLatch);
awaitOrThrow(flushLatch);
assertTombstone(1);
unblockPutFromLoad(putFromLoadBarrier, putFromLoad);
commitLatch.countDown();
update.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
assertSingleCacheEntry();
assertItemDescription("Updated item");
}
@TestForIssue(jiraKey = "HHH-11323")
@Test
public void testEvictPutFromLoadDuringUpdate() throws Exception {
CountDownLatch flushLatch = new CountDownLatch(1);
CountDownLatch commitLatch = new CountDownLatch(1);
CyclicBarrier putFromLoadBarrier = new CyclicBarrier(2);
Future<?> putFromLoad = blockedPutFromLoad(putFromLoadBarrier);
Future<Boolean> update = updateFlushWait(itemId, null, null, flushLatch, commitLatch);
// Flush stores FutureUpdate(timestamp, null)
awaitOrThrow(flushLatch);
sessionFactory().getCache().evictEntityData(Item.class, itemId);
commitLatch.countDown();
update.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
unblockPutFromLoad(putFromLoadBarrier, putFromLoad);
assertItemDescription("Updated item");
}
private Future<?> blockedPutFromLoad(CyclicBarrier putFromLoadBarrier) throws InterruptedException, BrokenBarrierException, TimeoutException {
BlockingInterceptor blockingInterceptor = new BlockingInterceptor(putFromLoadBarrier, ReadWriteKeyCommand.class, false, true);
entityCache.getAsyncInterceptorChain().addInterceptor(blockingInterceptor, 0);
cleanup.add(() -> extractInterceptorChain(entityCache).removeInterceptor(BlockingInterceptor.class));
// the putFromLoad should be blocked in the interceptor
Future<?> putFromLoad = executor.submit(() -> withTxSessionApply(s -> {
assertEquals("Original item", s.load(Item.class, itemId).getDescription());
return null;
}));
putFromLoadBarrier.await(WAIT_TIMEOUT, TimeUnit.SECONDS);
blockingInterceptor.suspend(true);
return putFromLoad;
}
private void unblockPutFromLoad(CyclicBarrier putFromLoadBarrier, Future<?> putFromLoad) throws InterruptedException, BrokenBarrierException, TimeoutException, java.util.concurrent.ExecutionException {
putFromLoadBarrier.await(WAIT_TIMEOUT, TimeUnit.SECONDS);
putFromLoad.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
}
private void assertTombstone(int expectedSize) {
Tombstone tombstone = assertCacheContains(Tombstone.class);
assertEquals("Tombstone is " + tombstone, expectedSize, tombstone.size());
}
}
| 12,987
| 36.537572
| 204
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/LocalCacheTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.INFINISPAN_CONFIG_LOCAL_RESOURCE;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.INFINISPAN_CONFIG_RESOURCE_PROP;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform;
import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl;
import org.hibernate.testing.TestForIssue;
import org.infinispan.commons.util.ByRef;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.test.TestException;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Customer;
import org.junit.Test;
public class LocalCacheTest extends SingleNodeTest {
@Override
public List<Object[]> getParameters() {
return Collections.singletonList(new Object[]{
"local", NoJtaPlatform.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class, null, AccessType.READ_WRITE, CacheMode.LOCAL, false, false
});
}
@Override
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(INFINISPAN_CONFIG_RESOURCE_PROP, INFINISPAN_CONFIG_LOCAL_RESOURCE);
}
@Test
@TestForIssue(jiraKey = "HHH-12457")
public void testRollback() throws Exception {
ByRef<Integer> idRef = new ByRef<>(0);
withTxSession(s -> {
Customer c = new Customer();
c.setName("Foo");
s.persist(c);
idRef.set(c.getId());
});
Exceptions.expectException(TestException.class, () -> withTxSession(s -> {
Customer c = s.load(Customer.class, idRef.get());
c.setName("Bar");
s.persist(c);
s.flush();
throw new TestException("Roll me back");
}));
withTxSession(s -> {
Customer c = s.load(Customer.class, idRef.get());
assertEquals("Foo", c.getName());
});
}
}
| 2,209
| 36.457627
| 158
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/JndiRegionFactoryTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NameNotFoundException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.stat.Statistics;
import org.infinispan.Cache;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Item;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.jboss.util.naming.NonSerializableFactory;
import org.jnp.server.Main;
import org.jnp.server.SingletonNamingServer;
import org.junit.Test;
/**
* @author Galder Zamarreño
*/
public class JndiRegionFactoryTest extends SingleNodeTest {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( JndiRegionFactoryTest.class );
private static final String JNDI_NAME = "java:CacheManager";
private Main namingMain;
private SingletonNamingServer namingServer;
private Properties props;
private boolean bindToJndi = true;
private EmbeddedCacheManager manager;
@Override
public List<Object[]> getParameters() {
return Collections.singletonList(READ_WRITE_INVALIDATION);
}
@Override
protected void cleanupTest() throws Exception {
Context ctx = new InitialContext( props );
unbind( JNDI_NAME, ctx );
namingServer.destroy();
namingMain.stop();
manager.stop(); // Need to stop cos JNDI region factory does not stop it.
}
@Override
protected void afterStandardServiceRegistryBuilt(StandardServiceRegistry ssr) {
if ( bindToJndi ) {
try {
// Create an in-memory jndi
namingServer = new SingletonNamingServer();
namingMain = new Main();
namingMain.setInstallGlobalService( true );
namingMain.setPort( -1 );
namingMain.start();
props = new Properties();
props.put( "java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory" );
props.put( "java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces" );
final String cfgFileName = (String) ssr.getService( ConfigurationService.class ).getSettings().get(
InfinispanProperties.INFINISPAN_CONFIG_RESOURCE_PROP
);
manager = new DefaultCacheManager(
cfgFileName == null ? InfinispanProperties.DEF_INFINISPAN_CONFIG_RESOURCE : cfgFileName,
false
);
Context ctx = new InitialContext( props );
bind( JNDI_NAME, manager, EmbeddedCacheManager.class, ctx );
}
catch (Exception e) {
throw new RuntimeException( "Failure to set up JNDI", e );
}
}
}
@Override
@SuppressWarnings("unchecked")
protected void addSettings(Map settings) {
super.addSettings( settings );
settings.put( InfinispanProperties.CACHE_MANAGER_RESOURCE_PROP, JNDI_NAME );
settings.put( Environment.JNDI_CLASS, "org.jnp.interfaces.NamingContextFactory" );
settings.put( "java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces" );
}
@Test
public void testRedeployment() throws Exception {
addEntityCheckCache(sessionFactory());
bindToJndi = false;
rebuildSessionFactory();
addEntityCheckCache(sessionFactory());
TestRegionFactory regionFactory = TestRegionFactoryProvider.load().wrap(sessionFactory().getCache().getRegionFactory());
Cache cache = regionFactory.getCacheManager().getCache(Item.class.getName());
assertEquals(ComponentStatus.RUNNING, cache.getStatus());
}
private void addEntityCheckCache(SessionFactoryImplementor sessionFactory) throws Exception {
Item item = new Item( "chris", "Chris's Item" );
withTxSession(s -> s.persist( item ));
withTxSession(s -> {
Item found = s.load(Item.class, item.getId());
Statistics stats = sessionFactory.getStatistics();
log.info(stats.toString());
assertEquals(item.getDescription(), found.getDescription());
assertEquals(0, stats.getSecondLevelCacheMissCount());
assertEquals(1, stats.getSecondLevelCacheHitCount());
s.delete(found);
});
}
/**
* Helper method that binds the a non serializable object to the JNDI tree.
*
* @param jndiName Name under which the object must be bound
* @param who Object to bind in JNDI
* @param classType Class type under which should appear the bound object
* @param ctx Naming context under which we bind the object
* @throws Exception Thrown if a naming exception occurs during binding
*/
private void bind(String jndiName, Object who, Class<?> classType, Context ctx) throws Exception {
// Ah ! This service isn't serializable, so we use a helper class
NonSerializableFactory.bind( jndiName, who );
Name n = ctx.getNameParser( "" ).parse( jndiName );
while ( n.size() > 1 ) {
String ctxName = n.get( 0 );
try {
ctx = (Context) ctx.lookup( ctxName );
}
catch (NameNotFoundException e) {
log.debug( "creating Subcontext " + ctxName );
ctx = ctx.createSubcontext( ctxName );
}
n = n.getSuffix( 1 );
}
// The helper class NonSerializableFactory uses address type nns, we go on to
// use the helper class to bind the service object in JNDI
StringRefAddr addr = new StringRefAddr( "nns", jndiName );
Reference ref = new Reference( classType.getName(), addr, NonSerializableFactory.class.getName(), null );
ctx.rebind( n.get( 0 ), ref );
}
private void unbind(String jndiName, Context ctx) throws Exception {
NonSerializableFactory.unbind( jndiName );
// ctx.unbind(jndiName);
}
}
| 6,374
| 35.849711
| 123
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/NoTenancyTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Collections;
import java.util.List;
import org.infinispan.AdvancedCache;
import org.infinispan.context.Flag;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Item;
import org.junit.Test;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public class NoTenancyTest extends SingleNodeTest {
@Override
public List<Object[]> getParameters() {
return Collections.singletonList(READ_ONLY_INVALIDATION);
}
@Test
public void testNoTenancy() throws Exception {
final Item item = new Item("my item", "description" );
withTxSession(s -> s.persist(item));
for (int i = 0; i < 5; ++i) { // make sure we get something cached
withTxSession(s -> {
Item item2 = s.get(Item.class, item.getId());
assertNotNull(item2);
assertEquals(item.getName(), item2.getName());
});
}
InfinispanBaseRegion region = TEST_SESSION_ACCESS.getRegion(sessionFactory(), Item.class.getName());
AdvancedCache localCache = region.getCache().withFlags(Flag.CACHE_MODE_LOCAL);
assertEquals(1, localCache.size());
}
}
| 1,322
| 30.5
| 104
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/VersionedTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.PessimisticLockException;
import org.hibernate.Session;
import org.hibernate.StaleStateException;
import org.hibernate.cache.spi.access.AccessType;
import org.infinispan.AdvancedCache;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commons.util.ByRef;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.hibernate.cache.commons.access.SessionAccess;
import org.infinispan.hibernate.cache.commons.util.Caches;
import org.infinispan.hibernate.cache.commons.util.VersionedEntry;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.interceptors.impl.CallInterceptor;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Item;
import org.infinispan.test.hibernate.cache.commons.functional.entities.OtherItem;
import org.junit.Test;
import jakarta.transaction.Synchronization;
/**
* Tests specific to versioned entries -based caches.
* Similar to {@link TombstoneTest} but some cases have been removed since
* we are modifying the cache only once, therefore some sequences of operations
* would fail before touching the cache.
*
* @author Radim Vansa <rvansa@redhat.com>
*/
public class VersionedTest extends AbstractNonInvalidationTest {
protected static final SessionAccess SESSION_ACCESS = SessionAccess.findSessionAccess();
@Override
public List<Object[]> getParameters() {
return Arrays.asList(NONSTRICT_REPLICATED, NONSTRICT_DISTRIBUTED, NONSTRICT_REPLICATED_STATS, NONSTRICT_DISTRIBUTED_STATS);
}
@Override
protected boolean getUseQueryCache() {
return false;
}
@Test
public void testTwoRemoves() throws Exception {
CyclicBarrier loadBarrier = new CyclicBarrier(2);
CountDownLatch flushLatch = new CountDownLatch(2);
CountDownLatch commitLatch = new CountDownLatch(1);
Future<Boolean> first = removeFlushWait(itemId, loadBarrier, null, flushLatch, commitLatch);
Future<Boolean> second = removeFlushWait(itemId, loadBarrier, null, flushLatch, commitLatch);
awaitOrThrow(flushLatch);
assertSingleEmpty();
commitLatch.countDown();
boolean firstResult = first.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
boolean secondResult = second.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
assertTrue(firstResult != secondResult);
assertSingleEmpty();
TIME_SERVICE.advance(timeout + 1);
assertEmptyCache();
}
@Test
public void testRemoveRolledBack() throws Exception {
withTxSession(s -> {
Item item = s.load(Item.class, itemId);
s.delete(item);
assertSingleCacheEntry();
s.flush();
markRollbackOnly(s);
});
assertSingleEmpty();
}
@Test
public void testUpdateRolledBack() throws Exception {
ByRef<Object> entryRef = new ByRef<>(null);
withTxSession(s -> {
Item item = s.load(Item.class, itemId);
item.getDescription();
Object prevEntry = assertSingleCacheEntry();
entryRef.set(prevEntry);
item.setDescription("Updated item");
s.update(item);
assertEquals(prevEntry, assertSingleCacheEntry());
s.flush();
assertEquals(prevEntry, assertSingleCacheEntry());
markRollbackOnly(s);
});
assertEquals(entryRef.get(), assertSingleCacheEntry());
}
@Test
public void testStaleReadDuringUpdate() throws Exception {
ByRef<Object> entryRef = testStaleRead((s, item) -> {
item.setDescription("Updated item");
s.update(item);
});
assertNotEquals(entryRef.get(), assertSingleCacheEntry());
withTxSession(s -> {
Item item = s.load(Item.class, itemId);
assertEquals("Updated item", item.getDescription());
});
}
@Test
public void testStaleReadDuringRemove() throws Exception {
try {
testStaleRead((s, item) -> s.delete(item));
if (accessType == AccessType.NONSTRICT_READ_WRITE) {
// Nonstrict removes preemptively to prevent permanent cache inconsistency
fail("Should have thrown an ObjectNotFoundException!");
}
} catch (ObjectNotFoundException e) {
if (accessType != AccessType.NONSTRICT_READ_WRITE) {
throw e;
}
}
assertSingleEmpty();
withTxSession(s -> {
Item item = s.get(Item.class, itemId);
assertNull(item);
});
}
protected ByRef<Object> testStaleRead(BiConsumer<Session, Item> consumer) throws Exception {
AtomicReference<Exception> synchronizationException = new AtomicReference<>();
CountDownLatch syncLatch = new CountDownLatch(1);
CountDownLatch commitLatch = new CountDownLatch(1);
Future<Boolean> action = executor.submit(() -> withTxSessionApply(s -> {
try {
SESSION_ACCESS.getTransactionCoordinator(s).registerLocalSynchronization(new Synchronization() {
@Override
public void beforeCompletion() {
}
@Override
public void afterCompletion(int i) {
syncLatch.countDown();
try {
awaitOrThrow(commitLatch);
} catch (Exception e) {
synchronizationException.set(e);
}
}
});
Item item = s.load(Item.class, itemId);
consumer.accept(s, item);
s.flush();
} catch (StaleStateException e) {
log.info("Exception thrown: ", e);
markRollbackOnly(s);
return false;
} catch (PessimisticLockException e) {
log.info("Exception thrown: ", e);
markRollbackOnly(s);
return false;
}
return true;
}));
awaitOrThrow(syncLatch);
ByRef<Object> entryRef = new ByRef<>(null);
try {
withTxSession(s -> {
Item item = s.load(Item.class, itemId);
assertEquals("Original item", item.getDescription());
entryRef.set(assertSingleCacheEntry());
});
} finally {
commitLatch.countDown();
}
assertTrue(action.get(WAIT_TIMEOUT, TimeUnit.SECONDS));
assertNull(synchronizationException.get());
return entryRef;
}
@Test
public void testUpdateEvictExpiration() throws Exception {
CyclicBarrier loadBarrier = new CyclicBarrier(2);
CountDownLatch preEvictLatch = new CountDownLatch(1);
CountDownLatch postEvictLatch = new CountDownLatch(1);
CountDownLatch flushLatch = new CountDownLatch(1);
CountDownLatch commitLatch = new CountDownLatch(1);
Future<Boolean> first = updateFlushWait(itemId, loadBarrier, null, flushLatch, commitLatch);
Future<Boolean> second = evictWait(itemId, loadBarrier, preEvictLatch, postEvictLatch);
awaitOrThrow(flushLatch);
assertSingleCacheEntry();
preEvictLatch.countDown();
awaitOrThrow(postEvictLatch);
assertSingleEmpty();
commitLatch.countDown();
first.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
second.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
assertSingleEmpty();
TIME_SERVICE.advance(timeout + 1);
assertEmptyCache();
}
@Test
public void testEvictUpdateExpiration() throws Exception {
// since the timestamp for update is based on session open/tx begin time, we have to do this sequentially
sessionFactory().getCache().evictEntityData(Item.class, itemId);
assertSingleEmpty();
TIME_SERVICE.advance(1);
withTxSession(s -> {
Item item = s.load(Item.class, itemId);
item.setDescription("Updated item");
s.update(item);
});
assertSingleCacheEntry();
TIME_SERVICE.advance(timeout + 1);
assertSingleCacheEntry();
}
@Test
public void testEvictAndPutFromLoad() throws Exception {
sessionFactory().getCache().evictEntityData(Item.class, itemId);
assertSingleEmpty();
TIME_SERVICE.advance(1);
withTxSession(s -> {
Item item = s.load(Item.class, itemId);
assertEquals("Original item", item.getDescription());
});
assertSingleCacheEntry();
TIME_SERVICE.advance(TIMEOUT + 1);
assertSingleCacheEntry();
}
@Test
public void testCollectionUpdate() throws Exception {
// the first insert puts VersionedEntry(null, null, timestamp), so we have to wait a while to cache the entry
TIME_SERVICE.advance(1);
withTxSession(s -> {
Item item = s.load(Item.class, itemId);
OtherItem otherItem = new OtherItem();
otherItem.setName("Other 1");
s.persist(otherItem);
item.addOtherItem(otherItem);
});
withTxSession(s -> {
Item item = s.load(Item.class, itemId);
Set<OtherItem> otherItems = item.getOtherItems();
assertFalse(otherItems.isEmpty());
otherItems.remove(otherItems.iterator().next());
});
AdvancedCache collectionCache = TEST_SESSION_ACCESS.getRegion(sessionFactory(), Item.class.getName() + ".otherItems").getCache();
CountDownLatch putFromLoadLatch = new CountDownLatch(1);
AtomicBoolean committing = new AtomicBoolean(false);
CollectionUpdateTestInterceptor collectionUpdateTestInterceptor = new CollectionUpdateTestInterceptor(putFromLoadLatch);
AnotherCollectionUpdateTestInterceptor anotherInterceptor = new AnotherCollectionUpdateTestInterceptor(putFromLoadLatch, committing);
AsyncInterceptorChain interceptorChain = collectionCache.getAsyncInterceptorChain();
interceptorChain.addInterceptorBefore( collectionUpdateTestInterceptor, CallInterceptor.class );
interceptorChain.addInterceptor(anotherInterceptor, 0);
TIME_SERVICE.advance(1);
Future<Boolean> addFuture = executor.submit(() -> withTxSessionApply(s -> {
awaitOrThrow(collectionUpdateTestInterceptor.updateLatch);
Item item = s.load(Item.class, itemId);
OtherItem otherItem = new OtherItem();
otherItem.setName("Other 2");
s.persist(otherItem);
item.addOtherItem(otherItem);
committing.set(true);
return true;
}));
Future<Boolean> readFuture = executor.submit(() -> withTxSessionApply(s -> {
Item item = s.load(Item.class, itemId);
assertTrue(item.getOtherItems().isEmpty());
return true;
}));
addFuture.get();
readFuture.get();
interceptorChain.removeInterceptor(CollectionUpdateTestInterceptor.class);
interceptorChain.removeInterceptor(AnotherCollectionUpdateTestInterceptor.class);
withTxSession(s -> assertFalse(s.load(Item.class, itemId).getOtherItems().isEmpty()));
}
class CollectionUpdateTestInterceptor extends DDAsyncInterceptor {
final AtomicBoolean firstPutFromLoad = new AtomicBoolean(true);
final CountDownLatch putFromLoadLatch;
final CountDownLatch updateLatch = new CountDownLatch(1);
public CollectionUpdateTestInterceptor(CountDownLatch putFromLoadLatch) {
this.putFromLoadLatch = putFromLoadLatch;
}
@Override
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable {
if (command.hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT)) {
if (firstPutFromLoad.compareAndSet(true, false)) {
updateLatch.countDown();
awaitOrThrow(putFromLoadLatch);
}
}
return super.visitReadWriteKeyCommand(ctx, command);
}
}
class AnotherCollectionUpdateTestInterceptor extends DDAsyncInterceptor {
final CountDownLatch putFromLoadLatch;
final AtomicBoolean committing;
public AnotherCollectionUpdateTestInterceptor(CountDownLatch putFromLoadLatch, AtomicBoolean committing) {
this.putFromLoadLatch = putFromLoadLatch;
this.committing = committing;
}
@Override
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable {
if (committing.get() && !command.hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT)) {
putFromLoadLatch.countDown();
}
return super.visitReadWriteKeyCommand(ctx, command);
}
}
protected void assertSingleEmpty() {
Map contents = Caches.entrySet(entityCache).toMap();
Object value;
assertEquals(1, contents.size());
value = contents.get(itemId);
assertEquals(VersionedEntry.class, value.getClass());
assertNull(((VersionedEntry) value).getValue());
}
}
| 13,603
| 35.767568
| 139
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/InvalidationTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.hibernate.PessimisticLockException;
import org.hibernate.testing.TestForIssue;
import org.infinispan.AdvancedCache;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Item;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.junit.Test;
/**
* Tests specific to invalidation mode caches
*
* @author Radim Vansa <rvansa@redhat.com>
*/
public class InvalidationTest extends SingleNodeTest {
static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(InvalidationTest.class);
@Override
public List<Object[]> getParameters() {
return Arrays.asList(TRANSACTIONAL, READ_WRITE_INVALIDATION);
}
@Override
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(TestRegionFactory.PENDING_PUTS_SIMPLE, false);
}
@Test
@TestForIssue(jiraKey = "HHH-9868")
public void testConcurrentRemoveAndPutFromLoad() throws Exception {
final Item item = new Item( "chris", "Chris's Item" );
withTxSession(s -> {
s.persist(item);
});
Phaser deletePhaser = new Phaser(2);
Phaser getPhaser = new Phaser(2);
HookInterceptor hook = new HookInterceptor();
AdvancedCache pendingPutsCache = getPendingPutsCache(Item.class);
extractInterceptorChain(pendingPutsCache).addInterceptor(hook, 0);
AtomicBoolean getThreadBlockedInDB = new AtomicBoolean(false);
Thread deleteThread = new Thread(() -> {
try {
withTxSession(s -> {
Item loadedItem = s.get(Item.class, item.getId());
assertNotNull(loadedItem);
arriveAndAwait(deletePhaser, 2000);
arriveAndAwait(deletePhaser, 2000);
log.trace("Item loaded");
s.delete(loadedItem);
s.flush();
log.trace("Item deleted");
// start get-thread here
arriveAndAwait(deletePhaser, 2000);
// we need longer timeout since in non-MVCC DBs the get thread
// can be blocked
arriveAndAwait(deletePhaser, 4000);
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}, "delete-thread");
Thread getThread = new Thread(() -> {
try {
withTxSession(s -> {
// DB load should happen before the record is deleted,
// putFromLoad should happen after deleteThread ends
Item loadedItem = s.get(Item.class, item.getId());
if (getThreadBlockedInDB.get()) {
assertNull(loadedItem);
} else {
assertNotNull(loadedItem);
}
});
} catch (PessimisticLockException e) {
// If we end up here, database locks guard us against situation tested
// in this case and HHH-9868 cannot happen.
// (delete-thread has ITEMS table write-locked and we try to acquire read-lock)
try {
arriveAndAwait(getPhaser, 2000);
arriveAndAwait(getPhaser, 2000);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}, "get-thread");
deleteThread.start();
// deleteThread loads the entity
arriveAndAwait(deletePhaser, 2000);
withTx(() -> {
sessionFactory().getCache().evictEntityData(Item.class, item.getId());
assertFalse(sessionFactory().getCache().containsEntity(Item.class, item.getId()));
return null;
});
arriveAndAwait(deletePhaser, 2000);
// delete thread invalidates PFER
arriveAndAwait(deletePhaser, 2000);
// get thread gets the entity from DB
hook.block(getPhaser, getThread);
getThread.start();
try {
arriveAndAwait(getPhaser, 2000);
} catch (TimeoutException e) {
getThreadBlockedInDB.set(true);
}
arriveAndAwait(deletePhaser, 2000);
// delete thread finishes the remove from DB and cache
deleteThread.join();
hook.unblock();
arriveAndAwait(getPhaser, 2000);
// get thread puts the entry into cache
getThread.join();
assertNoInvalidators(pendingPutsCache);
withTxSession(s -> {
Item loadedItem = s.get(Item.class, item.getId());
assertNull(loadedItem);
});
}
protected AdvancedCache getSecondLevelCache(Class<?> entityClazz) {
InfinispanBaseRegion region = TEST_SESSION_ACCESS.getRegion(sessionFactory(), entityClazz.getName());
return region.getCache();
}
protected AdvancedCache getPendingPutsCache(Class<?> entityClazz) {
InfinispanBaseRegion region = TEST_SESSION_ACCESS.getRegion(sessionFactory(), entityClazz.getName());
AdvancedCache entityCache = region.getCache();
return entityCache.getCacheManager().getCache(
entityCache.getName() + "-" + InfinispanProperties.DEF_PENDING_PUTS_RESOURCE).getAdvancedCache();
}
protected static void arriveAndAwait(Phaser phaser, int timeout) throws TimeoutException, InterruptedException {
phaser.awaitAdvanceInterruptibly(phaser.arrive(), timeout, TimeUnit.MILLISECONDS);
}
@TestForIssue(jiraKey = "HHH-11304")
@Test
public void testFailedInsert() throws Exception {
AdvancedCache pendingPutsCache = getPendingPutsCache(Item.class);
assertNoInvalidators(pendingPutsCache);
withTxSession(s -> {
Item i = new Item("inserted", "bar");
s.persist(i);
s.flush();
s.getTransaction().markRollbackOnly();
});
assertNoInvalidators(pendingPutsCache);
}
@TestForIssue(jiraKey = "HHH-11304")
@Test
public void testFailedUpdate() throws Exception {
AdvancedCache pendingPutsCache = getPendingPutsCache(Item.class);
assertNoInvalidators(pendingPutsCache);
final Item item = new Item("before-update", "bar");
withTxSession(s -> s.persist(item));
withTxSession(s -> {
Item item2 = s.load(Item.class, item.getId());
assertEquals("before-update", item2.getName());
item2.setName("after-update");
s.persist(item2);
s.flush();
s.flush(); // workaround for HHH-11312
s.getTransaction().markRollbackOnly();
});
assertNoInvalidators(pendingPutsCache);
withTxSession(s -> {
Item item3 = s.load(Item.class, item.getId());
assertEquals("before-update", item3.getName());
s.delete(item3);
});
assertNoInvalidators(pendingPutsCache);
}
@TestForIssue(jiraKey = "HHH-11304")
@Test
public void testFailedRemove() throws Exception {
AdvancedCache pendingPutsCache = getPendingPutsCache(Item.class);
assertNoInvalidators(pendingPutsCache);
final Item item = new Item("before-remove", "bar");
withTxSession(s -> s.persist(item));
withTxSession(s -> {
Item item2 = s.load(Item.class, item.getId());
assertEquals("before-remove", item2.getName());
s.delete(item2);
s.flush();
s.getTransaction().markRollbackOnly();
});
assertNoInvalidators(pendingPutsCache);
withTxSession(s -> {
Item item3 = s.load(Item.class, item.getId());
assertEquals("before-remove", item3.getName());
s.delete(item3);
});
assertNoInvalidators(pendingPutsCache);
}
protected void assertNoInvalidators(AdvancedCache<Object, Object> pendingPutsCache) throws Exception {
Method getInvalidators = null;
for (Map.Entry<Object, Object> entry : pendingPutsCache.entrySet()) {
if (getInvalidators == null) {
getInvalidators = entry.getValue().getClass().getMethod("getInvalidators");
getInvalidators.setAccessible(true);
}
Collection invalidators = (Collection) getInvalidators.invoke(entry.getValue());
if (invalidators != null) {
assertTrue("Invalidators on key " + entry.getKey() + ": " + invalidators, invalidators.isEmpty());
}
}
}
static class HookInterceptor extends DDAsyncInterceptor {
Phaser phaser;
Thread thread;
public synchronized void block(Phaser phaser, Thread thread) {
this.phaser = phaser;
this.thread = thread;
}
public synchronized void unblock() {
phaser = null;
thread = null;
}
@Override
public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
Phaser phaser;
Thread thread;
synchronized (this) {
phaser = this.phaser;
thread = this.thread;
}
if (phaser != null && Thread.currentThread() == thread) {
arriveAndAwait(phaser, 2000);
arriveAndAwait(phaser, 2000);
}
return super.visitGetKeyValueCommand(ctx, command);
}
}
}
| 10,162
| 35.557554
| 115
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/AbstractNonInvalidationTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import org.hibernate.StaleStateException;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.spi.entry.CacheEntry;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
import org.infinispan.AdvancedCache;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.hibernate.cache.commons.util.Caches;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Item;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.util.ControlledTimeService;
import org.junit.After;
import org.junit.Before;
import jakarta.persistence.OptimisticLockException;
import jakarta.persistence.PessimisticLockException;
/**
* Common base for TombstoneTest and VersionedTest
*
* @author Radim Vansa <rvansa@redhat.com>
*/
public abstract class AbstractNonInvalidationTest extends SingleNodeTest {
protected static final int WAIT_TIMEOUT = 20; // seconds
protected static final ControlledTimeService TIME_SERVICE = new ControlledTimeService();
protected long TIMEOUT;
protected ExecutorService executor;
protected static InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(MethodHandles.lookup().lookupClass());
protected AdvancedCache entityCache;
protected long itemId;
protected InfinispanBaseRegion region;
protected long timeout;
protected final List<Runnable> cleanup = new ArrayList<>();
@BeforeClassOnce
public void setup() {
executor = Executors.newCachedThreadPool(new ThreadFactory() {
AtomicInteger counter = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "Executor-" + counter.incrementAndGet());
}
});
}
@AfterClassOnce
public void shutdown() {
executor.shutdown();
}
@Override
protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) {
// This applies to manually set LOCK_TIMEOUT for H2 DB. AvailableSettings.JPA_LOCK_TIMEOUT
// works only for queries, not for CRUDs, so we have to modify the connection URL.
// Alternative could be executing SET LOCK_TIMEOUT 100 as a native query.
String url = (String) ssrb.getSettings().get(AvailableSettings.URL);
if (url != null && url.contains("LOCK_TIMEOUT")) {
url = url.replaceAll("LOCK_TIMEOUT=[^;]*", "LOCK_TIMEOUT=100");
}
ssrb.applySetting(AvailableSettings.URL, url);
}
@Override
protected void startUp() {
super.startUp();
TestRegionFactory regionFactory = TestRegionFactoryProvider.load().wrap(sessionFactory().getCache().getRegionFactory());
TIMEOUT = regionFactory.getPendingPutsCacheConfiguration().expiration().maxIdle();
region = TEST_SESSION_ACCESS.getRegion(sessionFactory(), Item.class.getName());
entityCache = region.getCache();
}
@Before
public void insertAndClearCache() throws Exception {
region = TEST_SESSION_ACCESS.getRegion(sessionFactory(), Item.class.getName());
entityCache = region.getCache();
timeout = TestRegionFactoryProvider.load().findRegionFactory(sessionFactory().getCache())
.getPendingPutsCacheConfiguration().expiration().maxIdle();
Item item = new Item("my item", "Original item");
withTxSession(s -> s.persist(item));
entityCache.clear();
assertEquals("Cache is not empty", Collections.EMPTY_SET, entityCache.keySet());
itemId = item.getId();
log.info("Insert and clear finished");
}
@After
public void cleanup() throws Exception {
cleanup.forEach(Runnable::run);
cleanup.clear();
withTxSession(s -> {
TEST_SESSION_ACCESS.execQueryUpdate(s, "delete from Item");
});
}
protected Future<Boolean> removeFlushWait(long id, CyclicBarrier loadBarrier, CountDownLatch preFlushLatch, CountDownLatch flushLatch, CountDownLatch commitLatch) throws Exception {
return executor.submit(() -> withTxSessionApply(s -> {
try {
Item item = s.load(Item.class, id);
item.getName(); // force load & putFromLoad before the barrier
loadBarrier.await(WAIT_TIMEOUT, TimeUnit.SECONDS);
s.delete(item);
if (preFlushLatch != null) {
awaitOrThrow(preFlushLatch);
}
s.flush();
} catch (StaleStateException e) {
log.info("Exception thrown: ", e);
markRollbackOnly(s);
return false;
} catch (PessimisticLockException | org.hibernate.PessimisticLockException e) {
log.info("Exception thrown: ", e);
markRollbackOnly(s);
return false;
} finally {
if (flushLatch != null) {
flushLatch.countDown();
}
}
awaitOrThrow(commitLatch);
return true;
}));
}
protected Future<Boolean> updateFlushWait(long id, CyclicBarrier loadBarrier, CountDownLatch preFlushLatch, CountDownLatch flushLatch, CountDownLatch commitLatch) throws Exception {
return executor.submit(() -> withTxSessionApply(s -> {
try {
Item item = s.load(Item.class, id);
item.getName(); // force load & putFromLoad before the barrier
if (loadBarrier != null) {
loadBarrier.await(WAIT_TIMEOUT, TimeUnit.SECONDS);
}
item.setDescription("Updated item");
s.update(item);
if (preFlushLatch != null) {
awaitOrThrow(preFlushLatch);
}
s.flush();
} catch (StaleStateException | OptimisticLockException
| PessimisticLockException | org.hibernate.PessimisticLockException e) {
log.info("Exception thrown: ", e);
markRollbackOnly(s);
return false;
} finally {
if (flushLatch != null) {
flushLatch.countDown();
}
}
if (commitLatch != null) {
awaitOrThrow(commitLatch);
}
return true;
}));
}
protected Future<Boolean> evictWait(long id, CyclicBarrier loadBarrier, CountDownLatch preEvictLatch, CountDownLatch postEvictLatch) throws Exception {
return executor.submit(() -> {
try {
loadBarrier.await(WAIT_TIMEOUT, TimeUnit.SECONDS);
if (preEvictLatch != null) {
awaitOrThrow(preEvictLatch);
}
sessionFactory().getCache().evictEntityData(Item.class, id);
} finally {
if (postEvictLatch != null) {
postEvictLatch.countDown();
}
}
return true;
});
}
protected void awaitOrThrow(CountDownLatch latch) throws InterruptedException, TimeoutException {
if (!latch.await(WAIT_TIMEOUT, TimeUnit.SECONDS)) {
throw new TimeoutException();
}
}
@Override
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(TestRegionFactory.TIME_SERVICE, TIME_SERVICE);
}
protected void assertEmptyCache() {
assertNull(entityCache.get(itemId)); // force expiration
Map contents = Caches.entrySet(entityCache).toMap();
assertEquals(Collections.EMPTY_MAP, contents);
}
protected <T> T assertCacheContains(Class<T> expected) {
Map contents = Caches.entrySet(entityCache).toMap();
assertEquals("Cache does not have single element", 1, contents.size());
Object value = contents.get(itemId);
assertTrue(String.valueOf(value), expected.isInstance(value));
return (T) value;
}
protected Object assertSingleCacheEntry() {
return assertCacheContains(CacheEntry.class);
}
}
| 8,788
| 37.548246
| 184
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/EntitiesAndCollectionsInSameRegionTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.Hibernate;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.cache.internal.DefaultCacheKeysFactory;
import org.hibernate.cfg.Environment;
import org.hibernate.stat.CacheRegionStatistics;
import org.hibernate.stat.Statistics;
import org.hibernate.testing.TestForIssue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
/**
* @author Gail Badner
*/
public class EntitiesAndCollectionsInSameRegionTest extends SingleNodeTest {
private static final String REGION_NAME = "ARegion";
private final AnEntity anEntity;
private final AnotherEntity anotherEntity;
public EntitiesAndCollectionsInSameRegionTest() {
anEntity = new AnEntity();
anEntity.id = 1;
anEntity.valuesSet.add("abc");
anotherEntity = new AnotherEntity();
anotherEntity.id = 1;
anotherEntity.valuesSet.add(123);
}
@Override
public List<Object[]> getParameters() {
return getParameters(true, false, false, false, false);
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[]{
AnEntity.class,
AnotherEntity.class
};
}
@Override
@SuppressWarnings("unchecked")
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(Environment.CACHE_KEYS_FACTORY, DefaultCacheKeysFactory.SHORT_NAME);
}
@Before
public void setup() throws Exception {
final Statistics stats = sessionFactory().getStatistics();
stats.clear();
withTxSession(
s -> {
s.persist(anEntity);
s.persist(anotherEntity);
}
);
// Then entities should have been cached, but not their collections.
CacheRegionStatistics cacheStatistics = stats.getCacheRegionStatistics(REGION_NAME);
assertEquals(0, cacheStatistics.getMissCount());
assertEquals(0, cacheStatistics.getHitCount());
assertEquals(2, cacheStatistics.getPutCount());
stats.clear();
}
@After
public void cleanup() throws Exception {
withTxSession(
s -> {
s.delete(s.get(AnEntity.class, 1));
s.delete(s.get(AnotherEntity.class, 1));
}
);
}
@Test
@TestForIssue(jiraKey = "HHH-10418")
public void testEntitiesAndCollections() throws Exception {
final Statistics stats = sessionFactory().getStatistics();
stats.clear();
withTxSession(
s -> {
AnEntity anEntity1 = s.get(AnEntity.class, anEntity.id);
CacheRegionStatistics cacheStatistics = stats.getCacheRegionStatistics(REGION_NAME);
// anEntity1 was cached when it was persisted
assertEquals(0, cacheStatistics.getMissCount());
assertEquals(1, cacheStatistics.getHitCount());
assertEquals(0, cacheStatistics.getPutCount());
stats.clear();
assertFalse(Hibernate.isInitialized(anEntity1.valuesSet));
Hibernate.initialize(anEntity1.valuesSet);
// anEntity1.values gets cached when it gets loadead
cacheStatistics = stats.getCacheRegionStatistics(REGION_NAME);
assertEquals(1, cacheStatistics.getMissCount());
assertEquals(0, cacheStatistics.getHitCount());
assertEquals(1, cacheStatistics.getPutCount());
stats.clear();
AnotherEntity anotherEntity1 = s.get(AnotherEntity.class, anotherEntity.id);
// anotherEntity1 was cached when it was persisted
cacheStatistics = stats.getCacheRegionStatistics(REGION_NAME);
assertEquals(0, cacheStatistics.getMissCount());
assertEquals(1, cacheStatistics.getHitCount());
assertEquals(0, cacheStatistics.getPutCount());
stats.clear();
assertFalse(Hibernate.isInitialized(anotherEntity1.valuesSet));
Hibernate.initialize(anotherEntity1.valuesSet);
// anotherEntity1.values gets cached when it gets loadead
cacheStatistics = stats.getCacheRegionStatistics(REGION_NAME);
assertEquals(1, cacheStatistics.getMissCount());
assertEquals(0, cacheStatistics.getHitCount());
assertEquals(1, cacheStatistics.getPutCount());
}
);
// The entities and their collections should all be cached now.
withTxSession(
s -> {
stats.clear();
AnEntity anEntity1 = s.get(AnEntity.class, anEntity.id);
CacheRegionStatistics cacheStatistics = stats.getCacheRegionStatistics(REGION_NAME);
assertEquals(0, cacheStatistics.getMissCount());
assertEquals(1, cacheStatistics.getHitCount());
assertEquals(0, cacheStatistics.getPutCount());
stats.clear();
assertFalse(Hibernate.isInitialized(anEntity1.valuesSet));
Hibernate.initialize(anEntity1.valuesSet);
cacheStatistics = stats.getCacheRegionStatistics(REGION_NAME);
assertEquals(0, cacheStatistics.getMissCount());
assertEquals(1, cacheStatistics.getHitCount());
assertEquals(0, cacheStatistics.getPutCount());
assertEquals(anEntity.valuesSet, anEntity1.valuesSet);
stats.clear();
AnotherEntity anotherEntity1 = s.get(AnotherEntity.class, anotherEntity.id);
cacheStatistics = stats.getCacheRegionStatistics(REGION_NAME);
assertEquals(0, cacheStatistics.getMissCount());
assertEquals(1, cacheStatistics.getHitCount());
assertEquals(0, cacheStatistics.getPutCount());
stats.clear();
assertFalse(Hibernate.isInitialized(anotherEntity1.valuesSet));
Hibernate.initialize(anotherEntity1.valuesSet);
cacheStatistics = stats.getCacheRegionStatistics(REGION_NAME);
assertEquals(0, cacheStatistics.getMissCount());
assertEquals(1, cacheStatistics.getHitCount());
assertEquals(0, cacheStatistics.getPutCount());
assertEquals(anotherEntity.valuesSet, anotherEntity1.valuesSet);
}
);
}
@Entity(name = "AnEntity")
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL, region = REGION_NAME)
public static class AnEntity {
@Id
private int id;
@ElementCollection
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL, region = REGION_NAME)
private Set<String> valuesSet = new HashSet<>();
}
@Entity(name = "AnotherEntity")
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL, region = REGION_NAME)
public static class AnotherEntity {
@Id
private int id;
@ElementCollection
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL, region = REGION_NAME)
private Set<Integer> valuesSet = new HashSet<>();
}
}
| 7,297
| 30.868996
| 96
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/BulkOperationsTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.stat.CacheRegionStatistics;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Contact;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Customer;
import org.infinispan.test.hibernate.cache.commons.util.InfinispanTestingSetup;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.util.ControlledTimeService;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
/**
* BulkOperationsTestCase.
*
* @author Galder Zamarreño
* @since 3.5
*/
public class BulkOperationsTest extends SingleNodeTest {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(BulkOperationsTest.class);
private static final ControlledTimeService TIME_SERVICE = new AlwaysMoveForwardTimeService();
@Rule
public TestName name = new TestName();
@Override
public List<Object[]> getParameters() {
return getParameters(true, true, false, true, true);
}
@ClassRule
public static final InfinispanTestingSetup infinispanTestIdentifier = new InfinispanTestingSetup();
@Override
protected String getBaseForMappings() {
return "org/infinispan/test/";
}
@Override
public String[] getMappings() {
return new String[] {
"hibernate/cache/commons/functional/entities/Contact.hbm.xml",
"hibernate/cache/commons/functional/entities/Customer.hbm.xml"
};
}
@Override
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(TestRegionFactory.TIME_SERVICE, TIME_SERVICE);
}
@Test
public void testBulkOperations() throws Throwable {
log.infof("*** %s", name.getMethodName());
boolean cleanedUp = false;
try {
createContacts();
List<Integer> rhContacts = getContactsByCustomer("Red Hat");
assertNotNull("Red Hat contacts exist", rhContacts);
assertEquals("Created expected number of Red Hat contacts", 10, rhContacts.size());
CacheRegionStatistics contactSlcs = sessionFactory()
.getStatistics()
.getCacheRegionStatistics(Contact.class.getName());
assertEquals(20, contactSlcs.getElementCountInMemory());
assertEquals("Deleted all Red Hat contacts", 10, deleteContacts());
assertEquals(0, contactSlcs.getElementCountInMemory());
List<Integer> jbContacts = getContactsByCustomer("JBoss");
assertNotNull("JBoss contacts exist", jbContacts);
assertEquals("JBoss contacts remain", 10, jbContacts.size());
for (Integer id : rhContacts) {
assertNull("Red Hat contact " + id + " cannot be retrieved", getContact(id));
}
rhContacts = getContactsByCustomer("Red Hat");
if (rhContacts != null) {
assertEquals("No Red Hat contacts remain", 0, rhContacts.size());
}
updateContacts("Kabir", "Updated");
assertEquals(0, contactSlcs.getElementCountInMemory());
// Advance so that invalidation can be seen as past and data can be loaded
TIME_SERVICE.advance(1);
for (Integer id : jbContacts) {
Contact contact = getContact(id);
assertNotNull("JBoss contact " + id + " exists", contact);
String expected = ("Kabir".equals(contact.getName())) ? "Updated" : "2222";
assertEquals("JBoss contact " + id + " has correct TLF", expected, contact.getTlf());
}
List<Integer> updated = getContactsByTLF("Updated");
assertNotNull("Got updated contacts", updated);
assertEquals("Updated contacts", 5, updated.size());
assertEquals(10, contactSlcs.getElementCountInMemory());
updateContactsWithOneManual("Kabir", "UpdatedAgain");
// In the other types the
assertEquals((accessType == AccessType.TRANSACTIONAL ||
(accessType == AccessType.READ_WRITE && cacheMode == CacheMode.INVALIDATION_SYNC)) ? 1 : 0,
contactSlcs.getElementCountInMemory());
for (Integer id : jbContacts) {
Contact contact = getContact(id);
assertNotNull("JBoss contact " + id + " exists", contact);
String expected = ("Kabir".equals(contact.getName())) ? "UpdatedAgain" : "2222";
assertEquals("JBoss contact " + id + " has correct TLF", expected, contact.getTlf());
}
updated = getContactsByTLF("UpdatedAgain");
assertNotNull("Got updated contacts", updated);
assertEquals("Updated contacts", 5, updated.size());
}
catch (Throwable t) {
cleanedUp = true;
cleanup( true );
throw t;
}
finally {
// cleanup the db so we can run this test multiple times w/o restarting the cluster
if ( !cleanedUp ) {
cleanup( false );
}
}
}
public void createContacts() throws Exception {
withTxSession(s -> {
for ( int i = 0; i < 10; i++ ) {
Customer c = createCustomer( i );
s.persist(c);
}
});
}
public int deleteContacts() throws Exception {
String deleteHQL = "delete Contact where customer in "
+ " (select customer FROM Customer as customer where customer.name = :cName)";
int rowsAffected = withTxSessionApply(s ->
TEST_SESSION_ACCESS.execQueryUpdateAutoFlush(s, deleteHQL, new String[]{"cName", "Red Hat"}));
return rowsAffected;
}
@SuppressWarnings( {"unchecked"})
public List<Integer> getContactsByCustomer(String customerName) throws Exception {
String selectHQL = "select contact.id from Contact contact"
+ " where contact.customer.name = :cName";
return (List<Integer>) withTxSessionApply(s ->
TEST_SESSION_ACCESS.execQueryListAutoFlush(s, selectHQL, new String[]{"cName", customerName}));
}
@SuppressWarnings( {"unchecked"})
public List<Integer> getContactsByTLF(String tlf) throws Exception {
String selectHQL = "select contact.id from Contact contact"
+ " where contact.tlf = :cTLF";
return (List<Integer>) withTxSessionApply(s ->
TEST_SESSION_ACCESS.execQueryListAutoFlush(s, selectHQL, new String[]{"cTLF", tlf}));
}
public int updateContacts(String name, String newTLF) throws Exception {
String updateHQL = "update Contact set tlf = :cNewTLF where name = :cName";
return withTxSessionApply(s ->
TEST_SESSION_ACCESS.execQueryUpdateAutoFlush(s, updateHQL,
new String[]{"cNewTLF", newTLF},
new String[]{"cName", name}));
}
public int updateContactsWithOneManual(String name, String newTLF) throws Exception {
String queryHQL = "from Contact c where c.name = :cName";
String updateHQL = "update Contact set tlf = :cNewTLF where name = :cName";
return withTxSessionApply(s -> {
List<Contact> list = TEST_SESSION_ACCESS.execQueryList(s, queryHQL, new String[]{"cName", name});
list.get(0).setTlf(newTLF);
return TEST_SESSION_ACCESS.execQueryUpdateAutoFlush(s, updateHQL,
new String[]{"cNewTLF", newTLF},
new String[]{"cName", name});
});
}
public Contact getContact(Integer id) throws Exception {
return withTxSessionApply(s -> s.get( Contact.class, id ));
}
public void cleanup(boolean ignore) throws Exception {
String deleteContactHQL = "delete from Contact";
String deleteCustomerHQL = "delete from Customer";
withTxSession(s -> {
TEST_SESSION_ACCESS.execQueryUpdateAutoFlush(s, deleteContactHQL);
TEST_SESSION_ACCESS.execQueryUpdateAutoFlush(s, deleteCustomerHQL);
});
}
private Customer createCustomer(int id) throws Exception {
log.trace("CREATE CUSTOMER " + id);
try {
Customer customer = new Customer();
customer.setName( (id % 2 == 0) ? "JBoss" : "Red Hat" );
Set<Contact> contacts = new HashSet<Contact>();
Contact kabir = new Contact();
kabir.setCustomer( customer );
kabir.setName( "Kabir" );
kabir.setTlf( "1111" );
contacts.add( kabir );
Contact bill = new Contact();
bill.setCustomer( customer );
bill.setName( "Bill" );
bill.setTlf( "2222" );
contacts.add( bill );
customer.setContacts( contacts );
return customer;
}
finally {
log.trace("CREATE CUSTOMER " + id + " - END");
}
}
/**
* A time service that whenever you ask it for the time, it moves the clock forward.
*
* This time service guarantees that after a session timestamp has been generated,
* the next time the region is invalidated and the time is checked, this time is forward in time.
*
* By doing that, we can guarantee that when a region is invalidated in same session,
* the region invalidation timestamp will be in the future and we avoid potential invalid things being added to second level cache.
* More info can be found in {@link org.infinispan.hibernate.cache.commons.access.FutureUpdateSynchronization}.
*/
static final class AlwaysMoveForwardTimeService extends ControlledTimeService {
@Override
public long wallClockTime() {
advance(1);
return super.wallClockTime();
}
}
}
| 9,445
| 33.985185
| 134
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/ConcurrentWriteTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
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 java.util.concurrent.TimeUnit;
import org.hibernate.LockMode;
import org.hibernate.stat.CacheRegionStatistics;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Contact;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Customer;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.util.ControlledTimeService;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author nikita_tovstoles@mba.berkeley.edu
* @author Galder Zamarreño
*/
public class ConcurrentWriteTest extends SingleNodeTest {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( ConcurrentWriteTest.class );
/**
* when USER_COUNT==1, tests pass, when >4 tests fail
*/
private static final int USER_COUNT = 5;
private static final int ITERATION_COUNT = 150;
private static final int THINK_TIME_MILLIS = 10;
private static final long LAUNCH_INTERVAL_MILLIS = 10;
private static final Random random = new Random();
private static final ControlledTimeService TIME_SERVICE = new ControlledTimeService();
/**
* kill switch used to stop all users when one fails
*/
private static volatile boolean TERMINATE_ALL_USERS = false;
/**
* collection of IDs of all customers participating in this test
*/
private Set<Integer> customerIDs = new HashSet<Integer>();
@Override
public List<Object[]> getParameters() {
return getParameters(true, true, false, true, true);
}
@Override
protected void prepareTest() throws Exception {
super.prepareTest();
TERMINATE_ALL_USERS = false;
}
@Override
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(TestRegionFactory.TIME_SERVICE, TIME_SERVICE);
}
@Override
protected void cleanupTest() throws Exception {
try {
super.cleanupTest();
}
finally {
cleanup();
}
}
@Test
public void testPingDb() throws Exception {
withTxSession(s -> TEST_SESSION_ACCESS.execQueryList(s, "from " + Customer.class.getName()));
}
@Test
public void testSingleUser() throws Exception {
// setup
sessionFactory().getStatistics().clear();
// wait a while to make sure that timestamp comparison works after invalidateRegion
TIME_SERVICE.advance(1);
Customer customer = createCustomer( 0 );
final Integer customerId = customer.getId();
getCustomerIDs().add( customerId );
// wait a while to make sure that timestamp comparison works after collection remove (during insert)
TIME_SERVICE.advance(1);
assertNull( "contact exists despite not being added", getFirstContact( customerId ) );
// check that cache was hit
CacheRegionStatistics customerSlcs = sessionFactory()
.getStatistics()
.getCacheRegionStatistics(Customer.class.getName());
assertEquals( 1, customerSlcs.getPutCount() );
assertEquals( 1, customerSlcs.getElementCountInMemory() );
assertEquals( 1, TEST_SESSION_ACCESS.getRegion(sessionFactory(), Customer.class.getName()).getElementCountInMemory());
log.infof( "Add contact to customer {0}", customerId );
String contactsRegionName = Customer.class.getName() + ".contacts";
CacheRegionStatistics contactsCollectionSlcs = sessionFactory()
.getStatistics()
.getCacheRegionStatistics(contactsRegionName);
assertEquals( 1, contactsCollectionSlcs.getPutCount() );
assertEquals( 1, contactsCollectionSlcs.getElementCountInMemory() );
assertEquals( 1, TEST_SESSION_ACCESS.getRegion(sessionFactory(), contactsRegionName).getElementCountInMemory());
final Contact contact = addContact( customerId );
assertNotNull( "contact returned by addContact is null", contact );
assertEquals(
"Customer.contacts cache was not invalidated after addContact", 0,
contactsCollectionSlcs.getElementCountInMemory()
);
assertNotNull( "Contact missing after successful add call", getFirstContact( customerId ) );
// read everyone's contacts
readEveryonesFirstContact();
removeContact( customerId );
assertNull( "contact still exists after successful remove call", getFirstContact( customerId ) );
}
// Ignoring the test as it's more of a stress-test: this should be enabled manually
@Ignore
@Test
public void testManyUsers() throws Throwable {
try {
// setup - create users
for ( int i = 0; i < USER_COUNT; i++ ) {
Customer customer = createCustomer( 0 );
getCustomerIDs().add( customer.getId() );
}
assertEquals( "failed to create enough Customers", USER_COUNT, getCustomerIDs().size() );
final ExecutorService executor = Executors.newFixedThreadPool( USER_COUNT );
CyclicBarrier barrier = new CyclicBarrier( USER_COUNT + 1 );
List<Future<Void>> futures = new ArrayList<Future<Void>>( USER_COUNT );
for ( Integer customerId : getCustomerIDs() ) {
Future<Void> future = executor.submit( new UserRunner( customerId, barrier ) );
futures.add( future );
Thread.sleep( LAUNCH_INTERVAL_MILLIS ); // rampup
}
barrier.await( 2, TimeUnit.MINUTES ); // wait for all threads to finish
log.info( "All threads finished, let's shutdown the executor and check whether any exceptions were reported" );
for ( Future<Void> future : futures ) {
future.get();
}
executor.shutdown();
log.info( "All future gets checked" );
}
catch (Throwable t) {
log.error( "Error running test", t );
throw t;
}
}
public void cleanup() throws Exception {
getCustomerIDs().clear();
String deleteContactHQL = "delete from Contact";
String deleteCustomerHQL = "delete from Customer";
withTxSession(s -> {
TEST_SESSION_ACCESS.execQueryUpdateAutoFlush(s, deleteContactHQL);
TEST_SESSION_ACCESS.execQueryUpdateAutoFlush(s, deleteCustomerHQL);
});
}
private Customer createCustomer(int nameSuffix) throws Exception {
return withTxSessionApply(s -> {
Customer customer = new Customer();
customer.setName( "customer_" + nameSuffix );
customer.setContacts( new HashSet<Contact>() );
s.persist( customer );
return customer;
});
}
/**
* read first contact of every Customer participating in this test. this forces concurrent cache
* writes of Customer.contacts Collection cache node
*
* @return who cares
* @throws java.lang.Exception
*/
private void readEveryonesFirstContact() throws Exception {
withTxSession(s -> {
for ( Integer customerId : getCustomerIDs() ) {
if ( TERMINATE_ALL_USERS ) {
markRollbackOnly(s);
return;
}
Customer customer = s.load( Customer.class, customerId );
Set<Contact> contacts = customer.getContacts();
if ( !contacts.isEmpty() ) {
contacts.iterator().next();
}
}
});
}
/**
* -load existing Customer -get customer's contacts; return 1st one
*
* @param customerId
* @return first Contact or null if customer has none
*/
private Contact getFirstContact(Integer customerId) throws Exception {
assert customerId != null;
return withTxSessionApply(s -> {
Customer customer = s.load(Customer.class, customerId);
Set<Contact> contacts = customer.getContacts();
Contact firstContact = contacts.isEmpty() ? null : contacts.iterator().next();
if (TERMINATE_ALL_USERS) {
markRollbackOnly(s);
}
return firstContact;
});
}
/**
* -load existing Customer -create a new Contact and add to customer's contacts
*
* @param customerId
* @return added Contact
*/
private Contact addContact(Integer customerId) throws Exception {
assert customerId != null;
return withTxSessionApply(s -> {
final Customer customer = s.load(Customer.class, customerId);
Contact contact = new Contact();
contact.setName("contact name");
contact.setTlf("wtf is tlf?");
contact.setCustomer(customer);
customer.getContacts().add(contact);
// assuming contact is persisted via cascade from customer
if (TERMINATE_ALL_USERS) {
markRollbackOnly(s);
}
return contact;
});
}
/**
* remove existing 'contact' from customer's list of contacts
*
* @param customerId
* @throws IllegalStateException
* if customer does not own a contact
*/
private void removeContact(Integer customerId) throws Exception {
assert customerId != null;
withTxSession(s -> {
Customer customer = s.load( Customer.class, customerId );
Set<Contact> contacts = customer.getContacts();
if ( contacts.size() != 1 ) {
throw new IllegalStateException(
"can't remove contact: customer id=" + customerId
+ " expected exactly 1 contact, " + "actual count=" + contacts.size()
);
}
Contact contact = contacts.iterator().next();
// H2 version 1.3 (without MVCC fails with deadlock on Contacts/Customers modification, therefore,
// we have to enforce locking Contacts first
s.lock(contact, LockMode.PESSIMISTIC_WRITE);
contacts.remove( contact );
contact.setCustomer( null );
// explicitly delete Contact because hbm has no 'DELETE_ORPHAN' cascade?
// getEnvironment().getSessionFactory().getCurrentSession().delete(contact); //appears to
// not be needed
// assuming contact is persisted via cascade from customer
if ( TERMINATE_ALL_USERS ) {
markRollbackOnly(s);
}
});
}
/**
* @return the customerIDs
*/
public Set<Integer> getCustomerIDs() {
return customerIDs;
}
private String statusOfRunnersToString(Set<UserRunner> runners) {
assert runners != null;
StringBuilder sb = new StringBuilder(
"TEST CONFIG [userCount=" + USER_COUNT
+ ", iterationsPerUser=" + ITERATION_COUNT + ", thinkTimeMillis="
+ THINK_TIME_MILLIS + "] " + " STATE of UserRunners: "
);
for ( UserRunner r : runners ) {
sb.append( r.toString() ).append( System.lineSeparator() );
}
return sb.toString();
}
class UserRunner implements Callable<Void> {
private final CyclicBarrier barrier;
final private Integer customerId;
private int completedIterations = 0;
private Throwable causeOfFailure;
public UserRunner(Integer cId, CyclicBarrier barrier) {
assert cId != null;
this.customerId = cId;
this.barrier = barrier;
}
private boolean contactExists() throws Exception {
return getFirstContact( customerId ) != null;
}
public Void call() throws Exception {
// name this thread for easier log tracing
Thread.currentThread().setName( "UserRunnerThread-" + getCustomerId() );
log.info( "Wait for all executions paths to be ready to perform calls" );
try {
for ( int i = 0; i < ITERATION_COUNT && !TERMINATE_ALL_USERS; i++ ) {
contactExists();
log.trace( "Add contact for customer " + customerId );
addContact( customerId );
log.trace( "Added contact" );
thinkRandomTime();
contactExists();
thinkRandomTime();
log.trace( "Read all customers' first contact" );
// read everyone's contacts
readEveryonesFirstContact();
log.trace( "Read completed" );
thinkRandomTime();
log.trace( "Remove contact of customer" + customerId );
removeContact( customerId );
log.trace( "Removed contact" );
contactExists();
thinkRandomTime();
++completedIterations;
log.tracef( "Iteration completed %d", completedIterations );
}
}
catch (Throwable t) {
TERMINATE_ALL_USERS = true;
log.error( "Error", t );
throw new Exception( t );
}
finally {
log.info( "Wait for all execution paths to finish" );
barrier.await();
}
return null;
}
public boolean isSuccess() {
return ITERATION_COUNT == getCompletedIterations();
}
public int getCompletedIterations() {
return completedIterations;
}
public Throwable getCauseOfFailure() {
return causeOfFailure;
}
public Integer getCustomerId() {
return customerId;
}
@Override
public String toString() {
return super.toString() + "[customerId=" + getCustomerId() + " iterationsCompleted="
+ getCompletedIterations() + " completedAll=" + isSuccess() + " causeOfFailure="
+ (this.causeOfFailure != null ? getStackTrace( causeOfFailure ) : "") + "] ";
}
}
public static String getStackTrace(Throwable throwable) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter( sw, true );
throwable.printStackTrace( pw );
return sw.getBuffer().toString();
}
/**
* sleep between 0 and THINK_TIME_MILLIS.
*
* @throws RuntimeException if sleep is interrupted or TERMINATE_ALL_USERS flag was set to true i n the
* meantime
*/
private void thinkRandomTime() {
try {
Thread.sleep( random.nextInt( THINK_TIME_MILLIS ) );
}
catch (InterruptedException ex) {
throw new RuntimeException( "sleep interrupted", ex );
}
if ( TERMINATE_ALL_USERS ) {
throw new RuntimeException( "told to terminate (because a UserRunner had failed)" );
}
}
}
| 13,661
| 30.551963
| 121
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/NaturalIdOnManyToOne.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import org.hibernate.annotations.NaturalId;
import org.hibernate.annotations.NaturalIdCache;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Transient;
@Entity
@NaturalIdCache
/**
* Test case for NaturalId annotation - ANN-750
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
public class NaturalIdOnManyToOne {
@Id
@GeneratedValue
int id;
@Transient
long version;
@NaturalId
@ManyToOne
Citizen citizen;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public Citizen getCitizen() {
return citizen;
}
public void setCitizen(Citizen citizen) {
this.citizen = citizen;
}
}
| 1,205
| 18.451613
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/WithSimpleId.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import jakarta.persistence.Cacheable;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
/**
* The class should be in a package that is different from the test
* so that the test does not have access to the private ID field.
*
* @author Gail Badner
*/
@Entity
@Cacheable
public class WithSimpleId {
@Id
private Long id;
}
| 656
| 25.28
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/WithEmbeddedId.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import jakarta.persistence.Cacheable;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
/**
* The class should be in a package that is different from the test
* so that the test does not have access to the private embedded ID.
*
* @author Gail Badner
*/
@Entity
@Cacheable
public class WithEmbeddedId {
@EmbeddedId
private PK embeddedId;
}
| 683
| 26.36
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/AccountHolder.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
/**
* Comment
*
* @author Brian Stansberry
*/
public class AccountHolder implements Serializable {
private static final long serialVersionUID = 1L;
private String lastName;
private String ssn;
private transient boolean deserialized;
public AccountHolder() {
this("Stansberry", "123-456-7890");
}
public AccountHolder(String lastName, String ssn) {
this.lastName = lastName;
this.ssn = ssn;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof AccountHolder))
return false;
AccountHolder pk = (AccountHolder) obj;
if (!lastName.equals(pk.lastName))
return false;
if (!ssn.equals(pk.ssn))
return false;
return true;
}
@Override
public int hashCode() {
int result = 17;
result = result * 31 + lastName.hashCode();
result = result * 31 + ssn.hashCode();
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getClass().getName());
sb.append("[lastName=");
sb.append(lastName);
sb.append(",ssn=");
sb.append(ssn);
sb.append(",deserialized=");
sb.append(deserialized);
sb.append("]");
return sb.toString();
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
deserialized = true;
}
}
| 1,956
| 20.744444
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/OtherItem.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import java.util.ArrayList;
import java.util.List;
/**
* @author Gail Badner
*/
public class OtherItem {
private Long id;
// mapping added programmatically
private long version;
private String name;
private Item favoriteItem;
private List<Item> bagOfItems = new ArrayList<Item>();
public OtherItem() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Item getFavoriteItem() {
return favoriteItem;
}
public void setFavoriteItem(Item favoriteItem) {
this.favoriteItem = favoriteItem;
}
public List<Item> getBagOfItems() {
return bagOfItems;
}
public void setBagOfItems(List<Item> bagOfItems) {
this.bagOfItems = bagOfItems;
}
public void addItemToBag(Item item) {
bagOfItems.add( item );
item.getOtherItems().add( this );
}
}
| 1,350
| 18.028169
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/Citizen.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import org.hibernate.annotations.NaturalId;
import org.hibernate.annotations.NaturalIdCache;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Transient;
/**
* @author Emmanuel Bernard
*/
@Entity
@NaturalIdCache
public class Citizen {
@Id
@GeneratedValue
private Integer id;
@Transient
private long version;
private String firstname;
private String lastname;
@NaturalId
@ManyToOne
private State state;
@NaturalId
private String ssn;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
}
| 1,587
| 17.045455
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/Person.java
|
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import java.io.Serializable;
import jakarta.persistence.Cacheable;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Transient;
/**
* Test class using EmbeddedId
*
* @author Radim Vansa <rvansa@redhat.com>
*/
@Entity
@Cacheable
public class Person implements Serializable {
@EmbeddedId
Name name;
int age;
@Transient
long version;
public Person() {}
public Person(String firstName, String lastName, int age) {
name = new Name(firstName, lastName);
this.age = age;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
}
| 1,045
| 17.350877
| 72
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/Contact.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import java.io.Serializable;
/**
* Entity that has a many-to-one relationship to a Customer
*
* @author Galder Zamarreño
* @since 3.5
*/
public class Contact implements Serializable {
Integer id;
String name;
String tlf;
Customer customer;
// mapping added programmatically
long version;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTlf() {
return tlf;
}
public void setTlf(String tlf) {
this.tlf = tlf;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Contact))
return false;
Contact c = (Contact) o;
return c.id.equals(id) && c.name.equals(name) && c.tlf.equals(tlf);
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (id == null ? 0 : id.hashCode());
result = 31 * result + name.hashCode();
result = 31 * result + tlf.hashCode();
return result;
}
}
| 1,615
| 18.238095
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/Account.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import java.io.Serializable;
/**
* Comment
*
* @author Brian Stansberry
*/
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private long version;
private AccountHolder accountHolder;
private Integer balance;
private String branch;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public AccountHolder getAccountHolder() {
return accountHolder;
}
public void setAccountHolder(AccountHolder accountHolder) {
this.accountHolder = accountHolder;
}
public Integer getBalance() {
return balance;
}
public void setBalance(Integer balance) {
this.balance = balance;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Account))
return false;
Account acct = (Account) obj;
if (!safeEquals(id, acct.id))
return false;
if (!safeEquals(branch, acct.branch))
return false;
if (!safeEquals(balance, acct.balance))
return false;
if (!safeEquals(accountHolder, acct.accountHolder))
return false;
return true;
}
@Override
public int hashCode() {
int result = 17;
result = result * 31 + safeHashCode(id);
result = result * 31 + safeHashCode(branch);
result = result * 31 + safeHashCode(balance);
result = result * 31 + safeHashCode(accountHolder);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getClass().getName());
sb.append("[id=");
sb.append(id);
sb.append(",branch=");
sb.append(branch);
sb.append(",balance=");
sb.append(balance);
sb.append(",accountHolder=");
sb.append(accountHolder);
sb.append("]");
return sb.toString();
}
private static int safeHashCode(Object obj) {
return obj == null ? 0 : obj.hashCode();
}
private static boolean safeEquals(Object a, Object b) {
return (a == b || (a != null && a.equals(b)));
}
}
| 2,479
| 20.196581
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/VersionedItem.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
/**
* @author Steve Ebersole
*/
public class VersionedItem {
private Long id;
private Long version;
private String name;
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 1,006
| 18.365385
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/PK.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import java.io.Serializable;
/**
* This class should be in a package that is different from the test
* so that the test and entity that uses this class for its primary
* key does not have access to private field.
*
* @author Gail Badner
*/
public class PK implements Serializable {
private Long id;
public PK() {
}
public PK(Long id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
PK pk = (PK) o;
return !( id != null ? !id.equals( pk.id ) : pk.id != null );
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
| 1,010
| 20.0625
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/Age.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
/**
* @author Galder Zamarreño
*/
@NamedQueries({@NamedQuery(name=Age.QUERY, query = "SELECT a FROM Age a")})
@Entity
public class Age {
public static final String QUERY = "Age.findAll";
@Id
@GeneratedValue
private Integer id;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
| 976
| 20.711111
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/Customer.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import java.io.Serializable;
import java.util.Set;
/**
* Company customer
*
* @author Emmanuel Bernard
* @author Kabir Khan
*/
public class Customer implements Serializable {
Integer id;
String name;
// mapping added programmatically
long version;
private transient Set<Contact> contacts;
public Customer() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String string) {
name = string;
}
public Set<Contact> getContacts() {
return contacts;
}
public void setContacts(Set<Contact> contacts) {
this.contacts = contacts;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
}
| 1,101
| 17.366667
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/Name.java
|
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import java.io.Serializable;
import jakarta.persistence.Embeddable;
/**
* Test class with incorrectly defined equals and hashCode.
*
* @author Radim Vansa <rvansa@redhat.com>
*/
@Embeddable
public class Name implements Serializable {
String firstName;
String lastName;
public Name() {}
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object obj) {
return false;
}
}
| 981
| 18.64
| 72
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/Item.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Gavin King
*/
public class Item {
private Long id;
// mapping for version is added programmatically
private long version;
private String name;
private String description;
private Item owner;
private Set<Item> items = new HashSet<Item>( );
private Item bagOwner;
private List<Item> bagOfItems = new ArrayList<Item>( );
private Set<OtherItem> otherItems = new HashSet<OtherItem>( );
public Item() {}
public Item( String name, String description ) {
this.name = name;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Item getOwner() {
return owner;
}
public void setOwner( Item owner ) {
this.owner = owner;
}
public Set<Item> getItems() {
return items;
}
public void setItems( Set<Item> items ) {
this.items = items;
}
public void addItem( Item item ) {
item.setOwner( this );
getItems().add( item );
}
public Item getBagOwner() {
return bagOwner;
}
public void setBagOwner( Item bagOwner ) {
this.bagOwner = bagOwner;
}
public List<Item> getBagOfItems() {
return bagOfItems;
}
public void setBagOfItems( List<Item> bagOfItems ) {
this.bagOfItems = bagOfItems;
}
public void addItemToBag( Item item ) {
item.setBagOwner( this );
getBagOfItems().add( item );
}
public Set<OtherItem> getOtherItems() {
return otherItems;
}
public void setOtherItems(Set<OtherItem> otherItems) {
this.otherItems = otherItems;
}
public void addOtherItem(OtherItem otherItem) {
getOtherItems().add( otherItem );
otherItem.getBagOfItems().add( this );
}
}
| 2,425
| 18.723577
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/entities/State.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.infinispan.test.hibernate.cache.commons.functional.entities;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Transient;
/**
* @author Emmanuel Bernard
*/
@Entity
public class State {
@Id
@GeneratedValue
private Integer id;
@Transient
private long version;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 955
| 17.745098
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/classloader/SelectedClassnameClassLoader.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.classloader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.jboss.logging.Logger;
/**
* A ClassLoader that loads classes whose classname begins with one of a given set of strings, without attempting first to delegate
* to its parent loader.
* <p>
* This class is intended to allow emulation of 2 different types of common J2EE classloading situations.
* <ul>
* <li>Servlet-style child-first classloading, where this class is the child loader.</li>
* <li>Parent-first classloading where the parent does not have access to certain classes</li>
* </ul>
* </p>
* <p>
* This class can also be configured to raise a ClassNotFoundException if asked to load certain classes, thus allowing classes on
* the classpath to be hidden from a test environment.
* </p>
*
* @author Brian Stansberry
*/
public class SelectedClassnameClassLoader extends ClassLoader {
private static final Logger log = Logger.getLogger( SelectedClassnameClassLoader.class );
private String[] includedClasses = null;
private String[] excludedClasses = null;
private String[] notFoundClasses = null;
private Map<String, Class> classes = new java.util.HashMap<String, Class>();
/**
* Creates a new classloader that loads the given classes.
*
* @param includedClasses array of class or package names that should be directly loaded by this loader. Classes whose name
* starts with any of the strings in this array will be loaded by this class, unless their name appears in
* <code>excludedClasses</code>. Can be <code>null</code>
* @param excludedClasses array of class or package names that should NOT be directly loaded by this loader. Loading of classes
* whose name starts with any of the strings in this array will be delegated to <code>parent</code>, even if the classes
* package or classname appears in <code>includedClasses</code>. Typically this parameter is used to exclude loading one
* or more classes in a package whose other classes are loaded by this object.
* @param parent ClassLoader to which loading of classes should be delegated if necessary
*/
public SelectedClassnameClassLoader( String[] includedClasses,
String[] excludedClasses,
ClassLoader parent ) {
this(includedClasses, excludedClasses, null, parent);
}
/**
* Creates a new classloader that loads the given classes.
*
* @param includedClasses array of class or package names that should be directly loaded by this loader. Classes whose name
* starts with any of the strings in this array will be loaded by this class, unless their name appears in
* <code>excludedClasses</code>. Can be <code>null</code>
* @param excludedClasses array of class or package names that should NOT be directly loaded by this loader. Loading of classes
* whose name starts with any of the strings in this array will be delegated to <code>parent</code>, even if the classes
* package or classname appears in <code>includedClasses</code>. Typically this parameter is used to exclude loading one
* or more classes in a package whose other classes are loaded by this object.
* @param notFoundClasses array of class or package names for which this should raise a ClassNotFoundException
* @param parent ClassLoader to which loading of classes should be delegated if necessary
*/
public SelectedClassnameClassLoader( String[] includedClasses,
String[] excludedClasses,
String[] notFoundClasses,
ClassLoader parent ) {
super(parent);
this.includedClasses = includedClasses;
this.excludedClasses = excludedClasses;
this.notFoundClasses = notFoundClasses;
log.debug("created " + this);
}
@Override
protected synchronized Class<?> loadClass( String name,
boolean resolve ) throws ClassNotFoundException {
log.trace("loadClass(" + name + "," + resolve + ")");
if (isIncluded(name) && (isExcluded(name) == false)) {
Class c = findClass(name);
if (resolve) {
resolveClass(c);
}
return c;
} else if (isNotFound(name)) {
throw new ClassNotFoundException(name + " is discarded");
} else {
return super.loadClass(name, resolve);
}
}
@Override
protected Class<?> findClass( String name ) throws ClassNotFoundException {
log.trace("findClass(" + name + ")");
Class result = classes.get(name);
if (result != null) {
return result;
}
if (isIncluded(name) && (isExcluded(name) == false)) {
result = createClass(name);
} else if (isNotFound(name)) {
throw new ClassNotFoundException(name + " is discarded");
} else {
result = super.findClass(name);
}
classes.put(name, result);
return result;
}
protected Class createClass( String name ) throws ClassFormatError, ClassNotFoundException {
log.info("createClass(" + name + ")");
try {
InputStream is = getResourceAsStream(name.replace('.', '/').concat(".class"));
byte[] bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
int read;
while ((read = is.read(bytes)) > -1) {
baos.write(bytes, 0, read);
}
bytes = baos.toByteArray();
return this.defineClass(name, bytes, 0, bytes.length);
} catch (FileNotFoundException e) {
throw new ClassNotFoundException("cannot find " + name, e);
} catch (IOException e) {
throw new ClassNotFoundException("cannot read " + name, e);
}
}
protected boolean isIncluded( String className ) {
if (includedClasses != null) {
for (int i = 0; i < includedClasses.length; i++) {
if (className.startsWith(includedClasses[i])) {
return true;
}
}
}
return false;
}
protected boolean isExcluded( String className ) {
if (excludedClasses != null) {
for (int i = 0; i < excludedClasses.length; i++) {
if (className.startsWith(excludedClasses[i])) {
return true;
}
}
}
return false;
}
protected boolean isNotFound( String className ) {
if (notFoundClasses != null) {
for (int i = 0; i < notFoundClasses.length; i++) {
if (className.startsWith(notFoundClasses[i])) {
return true;
}
}
}
return false;
}
@Override
public String toString() {
String s = getClass().getName();
s += "[includedClasses=";
s += listClasses(includedClasses);
s += ";excludedClasses=";
s += listClasses(excludedClasses);
s += ";notFoundClasses=";
s += listClasses(notFoundClasses);
s += ";parent=";
s += getParent();
s += "]";
return s;
}
private static String listClasses( String[] classes ) {
if (classes == null) return null;
String s = "";
for (int i = 0; i < classes.length; i++) {
if (i > 0) s += ",";
s += classes[i];
}
return s;
}
}
| 8,151
| 38.004785
| 131
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/PartialFutureUpdateTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.hibernate.cache.commons.util.FutureUpdate;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.interceptors.AsyncInterceptor;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Customer;
import static org.junit.Assert.assertEquals;
public class PartialFutureUpdateTest extends AbstractPartialUpdateTest {
@Override
protected boolean doUpdate() throws Exception {
withTxSession(localFactory, s -> {
Customer customer = s.load(Customer.class, 1);
assertEquals("JBoss", customer.getName());
customer.setName(customer.getName() + ", a division of Red Hat");
s.update(customer);
});
return true;
}
@Override
AsyncInterceptor getFailureInducingInterceptor() {
return new FailureInducingInterceptor();
}
public static class FailureInducingInterceptor extends BaseCustomAsyncInterceptor {
static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(FailureInducingInterceptor.class);
int remoteInvocationCount;
@Override
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable {
log.tracef("Invoked insert/update: %s", command);
if (!ctx.isOriginLocal()) {
remoteInvocationCount++;
log.tracef("Remote invocation count: %d ", remoteInvocationCount);
if (command.getKey().toString().endsWith("#1")
&& remoteInvocationCount == 4
&& command.getFunction() instanceof FutureUpdate) {
throw new AbstractPartialUpdateTest.InducedException("Simulate failure when FutureUpdate received");
}
}
return super.visitReadWriteKeyCommand(ctx, command);
}
}
}
| 2,107
| 35.344828
| 123
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/EntityCollectionInvalidationTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.testing.TestForIssue;
import org.infinispan.AdvancedCache;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commons.util.Util;
import org.infinispan.context.InvocationContext;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.hibernate.cache.commons.access.PutFromLoadValidator;
import org.infinispan.hibernate.cache.commons.util.FutureUpdate;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited;
import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Contact;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Customer;
import org.infinispan.test.hibernate.cache.commons.util.ExpectingInterceptor;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import org.infinispan.util.ControlledTimeService;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
/**
* EntityCollectionInvalidationTestCase.
*
* @author Galder Zamarreño
* @since 3.5
*/
public class EntityCollectionInvalidationTest extends DualNodeTest {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( EntityCollectionInvalidationTest.class );
private static final Integer CUSTOMER_ID = new Integer( 1 );
private static final TestSessionAccess TEST_SESSION_ACCESS = TestSessionAccess.findTestSessionAccess();
private EmbeddedCacheManager localManager, remoteManager;
private AdvancedCache localCustomerCache, remoteCustomerCache;
private AdvancedCache localContactCache, remoteContactCache;
private AdvancedCache localCollectionCache, remoteCollectionCache;
private MyListener localListener, remoteListener;
private SessionFactoryImplementor localFactory, remoteFactory;
private final ControlledTimeService timeService = new ControlledTimeService();
private InfinispanBaseRegion localCustomerRegion, remoteCustomerRegion;
private InfinispanBaseRegion localCollectionRegion, remoteCollectionRegion;
private InfinispanBaseRegion localContactRegion, remoteContactRegion;
@Rule
public TestName name = new TestName();
@Override
public List<Object[]> getParameters() {
return getParameters(true, true, false, true, true);
}
@Override
public void startUp() {
super.startUp();
// Bind a listener to the "local" cache
// Our region factory makes its CacheManager available to us
localManager = ClusterAware.getCacheManager( DualNodeTest.LOCAL );
// Cache localCache = localManager.getCache("entity");
localCustomerCache = localManager.getCache( Customer.class.getName() ).getAdvancedCache();
localContactCache = localManager.getCache( Contact.class.getName() ).getAdvancedCache();
localCollectionCache = localManager.getCache( Customer.class.getName() + ".contacts" ).getAdvancedCache();
localListener = new MyListener( "local" );
localCustomerCache.addListener( localListener );
localContactCache.addListener( localListener );
localCollectionCache.addListener( localListener );
// Bind a listener to the "remote" cache
remoteManager = ClusterAware.getCacheManager( DualNodeTest.REMOTE );
remoteCustomerCache = remoteManager.getCache( Customer.class.getName() ).getAdvancedCache();
remoteContactCache = remoteManager.getCache( Contact.class.getName() ).getAdvancedCache();
remoteCollectionCache = remoteManager.getCache( Customer.class.getName() + ".contacts" ).getAdvancedCache();
remoteListener = new MyListener( "remote" );
remoteCustomerCache.addListener( remoteListener );
remoteContactCache.addListener( remoteListener );
remoteCollectionCache.addListener( remoteListener );
localFactory = sessionFactory();
localCustomerRegion = TEST_SESSION_ACCESS.getRegion(localFactory, Customer.class.getName());
localContactRegion = TEST_SESSION_ACCESS.getRegion(localFactory, Contact.class.getName());
localCollectionRegion = TEST_SESSION_ACCESS.getRegion(localFactory, Customer.class.getName() + ".contacts");
remoteFactory = secondNodeEnvironment().getSessionFactory();
remoteCustomerRegion = TEST_SESSION_ACCESS.getRegion(remoteFactory, Customer.class.getName());
remoteContactRegion = TEST_SESSION_ACCESS.getRegion(remoteFactory, Contact.class.getName());
remoteCollectionRegion = TEST_SESSION_ACCESS.getRegion(remoteFactory, Customer.class.getName() + ".contacts");
}
@Override
public void shutDown() {
cleanupTransactionManagement();
}
@Override
protected void cleanupTest() throws Exception {
cleanup(localFactory);
localListener.clear();
remoteListener.clear();
// do not call super.cleanupTest becasue we would clean transaction managers
}
@Override
protected void addSettings(Map settings) {
super.addSettings(settings);
settings.put(TestRegionFactory.PENDING_PUTS_SIMPLE, false);
settings.put(TestRegionFactory.TIME_SERVICE, timeService);
}
@Test
public void testAll() throws Exception {
log.infof(name.getMethodName());
assertEmptyCaches();
assertTrue( remoteListener.isEmpty() );
assertTrue( localListener.isEmpty() );
log.debug( "Create node 0" );
IdContainer ids = createCustomer( localFactory );
assertTrue( remoteListener.isEmpty() );
assertTrue( localListener.isEmpty() );
// The create customer above removes the collection from the cache (see CollectionRecreateAction)
// and therefore the putFromLoad in getCustomer could be considered stale if executed too soon.
timeService.advance(1);
CountDownLatch remoteCollectionLoadLatch = null;
if (!cacheMode.isInvalidation()) {
remoteCollectionLoadLatch = new CountDownLatch(1);
ExpectingInterceptor.get(remoteCollectionCache)
.when((ctx, cmd) -> cmd instanceof ReadWriteKeyCommand)
.countDown(remoteCollectionLoadLatch);
}
log.debug( "Find node 0" );
// This actually brings the collection into the cache
getCustomer( ids.customerId, localFactory );
// Now the collection is in the cache so, the 2nd "get"
// should read everything from the cache
log.debug( "Find(2) node 0" );
localListener.clear();
getCustomer( ids.customerId, localFactory );
// Check the read came from the cache
log.debug( "Check cache 0" );
assertLoadedFromCache( localListener, ids.customerId, ids.contactIds );
if (remoteCollectionLoadLatch != null) {
log.debug( "Wait for remote collection put from load to complete" );
assertTrue(remoteCollectionLoadLatch.await(2, TimeUnit.SECONDS));
ExpectingInterceptor.cleanup(remoteCollectionCache);
}
log.debug( "Find node 1" );
// This actually brings the collection into the cache since invalidation is in use
getCustomer( ids.customerId, remoteFactory );
// Now the collection is in the cache so, the 2nd "get"
// should read everything from the cache
log.debug( "Find(2) node 1" );
remoteListener.clear();
getCustomer( ids.customerId, remoteFactory );
// Check the read came from the cache
log.debug( "Check cache 1" );
assertLoadedFromCache( remoteListener, ids.customerId, ids.contactIds );
// Modify customer in remote
remoteListener.clear();
CountDownLatch modifyLatch = null;
if (!cacheMode.isInvalidation() && accessType != AccessType.NONSTRICT_READ_WRITE) {
modifyLatch = new CountDownLatch(1);
ExpectingInterceptor.get(localCustomerCache).when(this::isFutureUpdate).countDown(modifyLatch);
}
ids = modifyCustomer( ids.customerId, remoteFactory );
assertLoadedFromCache( remoteListener, ids.customerId, ids.contactIds );
if (modifyLatch != null) {
assertTrue(modifyLatch.await(2, TimeUnit.SECONDS));
ExpectingInterceptor.cleanup(localCustomerCache);
}
assertEquals( 0, localCollectionRegion.getElementCountInMemory());
if (cacheMode.isInvalidation()) {
// After modification, local cache should have been invalidated and hence should be empty
assertEquals(0, localCustomerRegion.getElementCountInMemory());
} else {
// Replicated cache is updated, not invalidated
assertEquals(1, localCustomerRegion.getElementCountInMemory());
}
}
@TestForIssue(jiraKey = "HHH-9881")
@Test
public void testConcurrentLoadAndRemoval() throws Exception {
if (!remoteCustomerCache.getCacheConfiguration().clustering().cacheMode().isInvalidation()) {
// This test is tailored for invalidation-based strategies, using pending puts cache
return;
}
AtomicReference<Exception> getException = new AtomicReference<>();
AtomicReference<Exception> deleteException = new AtomicReference<>();
Phaser getPhaser = new Phaser(2);
HookInterceptor hookInterceptor = new HookInterceptor(getException);
AdvancedCache remotePPCache = remoteCustomerCache.getCacheManager().getCache(
remoteCustomerCache.getName() + "-" + InfinispanProperties.DEF_PENDING_PUTS_RESOURCE).getAdvancedCache();
extractInterceptorChain(remotePPCache).addInterceptor(hookInterceptor, 0);
IdContainer idContainer = new IdContainer();
withTxSession(localFactory, s -> {
Customer customer = new Customer();
customer.setName( "JBoss" );
s.persist(customer);
idContainer.customerId = customer.getId();
});
// start loading
Thread getThread = new Thread(() -> {
try {
withTxSession(remoteFactory, s -> {
s.get(Customer.class, idContainer.customerId);
});
} catch (Exception e) {
log.error("Failure to get customer", e);
getException.set(e);
}
}, "get-thread");
Thread deleteThread = new Thread(() -> {
try {
withTxSession(localFactory, s -> {
Customer customer = s.get(Customer.class, idContainer.customerId);
s.delete(customer);
});
} catch (Exception e) {
log.error("Failure to delete customer", e);
deleteException.set(e);
}
}, "delete-thread");
// get thread should block on the beginning of PutFromLoadValidator#acquirePutFromLoadLock
hookInterceptor.block(getPhaser, getThread);
getThread.start();
arriveAndAwait(getPhaser);
deleteThread.start();
deleteThread.join();
hookInterceptor.unblock();
arriveAndAwait(getPhaser);
getThread.join();
if (getException.get() != null) {
throw new IllegalStateException("get-thread failed", getException.get());
}
if (deleteException.get() != null) {
throw new IllegalStateException("delete-thread failed", deleteException.get());
}
Customer localCustomer = getCustomer(idContainer.customerId, localFactory);
assertNull(localCustomer);
Customer remoteCustomer = getCustomer(idContainer.customerId, remoteFactory);
assertNull(remoteCustomer);
assertTrue(remoteCustomerCache.isEmpty());
}
protected void assertEmptyCaches() {
assertEquals(0, localCustomerRegion.getElementCountInMemory());
assertEquals(0, localContactRegion.getElementCountInMemory());
assertEquals(0, localCollectionRegion.getElementCountInMemory());
assertEquals(0, remoteCustomerRegion.getElementCountInMemory());
assertEquals(0, remoteContactRegion.getElementCountInMemory());
assertEquals(0, remoteCollectionRegion.getElementCountInMemory());
}
private IdContainer createCustomer(SessionFactory sessionFactory)
throws Exception {
log.debug( "CREATE CUSTOMER" );
Customer customer = new Customer();
customer.setName("JBoss");
Set<Contact> contacts = new HashSet<Contact>();
Contact kabir = new Contact();
kabir.setCustomer(customer);
kabir.setName("Kabir");
kabir.setTlf("1111");
contacts.add(kabir);
Contact bill = new Contact();
bill.setCustomer(customer);
bill.setName("Bill");
bill.setTlf("2222");
contacts.add(bill);
customer.setContacts(contacts);
ArrayList<Runnable> cleanup = new ArrayList<>();
CountDownLatch customerLatch = new CountDownLatch(1);
CountDownLatch collectionLatch = new CountDownLatch(1);
CountDownLatch contactsLatch = new CountDownLatch(2);
if (cacheMode.isInvalidation()) {
cleanup.add(mockValidator(remoteCustomerCache, customerLatch));
cleanup.add(mockValidator(remoteCollectionCache, collectionLatch));
cleanup.add(mockValidator(remoteContactCache, contactsLatch));
} else if (accessType == AccessType.NONSTRICT_READ_WRITE) {
// ATM nonstrict mode has sync after-invalidation update
Stream.of(customerLatch, collectionLatch, contactsLatch, contactsLatch).forEach(l -> l.countDown());
} else {
ExpectingInterceptor.get(remoteCustomerCache).when(this::isFutureUpdate).countDown(collectionLatch);
ExpectingInterceptor.get(remoteCollectionCache).when(this::isFutureUpdate).countDown(customerLatch);
ExpectingInterceptor.get(remoteContactCache).when(this::isFutureUpdate).countDown(contactsLatch);
cleanup.add(() -> ExpectingInterceptor.cleanup(remoteCustomerCache, remoteCollectionCache, remoteContactCache));
}
withTxSession(sessionFactory, session -> session.save(customer));
assertTrue(customerLatch.await(2, TimeUnit.SECONDS));
assertTrue(collectionLatch.await(2, TimeUnit.SECONDS));
assertTrue(contactsLatch.await(2, TimeUnit.SECONDS));
cleanup.forEach(Runnable::run);
IdContainer ids = new IdContainer();
ids.customerId = customer.getId();
Set contactIds = new HashSet();
contactIds.add( kabir.getId() );
contactIds.add( bill.getId() );
ids.contactIds = contactIds;
log.debug( "CREATE CUSTOMER - END" );
return ids;
}
private boolean isFutureUpdate(InvocationContext ctx, VisitableCommand cmd) {
return cmd instanceof ReadWriteKeyCommand && ((ReadWriteKeyCommand) cmd).getFunction() instanceof FutureUpdate;
}
private Runnable mockValidator(AdvancedCache cache, CountDownLatch latch) {
PutFromLoadValidator originalValidator = PutFromLoadValidator.removeFromCache(cache);
PutFromLoadValidator mockValidator = spy(originalValidator);
doAnswer(invocation -> {
try {
return invocation.callRealMethod();
} finally {
latch.countDown();
}
}).when(mockValidator).endInvalidatingKey(any(), any());
PutFromLoadValidator.addToCache(cache, mockValidator);
return () -> {
PutFromLoadValidator.removeFromCache(cache);
PutFromLoadValidator.addToCache(cache, originalValidator);
};
}
private Customer getCustomer(Integer id, SessionFactory sessionFactory) throws Exception {
log.debug( "Find customer with id=" + id );
return withTxSessionApply(sessionFactory, session -> doGetCustomer(id, session));
}
private Customer doGetCustomer(Integer id, Session session) throws Exception {
Customer customer = session.get( Customer.class, id );
if (customer == null) {
return null;
}
// Access all the contacts
Set<Contact> contacts = customer.getContacts();
if (contacts != null) {
for (Iterator it = contacts.iterator(); it.hasNext(); ) {
((Contact) it.next()).getName();
}
}
return customer;
}
private IdContainer modifyCustomer(Integer id, SessionFactory sessionFactory)
throws Exception {
log.debug( "Modify customer with id=" + id );
return withTxSessionApply(sessionFactory, session -> {
IdContainer ids = new IdContainer();
Set contactIds = new HashSet();
Customer customer = doGetCustomer( id, session );
customer.setName( "NewJBoss" );
ids.customerId = customer.getId();
Set<Contact> contacts = customer.getContacts();
for ( Contact c : contacts ) {
contactIds.add( c.getId() );
}
Contact contact = contacts.iterator().next();
contacts.remove( contact );
contactIds.remove( contact.getId() );
ids.contactIds = contactIds;
contact.setCustomer( null );
session.save( customer );
return ids;
});
}
private void cleanup(SessionFactory sessionFactory) throws Exception {
withTxSession(sessionFactory, session -> {
Customer c = (Customer) session.get(Customer.class, CUSTOMER_ID);
if (c != null) {
Set contacts = c.getContacts();
for (Iterator it = contacts.iterator(); it.hasNext(); ) {
session.delete(it.next());
}
c.setContacts(null);
session.delete(c);
}
// since we don't use orphan removal, some contacts may persist
for (Contact contact : session.createQuery("from Contact", Contact.class).getResultList()) {
session.delete(contact);
}
});
}
private void assertLoadedFromCache(MyListener listener, Integer custId, Set contactIds) {
assertTrue("Customer#" + custId + " was in cache", listener.visited.contains("Customer#" + custId));
for ( Iterator it = contactIds.iterator(); it.hasNext(); ) {
Integer contactId = (Integer) it.next();
assertTrue("Contact#" + contactId + " was in cache", listener.visited.contains("Contact#" + contactId));
}
assertTrue("Customer.contacts" + custId + " was in cache", listener.visited.contains( "Customer.contacts#" + custId ));
}
protected static void arriveAndAwait(Phaser phaser) throws TimeoutException, InterruptedException {
try {
phaser.awaitAdvanceInterruptibly(phaser.arrive(), 10, TimeUnit.SECONDS);
} catch (TimeoutException e) {
log.error("Failed to progress: " + Util.threadDump());
throw e;
}
}
@Listener
public static class MyListener {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( MyListener.class );
private Set<String> visited = ConcurrentHashMap.newKeySet();
private final String name;
public MyListener(String name) {
this.name = name;
}
public void clear() {
visited.clear();
}
public boolean isEmpty() {
return visited.isEmpty();
}
@CacheEntryVisited
public void nodeVisited(CacheEntryVisitedEvent event) {
log.debug( event.toString() );
if ( !event.isPre() ) {
String key = event.getCache().getName() + "#" + event.getKey();
log.debug( "MyListener[" + name + "] - Visiting key " + key );
// String name = fqn.toString();
String token = ".entities.";
int index = key.indexOf( token );
if ( index > -1 ) {
index += token.length();
key = key.substring( index );
log.debug( "MyListener[" + this.name + "] - recording visit to " + key );
visited.add( key );
}
}
}
}
private class IdContainer {
Integer customerId;
Set<Integer> contactIds;
}
static class HookInterceptor extends DDAsyncInterceptor {
final AtomicReference<Exception> failure;
Phaser phaser;
Thread thread;
private HookInterceptor(AtomicReference<Exception> failure) {
this.failure = failure;
}
public synchronized void block(Phaser phaser, Thread thread) {
this.phaser = phaser;
this.thread = thread;
}
public synchronized void unblock() {
phaser = null;
thread = null;
}
@Override
public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
try {
Phaser phaser;
Thread thread;
synchronized (this) {
phaser = this.phaser;
thread = this.thread;
}
if (phaser != null && Thread.currentThread() == thread) {
arriveAndAwait(phaser);
arriveAndAwait(phaser);
}
} catch (Exception e) {
failure.set(e);
throw e;
} finally {
return super.visitGetKeyValueCommand(ctx, command);
}
}
}
}
| 20,787
| 36.055258
| 134
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/AccountDAO.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import static org.infinispan.test.hibernate.cache.commons.util.TxUtil.withTxSession;
import static org.infinispan.test.hibernate.cache.commons.util.TxUtil.withTxSessionApply;
import java.util.Iterator;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Account;
import org.infinispan.test.hibernate.cache.commons.functional.entities.AccountHolder;
/**
* @author Brian Stansberry
*/
public class AccountDAO {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(AccountDAO.class);
private final boolean useJta;
private final SessionFactory sessionFactory;
private AccountHolder smith = new AccountHolder("Smith", "1000");
private AccountHolder jones = new AccountHolder("Jones", "2000");
private AccountHolder barney = new AccountHolder("Barney", "3000");
public AccountDAO(boolean useJta, SessionFactory sessionFactory) throws Exception {
this.useJta = useJta;
this.sessionFactory = sessionFactory;
}
public AccountHolder getSmith() {
return smith;
}
public AccountHolder getJones() {
return jones;
}
public AccountHolder getBarney() {
return barney;
}
public void updateAccountBranch(Integer id, String branch) throws Exception {
withTxSession(useJta, sessionFactory, session -> {
log.debug("Updating account " + id + " to branch " + branch);
Account account = session.get(Account.class, id);
log.debug("Set branch " + branch);
account.setBranch(branch);
session.update(account);
log.debug("Updated account " + id + " to branch " + branch);
});
}
public int getCountForBranch(String branch, boolean useRegion) throws Exception {
return withTxSessionApply(useJta, sessionFactory, session -> {
Query query = session.createQuery(
"select account from Account as account where account.branch = :branch");
query.setParameter("branch", branch);
if (useRegion) {
query.setCacheRegion("AccountRegion");
}
query.setCacheable(true);
return query.list().size();
});
}
public void createAccount(AccountHolder holder, Integer id, Integer openingBalance, String branch) throws Exception {
withTxSession(useJta, sessionFactory, session -> {
log.debug("Creating account " + id);
Account account = new Account();
account.setId(id);
account.setAccountHolder(holder);
account.setBalance(openingBalance);
log.debug("Set branch " + branch);
account.setBranch(branch);
session.persist(account);
log.debug("Created account " + id);
});
}
public Account getAccount(Integer id) throws Exception {
return withTxSessionApply(useJta, sessionFactory, session -> {
log.debug("Getting account " + id);
return session.get(Account.class, id);
});
}
public Account getAccountWithRefresh(Integer id) throws Exception {
return withTxSessionApply(useJta, sessionFactory, session -> {
log.debug("Getting account " + id + " with refresh");
Account acct = session.get(Account.class, id);
session.refresh(acct);
return session.get(Account.class, id);
});
}
public void updateAccountBalance(Integer id, Integer newBalance) throws Exception {
withTxSession(useJta, sessionFactory, session -> {
log.debug("Updating account " + id + " to balance " + newBalance);
Account account = session.get(Account.class, id);
account.setBalance(newBalance);
session.update(account);
log.debug("Updated account " + id + " to balance " + newBalance);
});
}
public String getBranch(Object holder, boolean useRegion) throws Exception {
return withTxSessionApply(useJta, sessionFactory, session -> {
Query query = session.createQuery(
"select account.branch from Account as account where account.accountHolder = ?");
query.setParameter(0, holder);
if (useRegion) {
query.setCacheRegion("AccountRegion");
}
query.setCacheable(true);
return (String) query.list().get(0);
});
}
public int getTotalBalance(AccountHolder holder, boolean useRegion) throws Exception {
List results = (List) withTxSessionApply(useJta, sessionFactory, session -> {
Query query = session.createQuery(
"select account.balance from Account as account where account.accountHolder = ?");
query.setParameter(0, holder);
if (useRegion) {
query.setCacheRegion("AccountRegion");
}
query.setCacheable(true);
return query.list();
});
int total = 0;
if (results != null) {
for (Iterator it = results.iterator(); it.hasNext();) {
total += ((Integer) it.next()).intValue();
System.out.println("Total = " + total);
}
}
return total;
}
public void cleanup() throws Exception {
internalCleanup();
}
private void internalCleanup() throws Exception {
withTxSession(useJta, sessionFactory, session -> {
Query query = session.createQuery("select account from Account as account");
List accts = query.list();
if (accts != null) {
for (Iterator it = accts.iterator(); it.hasNext(); ) {
try {
Object acct = it.next();
log.info("Removing " + acct);
session.delete(acct);
} catch (Exception ignored) {
}
}
}
});
}
public void remove() {
try {
internalCleanup();
} catch (Exception e) {
log.error("Caught exception in remove", e);
}
}
}
| 5,713
| 31.101124
| 118
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/DualNodeJtaTransactionManagerImpl.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import java.util.Hashtable;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.InvalidTransactionException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
/**
* Variant of SimpleJtaTransactionManagerImpl that doesn't use a VM-singleton, but rather a set of
* impls keyed by a node id.
*
* TODO: Merge with single node transaction manager as much as possible
*
* @author Brian Stansberry
*/
public class DualNodeJtaTransactionManagerImpl implements TransactionManager {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(DualNodeJtaTransactionManagerImpl.class);
private static final Hashtable INSTANCES = new Hashtable();
private ThreadLocal currentTransaction = new ThreadLocal();
private String nodeId;
public synchronized static DualNodeJtaTransactionManagerImpl getInstance(String nodeId) {
DualNodeJtaTransactionManagerImpl tm = (DualNodeJtaTransactionManagerImpl) INSTANCES
.get(nodeId);
if (tm == null) {
tm = new DualNodeJtaTransactionManagerImpl(nodeId);
INSTANCES.put(nodeId, tm);
}
return tm;
}
public synchronized static void cleanupTransactions() {
for (java.util.Iterator it = INSTANCES.values().iterator(); it.hasNext();) {
TransactionManager tm = (TransactionManager) it.next();
try {
tm.suspend();
} catch (Exception e) {
log.error("Exception cleaning up TransactionManager " + tm);
}
}
}
public synchronized static void cleanupTransactionManagers() {
INSTANCES.clear();
}
private DualNodeJtaTransactionManagerImpl(String nodeId) {
this.nodeId = nodeId;
}
public int getStatus() throws SystemException {
Transaction tx = getCurrentTransaction();
return tx == null ? Status.STATUS_NO_TRANSACTION : tx.getStatus();
}
public Transaction getTransaction() throws SystemException {
return (Transaction) currentTransaction.get();
}
public DualNodeJtaTransactionImpl getCurrentTransaction() {
return (DualNodeJtaTransactionImpl) currentTransaction.get();
}
public void begin() throws NotSupportedException, SystemException {
currentTransaction.set(new DualNodeJtaTransactionImpl(this));
}
public Transaction suspend() throws SystemException {
DualNodeJtaTransactionImpl suspended = getCurrentTransaction();
log.trace(nodeId + ": Suspending " + suspended + " for thread "
+ Thread.currentThread().getName());
currentTransaction.set(null);
return suspended;
}
public void resume(Transaction transaction) throws InvalidTransactionException,
IllegalStateException, SystemException {
currentTransaction.set(transaction);
log.trace(nodeId + ": Resumed " + transaction + " for thread "
+ Thread.currentThread().getName());
}
public void commit() throws RollbackException, HeuristicMixedException,
HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
Transaction tx = getCurrentTransaction();
if (tx == null) {
throw new IllegalStateException("no current transaction to commit");
}
tx.commit();
}
public void rollback() throws IllegalStateException, SecurityException, SystemException {
Transaction tx = getCurrentTransaction();
if (tx == null) {
throw new IllegalStateException("no current transaction");
}
tx.rollback();
}
public void setRollbackOnly() throws IllegalStateException, SystemException {
Transaction tx = getCurrentTransaction();
if (tx == null) {
throw new IllegalStateException("no current transaction");
}
tx.setRollbackOnly();
}
public void setTransactionTimeout(int i) throws SystemException {
}
void endCurrent(DualNodeJtaTransactionImpl transaction) {
if (transaction == currentTransaction.get()) {
currentTransaction.set(null);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getClass().getName());
sb.append("[nodeId=");
sb.append(nodeId);
sb.append("]");
return sb.toString();
}
}
| 4,947
| 33.361111
| 135
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/NaturalIdInvalidationTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.jpa.QueryHints;
import org.hibernate.query.criteria.HibernateCriteriaBuilder;
import org.hibernate.query.criteria.JpaCriteriaQuery;
import org.infinispan.Cache;
import org.infinispan.commons.test.categories.Smoke;
import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.manager.CacheContainer;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Citizen;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Citizen_;
import org.infinispan.test.hibernate.cache.commons.functional.entities.NaturalIdOnManyToOne;
import org.infinispan.test.hibernate.cache.commons.functional.entities.State;
import org.infinispan.test.hibernate.cache.commons.functional.entities.State_;
import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess;
import org.jboss.util.collection.ConcurrentSet;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
/**
* // TODO: Document this
*
* @author Galder Zamarreño
*/
@Category(Smoke.class)
public class NaturalIdInvalidationTest extends DualNodeTest {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(NaturalIdInvalidationTest.class);
protected static final TestSessionAccess TEST_SESSION_ACCESS = TestSessionAccess.findTestSessionAccess();
@Rule
public TestName name = new TestName();
@Override
public List<Object[]> getParameters() {
return getParameters(true, true, true, true, true);
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {
Citizen.class, State.class,
NaturalIdOnManyToOne.class
};
}
@Test
public void testAll() throws Exception {
log.infof("*** %s", name.getMethodName());
// Bind a listener to the "local" cache
// Our region factory makes its CacheManager available to us
CacheContainer localManager = ClusterAware.getCacheManager(DualNodeTest.LOCAL);
Cache localNaturalIdCache = localManager.getCache(Citizen.class.getName() + "##NaturalId");
MyListener localListener = new MyListener( "local" );
localNaturalIdCache.addListener(localListener);
// Bind a listener to the "remote" cache
CacheContainer remoteManager = ClusterAware.getCacheManager(DualNodeTest.REMOTE);
Cache remoteNaturalIdCache = remoteManager.getCache(Citizen.class.getName() + "##NaturalId");
MyListener remoteListener = new MyListener( "remote" );
remoteNaturalIdCache.addListener(remoteListener);
SessionFactoryImplementor localFactory = sessionFactory();
InfinispanBaseRegion localNaturalIdRegion = TEST_SESSION_ACCESS.getRegion(localFactory, Citizen.class.getName() + "##NaturalId");
SessionFactory remoteFactory = secondNodeEnvironment().getSessionFactory();
try {
assertTrue(remoteListener.isEmpty());
assertTrue(localListener.isEmpty());
CountDownLatch remoteUpdateLatch = getRemoteUpdateLatch(remoteNaturalIdCache);
saveSomeCitizens(localFactory);
assertTrue(await(remoteUpdateLatch));
assertTrue(remoteListener.isEmpty());
assertTrue(localListener.isEmpty());
log.debug("Find node 0");
// This actually brings the collection into the cache
getCitizenWithCriteria(localFactory);
// Now the collection is in the cache so, the 2nd "get"
// should read everything from the cache
log.debug( "Find(2) node 0" );
localListener.clear();
getCitizenWithCriteria(localFactory);
// Check the read came from the cache
log.debug( "Check cache 0" );
assertLoadedFromCache(localListener, "1234");
log.debug( "Find node 1" );
// This actually brings the collection into the cache since invalidation is in use
getCitizenWithCriteria(remoteFactory);
// Now the collection is in the cache so, the 2nd "get"
// should read everything from the cache
log.debug( "Find(2) node 1" );
remoteListener.clear();
getCitizenWithCriteria(remoteFactory);
// Check the read came from the cache
log.debug( "Check cache 1" );
assertLoadedFromCache(remoteListener, "1234");
// Modify customer in remote
remoteListener.clear();
CountDownLatch localUpdate = expectEvict(localNaturalIdCache.getAdvancedCache(), 1);
deleteCitizenWithCriteria(remoteFactory);
assertTrue(localUpdate.await(2, TimeUnit.SECONDS));
assertEquals(1, localNaturalIdRegion.getElementCountInMemory());
}
catch (Exception e) {
log.error("Error", e);
throw e;
} finally {
if (cacheMode.isInvalidation())
removeAfterEndInvalidationHandler(remoteNaturalIdCache.getAdvancedCache());
withTxSession(localFactory, s -> {
TEST_SESSION_ACCESS.execQueryUpdate(s, "delete NaturalIdOnManyToOne");
TEST_SESSION_ACCESS.execQueryUpdate(s, "delete Citizen");
TEST_SESSION_ACCESS.execQueryUpdate(s, "delete State");
});
}
}
private boolean await(CountDownLatch latch) {
assertNotNull(latch);
try {
log.debugf("Await latch: %s", latch);
boolean await = latch.await(2, TimeUnit.SECONDS);
log.debugf("Finished waiting for latch, did latch reach zero? %b", await);
return await;
} catch (InterruptedException e) {
// ignore;
return false;
}
}
public CountDownLatch getRemoteUpdateLatch(Cache remoteNaturalIdCache) {
CountDownLatch latch;
if (cacheMode.isInvalidation()) {
latch = useTransactionalCache()
? expectAfterEndInvalidation(remoteNaturalIdCache.getAdvancedCache(), 1)
: expectAfterEndInvalidation(remoteNaturalIdCache.getAdvancedCache(), 2);
} else {
latch = expectAfterUpdate(remoteNaturalIdCache.getAdvancedCache(), 2);
}
log.tracef("Created latch: %s", latch);
return latch;
}
private void assertLoadedFromCache(MyListener localListener, String id) {
for (String visited : localListener.visited){
if (visited.contains(id))
return;
}
fail("Citizen (" + id + ") should have present in the cache");
}
private void saveSomeCitizens(SessionFactory sf) throws Exception {
final Citizen c1 = new Citizen();
c1.setFirstname( "Emmanuel" );
c1.setLastname( "Bernard" );
c1.setSsn( "1234" );
final State france = new State();
france.setName( "Ile de France" );
c1.setState( france );
final Citizen c2 = new Citizen();
c2.setFirstname( "Gavin" );
c2.setLastname( "King" );
c2.setSsn( "000" );
final State australia = new State();
australia.setName( "Australia" );
c2.setState( australia );
withTxSession(sf, s -> {
s.persist( australia );
s.persist( france );
s.persist( c1 );
s.persist( c2 );
});
}
private void getCitizenWithCriteria(SessionFactory sf) throws Exception {
withTxSession(sf, s -> {
State france = getState(s, "Ile de France");
HibernateCriteriaBuilder cb = s.getCriteriaBuilder();
CriteriaQuery<Citizen> criteria = cb.createQuery(Citizen.class);
Root<Citizen> root = criteria.from(Citizen.class);
criteria.where(cb.equal(root.get(Citizen_.state), france));
s.createQuery(criteria)
.getResultList();
});
}
private void deleteCitizenWithCriteria(SessionFactory sf) throws Exception {
withTxSession(sf, s -> {
State france = getState(s, "Ile de France");
HibernateCriteriaBuilder cb = s.getCriteriaBuilder();
JpaCriteriaQuery<Citizen> criteria = cb.createQuery(Citizen.class);
Root<Citizen> root = criteria.from(Citizen.class);
criteria.where(cb.equal(root.get(Citizen_.ssn), "1234"), cb.equal(root.get(Citizen_.state), france));
Citizen c = s.createQuery(criteria).uniqueResult();
s.remove(c);
});
}
private State getState(Session s, String name) {
HibernateCriteriaBuilder cb = s.getCriteriaBuilder();
CriteriaQuery<State> criteria = cb.createQuery(State.class);
Root<State> root = criteria.from(State.class);
criteria.where(cb.equal(root.get(State_.name), name));
return s.createQuery(criteria)
.setHint(QueryHints.HINT_CACHEABLE, "true")
.getResultList().get(0);
}
@Listener
public static class MyListener {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( MyListener.class );
private Set<String> visited = new ConcurrentSet<String>();
private final String name;
public MyListener(String name) {
this.name = name;
}
public void clear() {
visited.clear();
}
public boolean isEmpty() {
return visited.isEmpty();
}
@CacheEntryVisited
public void nodeVisited(CacheEntryVisitedEvent event) {
log.debug( event.toString() );
if ( !event.isPre() ) {
visited.add(event.getKey().toString());
}
}
@CacheEntryCreated
@CacheEntryModified
@CacheEntryRemoved
public void nodeWritten(CacheEntryEvent event) {
log.debug( event.toString() );
}
}
}
| 10,275
| 33.483221
| 131
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/DualNodeTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.infinispan.test.hibernate.cache.commons.functional.AbstractFunctionalTest;
import org.infinispan.test.hibernate.cache.commons.util.InfinispanTestingSetup;
import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider;
import org.infinispan.test.hibernate.cache.commons.util.TxUtil;
import org.junit.ClassRule;
/**
* @author Galder Zamarreño
* @since 3.5
*/
public abstract class DualNodeTest extends AbstractFunctionalTest {
@ClassRule
public static final InfinispanTestingSetup infinispanTestIdentifier = new InfinispanTestingSetup();
public static final String REGION_FACTORY_DELEGATE = "hibernate.cache.region.factory_delegate";
public static final String NODE_ID_PROP = "hibernate.test.cluster.node.id";
public static final String NODE_ID_FIELD = "nodeId";
public static final String LOCAL = "local";
public static final String REMOTE = "remote";
private SecondNodeEnvironment secondNodeEnvironment;
protected void withTxSession(SessionFactory sessionFactory, TxUtil.ThrowingConsumer<Session, Exception> consumer) throws Exception {
TxUtil.withTxSession(useJta, sessionFactory, consumer);
}
protected <T> T withTxSessionApply(SessionFactory sessionFactory, TxUtil.ThrowingFunction<Session, T, Exception> consumer) throws Exception {
return TxUtil.withTxSessionApply(useJta, sessionFactory, consumer);
}
@Override
protected String getBaseForMappings() {
return "org/infinispan/test/";
}
@Override
public String[] getMappings() {
return new String[] {
"hibernate/cache/commons/functional/entities/Contact.hbm.xml",
"hibernate/cache/commons/functional/entities/Customer.hbm.xml"
};
}
@Override
@SuppressWarnings("unchecked")
protected void addSettings(Map settings) {
super.addSettings( settings );
applyStandardSettings( settings );
settings.put( NODE_ID_PROP, LOCAL );
settings.put( NODE_ID_FIELD, LOCAL );
settings.put( REGION_FACTORY_DELEGATE, TestRegionFactoryProvider.load().getRegionFactoryClass());
}
@Override
protected void cleanupTest() throws Exception {
cleanupTransactionManagement();
}
protected void cleanupTransactionManagement() {
DualNodeJtaTransactionManagerImpl.cleanupTransactions();
DualNodeJtaTransactionManagerImpl.cleanupTransactionManagers();
}
@Override
public void startUp() {
super.startUp();
// In some cases tests are multi-threaded, so they have to join the group
infinispanTestIdentifier.joinContext();
secondNodeEnvironment = new SecondNodeEnvironment();
}
@Override
public void shutDown() {
if ( secondNodeEnvironment != null ) {
secondNodeEnvironment.shutDown();
}
super.shutDown();
}
protected SecondNodeEnvironment secondNodeEnvironment() {
return secondNodeEnvironment;
}
protected void configureSecondNode(StandardServiceRegistryBuilder ssrb) {
}
@SuppressWarnings("unchecked")
protected void applyStandardSettings(Map settings) {
settings.put( Environment.CACHE_REGION_FACTORY, TestRegionFactoryProvider.load().getClusterAwareClass().getName() );
}
public class SecondNodeEnvironment {
private StandardServiceRegistry serviceRegistry;
private SessionFactoryImplementor sessionFactory;
public SecondNodeEnvironment() {
StandardServiceRegistryBuilder ssrb = constructStandardServiceRegistryBuilder();
applyStandardSettings( ssrb.getSettings() );
ssrb.applySetting( NODE_ID_PROP, REMOTE );
ssrb.applySetting( NODE_ID_FIELD, REMOTE );
configureSecondNode( ssrb );
serviceRegistry = ssrb.build();
MetadataSources metadataSources = new MetadataSources( serviceRegistry );
applyMetadataSources( metadataSources );
Metadata metadata = metadataSources.buildMetadata();
applyCacheSettings( metadata );
afterMetadataBuilt( metadata );
sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory();
}
public StandardServiceRegistry getServiceRegistry() {
return serviceRegistry;
}
public SessionFactoryImplementor getSessionFactory() {
return sessionFactory;
}
public void shutDown() {
if ( sessionFactory != null ) {
try {
sessionFactory.close();
}
catch (Exception ignore) {
}
}
if ( serviceRegistry != null ) {
try {
StandardServiceRegistryBuilder.destroy( serviceRegistry );
}
catch (Exception ignore) {
}
}
}
}
}
| 5,057
| 30.030675
| 142
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/AbstractPartialUpdateTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.stat.Statistics;
import org.infinispan.AdvancedCache;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.interceptors.AsyncInterceptor;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Customer;
import org.infinispan.test.hibernate.cache.commons.util.ExpectingInterceptor;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.infinispan.configuration.cache.InterceptorConfiguration.Position.FIRST;
import static org.infinispan.test.hibernate.cache.commons.util.TxUtil.withSession;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public abstract class AbstractPartialUpdateTest extends DualNodeTest {
static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(AbstractPartialUpdateTest.class);
protected SessionFactoryImplementor localFactory;
protected SessionFactoryImplementor remoteFactory;
private AdvancedCache<?, ?> remoteCustomerCache;
@Override
public List<Object[]> getParameters() {
return Collections.singletonList(READ_WRITE_REPLICATED);
}
@Override
public void startUp() {
super.startUp();
localFactory = sessionFactory();
remoteFactory = secondNodeEnvironment().getSessionFactory();
remoteCustomerCache = ClusterAware
.getCacheManager(DualNodeTest.REMOTE)
.getCache(Customer.class.getName()).getAdvancedCache();
}
public String getDbName() {
return getClass().getName().replaceAll("\\W", "_");
}
@Test
public void testPartialUpdate() throws Exception {
final AsyncInterceptor failureInterceptor =
addFailureInducingInterceptor(remoteCustomerCache);
try {
// Remote update latch
CountDownLatch remoteLatch = new CountDownLatch(2);
ExpectingInterceptor.get(remoteCustomerCache)
.when((ctx, cmd) -> cmd instanceof ReadWriteKeyCommand)
.countDown(remoteLatch);
try {
Statistics statsNode0 = getStatistics(localFactory);
withTxSession(localFactory, s -> {
Customer customer = new Customer();
customer.setName("JBoss");
s.persist(customer);
});
assertEquals(1, statsNode0.getSecondLevelCachePutCount());
assertEquals(0, statsNode0.getSecondLevelCacheMissCount());
assertEquals(0, statsNode0.getSecondLevelCacheHitCount());
// Wait for value to be applied remotely
assertTrue(remoteLatch.await(2, TimeUnit.SECONDS));
} finally {
ExpectingInterceptor.cleanup(remoteCustomerCache);
}
Statistics statsNode1 = getStatistics(remoteFactory);
withSession(remoteFactory.withOptions(), s -> {
Customer customer = s.load(Customer.class, 1);
assertEquals("JBoss", customer.getName());
});
assertEquals(0, statsNode1.getSecondLevelCachePutCount());
assertEquals(0, statsNode1.getSecondLevelCacheMissCount());
assertEquals(1, statsNode1.getSecondLevelCacheHitCount());
final boolean updated = doUpdate();
if (updated) {
withSession(localFactory.withOptions(), s -> {
Customer customer = s.load(Customer.class, 1);
assertEquals("JBoss, a division of Red Hat", customer.getName());
});
withSession(remoteFactory.withOptions(), s -> {
Customer customer = s.load(Customer.class, 1);
assertEquals("JBoss, a division of Red Hat", customer.getName());
});
}
} finally {
remoteCustomerCache.getAsyncInterceptorChain()
.removeInterceptor(failureInterceptor.getClass());
}
}
private AsyncInterceptor addFailureInducingInterceptor(AdvancedCache<?, ?> cache) {
final AsyncInterceptor interceptor = getFailureInducingInterceptor();
cache.getAsyncInterceptorChain().addInterceptor(interceptor, FIRST.ordinal());
log.trace("Injecting FailureInducingInterceptor into " + cache.getName());
return interceptor;
}
abstract AsyncInterceptor getFailureInducingInterceptor();
protected abstract boolean doUpdate() throws Exception;
public Statistics getStatistics(SessionFactoryImplementor sessionFactory) {
final Statistics stats = sessionFactory.getStatistics();
stats.clear();
return stats;
}
public static class InducedException extends Exception {
public InducedException(String message) {
super(message);
}
}
}
| 4,969
| 36.368421
| 119
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/ClusterAware.java
|
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.Hashtable;
import org.infinispan.manager.EmbeddedCacheManager;
public class ClusterAware {
public static final Hashtable<String, EmbeddedCacheManager> cacheManagers = new Hashtable<String, EmbeddedCacheManager>();
public static EmbeddedCacheManager getCacheManager(String name) {
return cacheManagers.get(name);
}
public static void addCacheManager(String name, EmbeddedCacheManager manager) {
assertNull(cacheManagers.put(name, manager));
}
public static void removeCacheManager(String name) {
assertNotNull(cacheManagers.remove(name));
}
}
| 766
| 29.68
| 125
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/DualNodeConnectionProviderImpl.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.service.UnknownUnwrapTypeException;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.Configurable;
import org.hibernate.service.spi.Stoppable;
import org.hibernate.testing.env.ConnectionProviderBuilder;
/**
* A {@link ConnectionProvider} implementation adding JTA-style transactionality around the returned
* connections using the {@link DualNodeJtaTransactionManagerImpl}.
*
* @author Brian Stansberry
*/
public class DualNodeConnectionProviderImpl implements ConnectionProvider, Configurable {
private static ConnectionProvider actualConnectionProvider = ConnectionProviderBuilder.buildConnectionProvider();
private String nodeId;
private boolean isTransactional;
@Override
public boolean isUnwrappableAs(Class unwrapType) {
return DualNodeConnectionProviderImpl.class.isAssignableFrom( unwrapType ) ||
ConnectionProvider.class.isAssignableFrom( unwrapType );
}
@Override
@SuppressWarnings( {"unchecked"})
public <T> T unwrap(Class<T> unwrapType) {
if ( DualNodeConnectionProviderImpl.class.isAssignableFrom( unwrapType ) ) {
return (T) this;
}
else if ( ConnectionProvider.class.isAssignableFrom( unwrapType ) ) {
return (T) actualConnectionProvider;
}
else {
throw new UnknownUnwrapTypeException( unwrapType );
}
}
public static ConnectionProvider getActualConnectionProvider() {
return actualConnectionProvider;
}
public void setNodeId(String nodeId) throws HibernateException {
if (nodeId == null) {
throw new HibernateException( "nodeId not configured" );
}
this.nodeId = nodeId;
}
public Connection getConnection() throws SQLException {
DualNodeJtaTransactionImpl currentTransaction = DualNodeJtaTransactionManagerImpl
.getInstance(nodeId).getCurrentTransaction();
if (currentTransaction == null) {
isTransactional = false;
return actualConnectionProvider.getConnection();
} else {
isTransactional = true;
Connection connection = currentTransaction.getEnlistedConnection();
if (connection == null) {
connection = actualConnectionProvider.getConnection();
currentTransaction.enlistConnection(connection);
}
return connection;
}
}
public void closeConnection(Connection conn) throws SQLException {
if (!isTransactional) {
conn.close();
}
}
public void close() throws HibernateException {
if ( actualConnectionProvider instanceof Stoppable ) {
( ( Stoppable ) actualConnectionProvider ).stop();
}
}
public boolean supportsAggressiveRelease() {
return true;
}
@Override
public void configure(Map configurationValues) {
nodeId = (String) configurationValues.get( "nodeId" );
}
}
| 3,280
| 31.81
| 116
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/SessionRefreshTest.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.infinispan.Cache;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
import org.infinispan.manager.CacheContainer;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Account;
import org.jboss.logging.Logger;
import org.junit.Test;
/**
* SessionRefreshTestCase.
*
* @author Galder Zamarreño
* @since 3.5
*/
public class SessionRefreshTest extends DualNodeTest {
private static final Logger log = Logger.getLogger(SessionRefreshTest.class);
private Cache localCache;
@Override
protected void configureSecondNode(StandardServiceRegistryBuilder ssrb) {
super.configureSecondNode(ssrb);
ssrb.applySetting(Environment.USE_SECOND_LEVEL_CACHE, "false");
}
@Override
public List<Object[]> getParameters() {
return getParameters(true, true, false, true, true);
}
@Override
protected void applyStandardSettings(Map settings) {
super.applyStandardSettings(settings);
settings.put(InfinispanProperties.ENTITY_CACHE_RESOURCE_PROP, getEntityCacheConfigName());
}
protected String getEntityCacheConfigName() {
return "entity";
}
@Override
protected String getBaseForMappings() {
return "org/infinispan/test/";
}
@Override
public String[] getMappings() {
return new String[] {"hibernate/cache/commons/functional/entities/Account.hbm.xml"};
}
@Override
protected void cleanupTransactionManagement() {
// Don't clean up the managers, just the transactions
// Managers are still needed by the long-lived caches
DualNodeJtaTransactionManagerImpl.cleanupTransactions();
}
@Test
public void testRefreshAfterExternalChange() throws Exception {
// First session factory uses a cache
CacheContainer localManager = ClusterAware.getCacheManager(DualNodeTest.LOCAL);
localCache = localManager.getCache(Account.class.getName());
SessionFactory localFactory = sessionFactory();
// Second session factory doesn't; just needs a transaction manager
SessionFactory remoteFactory = secondNodeEnvironment().getSessionFactory();
AccountDAO dao0 = new AccountDAO(useJta, localFactory);
AccountDAO dao1 = new AccountDAO(useJta, remoteFactory);
Integer id = new Integer(1);
dao0.createAccount(dao0.getSmith(), id, new Integer(5), DualNodeTest.LOCAL);
// Basic sanity check
Account acct1 = dao1.getAccount(id);
assertNotNull(acct1);
assertEquals(DualNodeTest.LOCAL, acct1.getBranch());
// This dao's session factory isn't caching, so cache won't see this change
dao1.updateAccountBranch(id, DualNodeTest.REMOTE);
// dao1's session doesn't touch the cache,
// so reading from dao0 should show a stale value from the cache
// (we check to confirm the cache is used)
Account acct0 = dao0.getAccount(id);
assertNotNull(acct0);
assertEquals(DualNodeTest.LOCAL, acct0.getBranch());
log.debug("Contents when re-reading from local: " + TestingUtil.printCache(localCache));
// Now call session.refresh and confirm we get the correct value
acct0 = dao0.getAccountWithRefresh(id);
assertNotNull(acct0);
assertEquals(DualNodeTest.REMOTE, acct0.getBranch());
log.debug("Contents after refreshing in remote: " + TestingUtil.printCache(localCache));
// Double check with a brand new session, in case the other session
// for some reason bypassed the 2nd level cache
AccountDAO dao0A = new AccountDAO(useJta, localFactory);
Account acct0A = dao0A.getAccount(id);
assertNotNull(acct0A);
assertEquals(DualNodeTest.REMOTE, acct0A.getBranch());
log.debug("Contents after creating a new session: " + TestingUtil.printCache(localCache));
}
}
| 4,204
| 33.467213
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/DualNodeJtaTransactionImpl.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
/**
* SimpleJtaTransactionImpl variant that works with DualNodeTransactionManagerImpl.
*
* TODO: Merge with single node transaction manager
*
* @author Brian Stansberry
*/
public class DualNodeJtaTransactionImpl implements Transaction {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(DualNodeJtaTransactionImpl.class);
private int status;
private LinkedList synchronizations;
private Connection connection; // the only resource we care about is jdbc connection
private final DualNodeJtaTransactionManagerImpl jtaTransactionManager;
private List<XAResource> enlistedResources = new ArrayList<XAResource>();
private Xid xid = new DualNodeJtaTransactionXid();
public DualNodeJtaTransactionImpl(DualNodeJtaTransactionManagerImpl jtaTransactionManager) {
this.jtaTransactionManager = jtaTransactionManager;
this.status = Status.STATUS_ACTIVE;
}
public int getStatus() {
return status;
}
public void commit() throws RollbackException, HeuristicMixedException,
HeuristicRollbackException, IllegalStateException, SystemException {
if (status == Status.STATUS_MARKED_ROLLBACK) {
log.trace("on commit, status was marked for rollback-only");
rollback();
} else {
status = Status.STATUS_PREPARING;
if (synchronizations != null) {
for (int i = 0; i < synchronizations.size(); i++) {
Synchronization s = (Synchronization) synchronizations.get(i);
s.beforeCompletion();
}
}
if (!runXaResourcePrepare()) {
status = Status.STATUS_ROLLING_BACK;
} else {
status = Status.STATUS_PREPARED;
}
status = Status.STATUS_COMMITTING;
if (connection != null) {
try {
connection.commit();
connection.close();
} catch (SQLException sqle) {
status = Status.STATUS_UNKNOWN;
throw new SystemException();
}
}
runXaResourceCommitTx();
status = Status.STATUS_COMMITTED;
if (synchronizations != null) {
for (int i = 0; i < synchronizations.size(); i++) {
Synchronization s = (Synchronization) synchronizations.get(i);
s.afterCompletion(status);
}
}
// status = Status.STATUS_NO_TRANSACTION;
jtaTransactionManager.endCurrent(this);
}
}
public void rollback() throws IllegalStateException, SystemException {
status = Status.STATUS_ROLLING_BACK;
runXaResourceRollback();
status = Status.STATUS_ROLLEDBACK;
if (connection != null) {
try {
connection.rollback();
connection.close();
} catch (SQLException sqle) {
status = Status.STATUS_UNKNOWN;
throw new SystemException();
}
}
if (synchronizations != null) {
for (int i = 0; i < synchronizations.size(); i++) {
Synchronization s = (Synchronization) synchronizations.get(i);
s.afterCompletion(status);
}
}
// status = Status.STATUS_NO_TRANSACTION;
jtaTransactionManager.endCurrent(this);
}
public void setRollbackOnly() throws IllegalStateException, SystemException {
status = Status.STATUS_MARKED_ROLLBACK;
}
public void registerSynchronization(Synchronization synchronization) throws RollbackException,
IllegalStateException, SystemException {
// todo : find the spec-allowable statuses during which synch can be registered...
if (synchronizations == null) {
synchronizations = new LinkedList();
}
synchronizations.add(synchronization);
}
public void enlistConnection(Connection connection) {
if (this.connection != null) {
throw new IllegalStateException("Connection already registered");
}
this.connection = connection;
}
public Connection getEnlistedConnection() {
return connection;
}
public boolean enlistResource(XAResource xaResource) throws RollbackException,
IllegalStateException, SystemException {
enlistedResources.add(new WrappedXaResource(xaResource));
try {
xaResource.start(xid, 0);
} catch (XAException e) {
log.error("Got an exception", e);
throw new SystemException(e.getMessage());
}
return true;
}
public boolean delistResource(XAResource xaResource, int i) throws IllegalStateException,
SystemException {
throw new SystemException("not supported");
}
public Collection<XAResource> getEnlistedResources() {
return enlistedResources;
}
private boolean runXaResourcePrepare() throws SystemException {
Collection<XAResource> resources = getEnlistedResources();
for (XAResource res : resources) {
try {
res.prepare(xid);
} catch (XAException e) {
log.trace("The resource wants to rollback!", e);
return false;
} catch (Throwable th) {
log.error("Unexpected error from resource manager!", th);
throw new SystemException(th.getMessage());
}
}
return true;
}
private void runXaResourceRollback() {
Collection<XAResource> resources = getEnlistedResources();
for (XAResource res : resources) {
try {
res.rollback(xid);
} catch (XAException e) {
log.warn("Error while rolling back",e);
}
}
}
private boolean runXaResourceCommitTx() throws HeuristicMixedException {
Collection<XAResource> resources = getEnlistedResources();
for (XAResource res : resources) {
try {
res.commit(xid, false);//todo we only support one phase commit for now, change this!!!
} catch (XAException e) {
log.warn("exception while committing",e);
throw new HeuristicMixedException(e.getMessage());
}
}
return true;
}
private static class DualNodeJtaTransactionXid implements Xid {
private static AtomicInteger txIdCounter = new AtomicInteger(0);
private int id = txIdCounter.incrementAndGet();
public int getFormatId() {
return id;
}
public byte[] getGlobalTransactionId() {
throw new IllegalStateException("TODO - please implement me!!!"); //todo implement!!!
}
public byte[] getBranchQualifier() {
throw new IllegalStateException("TODO - please implement me!!!"); //todo implement!!!
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"id=" + id +
'}';
}
}
private class WrappedXaResource implements XAResource {
private final XAResource xaResource;
private int prepareResult;
public WrappedXaResource(XAResource xaResource) {
this.xaResource = xaResource;
}
@Override
public void commit(Xid xid, boolean b) throws XAException {
// Commit only if not read only.
if (prepareResult != XAResource.XA_RDONLY)
xaResource.commit(xid, b);
else
log.tracef("Not committing {0} due to readonly.", xid);
}
@Override
public void end(Xid xid, int i) throws XAException {
xaResource.end(xid, i);
}
@Override
public void forget(Xid xid) throws XAException {
xaResource.forget(xid);
}
@Override
public int getTransactionTimeout() throws XAException {
return xaResource.getTransactionTimeout();
}
@Override
public boolean isSameRM(XAResource xaResource) throws XAException {
return xaResource.isSameRM(xaResource);
}
@Override
public int prepare(Xid xid) throws XAException {
prepareResult = xaResource.prepare(xid);
return prepareResult;
}
@Override
public Xid[] recover(int i) throws XAException {
return xaResource.recover(i);
}
@Override
public void rollback(Xid xid) throws XAException {
xaResource.rollback(xid);
}
@Override
public boolean setTransactionTimeout(int i) throws XAException {
return xaResource.setTransactionTimeout(i);
}
@Override
public void start(Xid xid, int i) throws XAException {
xaResource.start(xid, i);
}
}
}
| 9,634
| 30.486928
| 128
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/DualNodeJtaPlatformImpl.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.TransactionException;
import org.hibernate.engine.transaction.internal.jta.JtaStatusHelper;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.service.spi.Configurable;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.UserTransaction;
/**
* @author Steve Ebersole
*/
public class DualNodeJtaPlatformImpl implements JtaPlatform, Configurable {
private String nodeId;
public DualNodeJtaPlatformImpl() {
}
@Override
public void configure(Map configurationValues) {
nodeId = (String) configurationValues.get( DualNodeTest.NODE_ID_PROP );
if ( nodeId == null ) {
throw new HibernateException(DualNodeTest.NODE_ID_PROP + " not configured");
}
}
@Override
public TransactionManager retrieveTransactionManager() {
return DualNodeJtaTransactionManagerImpl.getInstance( nodeId );
}
@Override
public UserTransaction retrieveUserTransaction() {
throw new TransactionException( "UserTransaction not used in these tests" );
}
@Override
public Object getTransactionIdentifier(Transaction transaction) {
return transaction;
}
@Override
public boolean canRegisterSynchronization() {
return JtaStatusHelper.isActive( retrieveTransactionManager() );
}
@Override
public void registerSynchronization(Synchronization synchronization) {
try {
retrieveTransactionManager().getTransaction().registerSynchronization( synchronization );
}
catch (Exception e) {
throw new TransactionException( "Could not obtain transaction from TM" );
}
}
@Override
public int getCurrentStatus() throws SystemException {
return JtaStatusHelper.getStatus( retrieveTransactionManager() );
}
}
| 2,206
| 28.426667
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/test/java/org/infinispan/test/hibernate/cache/commons/functional/cluster/PartialTombstoneTest.java
|
package org.infinispan.test.hibernate.cache.commons.functional.cluster;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.hibernate.cache.commons.util.Tombstone;
import org.infinispan.interceptors.AsyncInterceptor;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.test.hibernate.cache.commons.functional.entities.Customer;
import java.util.concurrent.CompletionException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class PartialTombstoneTest extends AbstractPartialUpdateTest {
@Override
protected boolean doUpdate() throws Exception {
try {
withTxSession(localFactory, s -> {
Customer customer = s.load(Customer.class, 1);
assertEquals("JBoss", customer.getName());
customer.setName(customer.getName() + ", a division of Red Hat");
s.update(customer);
});
fail("Expected update to fail");
return true;
} catch (CompletionException e) {
assertExceptionCause(InducedException.class, e);
return false;
}
}
private static void assertExceptionCause(Class<InducedException> clazz, CompletionException e) {
Throwable cause = e.getCause();
while (!clazz.isInstance(cause)) {
cause = cause.getCause();
}
assertTrue("Expected " + clazz + " to be in the stacktrace", clazz.isInstance(cause));
}
@Override
AsyncInterceptor getFailureInducingInterceptor() {
return new FailureInducingInterceptor();
}
public static class FailureInducingInterceptor extends BaseCustomAsyncInterceptor {
static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(PartialFutureUpdateTest.FailureInducingInterceptor.class);
int remoteInvocationCount;
@Override
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable {
log.tracef("Invoked insert/update: %s", command);
if (!ctx.isOriginLocal()) {
remoteInvocationCount++;
log.tracef("Remote invocation count: %d ", remoteInvocationCount);
if (command.getKey().toString().endsWith("1")
&& remoteInvocationCount == 3
&& command.getFunction() instanceof Tombstone) {
throw new InducedException("Simulate failure when Tombstone received");
}
}
return super.visitReadWriteKeyCommand(ctx, command);
}
}
}
| 2,748
| 34.701299
| 147
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/package-info.java
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
/**
* Defines the integration with Infinispan as a second-level cache service.
*/
package org.infinispan.hibernate.cache.commons;
| 370
| 29.916667
| 94
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/TimeSource.java
|
package org.infinispan.hibernate.cache.commons;
public interface TimeSource {
long nextTimestamp();
}
| 106
| 16.833333
| 47
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/InfinispanBaseRegion.java
|
package org.infinispan.hibernate.cache.commons;
import org.infinispan.AdvancedCache;
/**
* Any region using {@link AdvancedCache} for the underlying storage.
*/
public interface InfinispanBaseRegion extends TimeSource {
AdvancedCache getCache();
String getName();
default void invalidateRegion() {
beginInvalidation();
endInvalidation();
}
void beginInvalidation();
void endInvalidation();
long getLastRegionInvalidation();
boolean checkValid();
void destroy();
long getElementCountInMemory();
}
| 550
| 17.366667
| 69
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/JndiCacheManagerProvider.java
|
package org.infinispan.hibernate.cache.commons;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jndi.internal.JndiServiceInitiator;
import org.hibernate.engine.jndi.spi.JndiService;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.hibernate.cache.spi.EmbeddedCacheManagerProvider;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.manager.impl.AbstractDelegatingEmbeddedCacheManager;
import org.kohsuke.MetaInfServices;
@MetaInfServices(EmbeddedCacheManagerProvider.class)
public class JndiCacheManagerProvider implements EmbeddedCacheManagerProvider {
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( JndiCacheManagerProvider.class );
@Override
public EmbeddedCacheManager getEmbeddedCacheManager(Properties properties) {
String jndiManagerName = properties.getProperty(InfinispanProperties.CACHE_MANAGER_RESOURCE_PROP);
if (jndiManagerName != null) {
EmbeddedCacheManager cacheManager = locateCacheManager(jndiManagerName, properties);
return new AbstractDelegatingEmbeddedCacheManager(cacheManager) {
@Override
public void stop() {
}
@Override
public void close() {
}
};
}
String factoryClass = properties.getProperty(Environment.CACHE_REGION_FACTORY);
if (factoryClass == null) {
// Factory class might not be defined in WF
return null;
} else if (factoryClass.endsWith("JndiInfinispanRegionFactory") || factoryClass.equals("infinispan-jndi")) {
throw log.propertyCacheManagerResourceNotSet();
}
return null;
}
private EmbeddedCacheManager locateCacheManager(String jndiNamespace, Properties jndiProperties) {
JndiService jndiService = JndiServiceInitiator.INSTANCE.initiateService(jndiProperties.entrySet()
.stream().collect(Collectors.toMap(e -> e.getKey().toString(), Map.Entry::getValue)), null);
return (EmbeddedCacheManager) jndiService.locate(jndiNamespace);
}
}
| 2,283
| 41.296296
| 128
|
java
|
null |
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/DataType.java
|
package org.infinispan.hibernate.cache.commons;
import java.util.function.Consumer;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger;
import org.infinispan.hibernate.cache.spi.InfinispanProperties;
public enum DataType {
ENTITY(InfinispanProperties.ENTITY, InfinispanProperties.DEF_ENTITY_RESOURCE, DataType::noValidation),
NATURAL_ID(InfinispanProperties.NATURAL_ID, InfinispanProperties.DEF_ENTITY_RESOURCE, DataType::noValidation),
COLLECTION(InfinispanProperties.COLLECTION, InfinispanProperties.DEF_ENTITY_RESOURCE, DataType::noValidation),
IMMUTABLE_ENTITY(InfinispanProperties.IMMUTABLE_ENTITY, InfinispanProperties.DEF_ENTITY_RESOURCE, DataType::noValidation),
TIMESTAMPS(InfinispanProperties.TIMESTAMPS, InfinispanProperties.DEF_TIMESTAMPS_RESOURCE, c -> {
if ( c.clustering().cacheMode().isInvalidation() ) {
throw log().timestampsMustNotUseInvalidation();
}
if (c.memory().isEvictionEnabled()) {
throw log().timestampsMustNotUseEviction();
}
}),
QUERY(InfinispanProperties.QUERY, InfinispanProperties.DEF_QUERY_RESOURCE, DataType::noValidation),
PENDING_PUTS(InfinispanProperties.PENDING_PUTS, InfinispanProperties.DEF_PENDING_PUTS_RESOURCE, c -> {
if (!c.isTemplate()) {
log().pendingPutsShouldBeTemplate();
}
if (c.clustering().cacheMode().isClustered()) {
throw log().pendingPutsMustNotBeClustered();
}
if (c.transaction().transactionMode().isTransactional()) {
throw log().pendingPutsMustNotBeTransactional();
}
if (c.expiration().maxIdle() <= 0) {
throw log().pendingPutsMustHaveMaxIdle();
}
});
private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(InfinispanProperties.class);
public final String key;
public final String defaultCacheName;
private final Consumer<Configuration> validation;
private static InfinispanMessageLogger log() {
// we need a method to avoid forward references
return log;
}
private static void noValidation(Configuration c) {
}
DataType(String key, String defaultCacheName, Consumer<Configuration> validation) {
this.key = key;
this.defaultCacheName = defaultCacheName;
this.validation = validation;
}
public void validate(Configuration configuration) {
validation.accept(configuration);
}
}
| 2,489
| 39.16129
| 125
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.