Search in sources :

Example 1 with ReadWriteKeyCommand

use of org.infinispan.commands.functional.ReadWriteKeyCommand in project infinispan by infinispan.

the class AbstractFunctionalTest method expectReadWriteKeyCommand.

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);
    }
}
Also used : Property(org.hibernate.mapping.Property) TxUtil(org.infinispan.test.hibernate.cache.commons.util.TxUtil) Reply(org.infinispan.remoting.inboundhandler.Reply) InfinispanMessageLogger(org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger) AdvancedCache(org.infinispan.AdvancedCache) PersistentClass(org.hibernate.mapping.PersistentClass) Map(java.util.Map) After(org.junit.After) AccessType(org.hibernate.cache.spi.access.AccessType) ClassRule(org.junit.ClassRule) Parameterized(org.junit.runners.Parameterized) SimpleCacheKeysFactory(org.hibernate.cache.internal.SimpleCacheKeysFactory) JtaPlatformImpl(org.infinispan.test.hibernate.cache.commons.tm.JtaPlatformImpl) BaseNonConfigCoreFunctionalTestCase(org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase) Predicate(java.util.function.Predicate) SimpleValue(org.hibernate.mapping.SimpleValue) Column(org.hibernate.mapping.Column) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) PerCacheInboundInvocationHandler(org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler) TestingUtil.wrapInboundInvocationHandler(org.infinispan.test.TestingUtil.wrapInboundInvocationHandler) EndInvalidationCommand(org.infinispan.hibernate.cache.commons.util.EndInvalidationCommand) ExpectingInterceptor(org.infinispan.test.hibernate.cache.commons.util.ExpectingInterceptor) TestRegionFactory(org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) AvailableSettings(org.hibernate.cfg.AvailableSettings) RootClass(org.hibernate.mapping.RootClass) RunWith(org.junit.runner.RunWith) Session(org.hibernate.Session) TestRegionFactoryProvider(org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider) Metadata(org.hibernate.boot.Metadata) ArrayList(java.util.ArrayList) AbstractDelegatingHandler(org.infinispan.remoting.inboundhandler.AbstractDelegatingHandler) XaConnectionProvider(org.infinispan.test.hibernate.cache.commons.tm.XaConnectionProvider) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) JtaTransactionCoordinatorBuilderImpl(org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl) Environment(org.hibernate.cfg.Environment) CustomParameterized(org.hibernate.testing.junit4.CustomParameterized) NoJtaPlatform(org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform) JtaPlatform(org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform) InfinispanTestingSetup(org.infinispan.test.hibernate.cache.commons.util.InfinispanTestingSetup) CacheRpcCommand(org.infinispan.commands.remote.CacheRpcCommand) CacheMode(org.infinispan.configuration.cache.CacheMode) FutureUpdate(org.infinispan.hibernate.cache.commons.util.FutureUpdate) TombstoneUpdate(org.infinispan.hibernate.cache.commons.util.TombstoneUpdate) ReadWriteKeyCommand(org.infinispan.commands.functional.ReadWriteKeyCommand) JdbcResourceLocalTransactionCoordinatorBuilderImpl(org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl) BeforeClassOnce(org.hibernate.testing.BeforeClassOnce) DeliverOrder(org.infinispan.remoting.inboundhandler.DeliverOrder) ReadWriteKeyCommand(org.infinispan.commands.functional.ReadWriteKeyCommand) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 2 with ReadWriteKeyCommand

use of org.infinispan.commands.functional.ReadWriteKeyCommand in project infinispan by infinispan.

the class EntityCollectionInvalidationTest method testAll.

@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());
    }
}
Also used : TestSessionAccess(org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess) TimeoutException(java.util.concurrent.TimeoutException) InfinispanMessageLogger(org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger) TestForIssue(org.hibernate.testing.TestForIssue) InvocationContext(org.infinispan.context.InvocationContext) AdvancedCache(org.infinispan.AdvancedCache) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) AccessType(org.hibernate.cache.spi.access.AccessType) DDAsyncInterceptor(org.infinispan.interceptors.DDAsyncInterceptor) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Listener(org.infinispan.notifications.Listener) PutFromLoadValidator(org.infinispan.hibernate.cache.commons.access.PutFromLoadValidator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SessionFactory(org.hibernate.SessionFactory) Set(java.util.Set) Matchers.any(org.mockito.Matchers.any) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ControlledTimeService(org.infinispan.util.ControlledTimeService) Stream(java.util.stream.Stream) ExpectingInterceptor(org.infinispan.test.hibernate.cache.commons.util.ExpectingInterceptor) TestRegionFactory(org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory) Customer(org.infinispan.test.hibernate.cache.commons.functional.entities.Customer) InfinispanProperties(org.infinispan.hibernate.cache.spi.InfinispanProperties) CacheEntryVisitedEvent(org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent) Session(org.hibernate.Session) Mockito.spy(org.mockito.Mockito.spy) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Contact(org.infinispan.test.hibernate.cache.commons.functional.entities.Contact) CacheEntryVisited(org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited) EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) TestName(org.junit.rules.TestName) TestingUtil.extractInterceptorChain(org.infinispan.test.TestingUtil.extractInterceptorChain) GetKeyValueCommand(org.infinispan.commands.read.GetKeyValueCommand) Iterator(java.util.Iterator) Util(org.infinispan.commons.util.Util) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) InfinispanBaseRegion(org.infinispan.hibernate.cache.commons.InfinispanBaseRegion) Assert.assertNull(org.junit.Assert.assertNull) Rule(org.junit.Rule) FutureUpdate(org.infinispan.hibernate.cache.commons.util.FutureUpdate) ReadWriteKeyCommand(org.infinispan.commands.functional.ReadWriteKeyCommand) Phaser(java.util.concurrent.Phaser) VisitableCommand(org.infinispan.commands.VisitableCommand) Assert.assertEquals(org.junit.Assert.assertEquals) ReadWriteKeyCommand(org.infinispan.commands.functional.ReadWriteKeyCommand) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 3 with ReadWriteKeyCommand

use of org.infinispan.commands.functional.ReadWriteKeyCommand in project infinispan by infinispan.

the class AbstractPartialUpdateTest method testPartialUpdate.

@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());
    }
}
Also used : AsyncInterceptor(org.infinispan.interceptors.AsyncInterceptor) FIRST(org.infinispan.configuration.cache.InterceptorConfiguration.Position.FIRST) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) InfinispanMessageLogger(org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger) TxUtil.withSession(org.infinispan.test.hibernate.cache.commons.util.TxUtil.withSession) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) AdvancedCache(org.infinispan.AdvancedCache) ReadWriteKeyCommand(org.infinispan.commands.functional.ReadWriteKeyCommand) ExpectingInterceptor(org.infinispan.test.hibernate.cache.commons.util.ExpectingInterceptor) Customer(org.infinispan.test.hibernate.cache.commons.functional.entities.Customer) Statistics(org.hibernate.stat.Statistics) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ReadWriteKeyCommand(org.infinispan.commands.functional.ReadWriteKeyCommand) Customer(org.infinispan.test.hibernate.cache.commons.functional.entities.Customer) CountDownLatch(java.util.concurrent.CountDownLatch) Statistics(org.hibernate.stat.Statistics) AsyncInterceptor(org.infinispan.interceptors.AsyncInterceptor) Test(org.junit.Test)

Example 4 with ReadWriteKeyCommand

use of org.infinispan.commands.functional.ReadWriteKeyCommand in project infinispan by infinispan.

the class SingleKeyFunctionalBackupWriteCommand method createWriteCommand.

@Override
WriteCommand createWriteCommand() {
    switch(operation) {
        case READ_WRITE:
            // noinspection unchecked
            return new ReadWriteKeyCommand(key, (Function) function, segmentId, getCommandInvocationId(), MATCH_ALWAYS, params, keyDataConversion, valueDataConversion);
        case READ_WRITE_KEY_VALUE:
            // noinspection unchecked
            ReadWriteKeyValueCommand cmd = new ReadWriteKeyValueCommand(key, value, (BiFunction) function, segmentId, getCommandInvocationId(), MATCH_ALWAYS, params, keyDataConversion, valueDataConversion);
            cmd.setPrevValueAndMetadata(prevValue, prevMetadata);
            return cmd;
        case WRITE_ONLY:
            // noinspection unchecked
            return new WriteOnlyKeyCommand(key, (Consumer) function, segmentId, getCommandInvocationId(), MATCH_ALWAYS, params, keyDataConversion, valueDataConversion);
        case WRITE_ONLY_KEY_VALUE:
            // noinspection unchecked
            return new WriteOnlyKeyValueCommand(key, value, (BiConsumer) function, segmentId, getCommandInvocationId(), MATCH_ALWAYS, params, keyDataConversion, valueDataConversion);
        default:
            throw new IllegalStateException("Unknown operation " + operation);
    }
}
Also used : ReadWriteKeyCommand(org.infinispan.commands.functional.ReadWriteKeyCommand) ReadWriteKeyValueCommand(org.infinispan.commands.functional.ReadWriteKeyValueCommand) WriteOnlyKeyCommand(org.infinispan.commands.functional.WriteOnlyKeyCommand) WriteOnlyKeyValueCommand(org.infinispan.commands.functional.WriteOnlyKeyValueCommand)

Example 5 with ReadWriteKeyCommand

use of org.infinispan.commands.functional.ReadWriteKeyCommand in project infinispan by infinispan.

the class AbstractRegionAccessStrategyTest method expectPutFromLoad.

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;
}
Also used : Arrays(java.util.Arrays) TestSessionAccess(org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Cache(org.infinispan.Cache) AdvancedCache(org.infinispan.AdvancedCache) After(org.junit.After) Mockito.doAnswer(org.mockito.Mockito.doAnswer) TestingUtil(org.infinispan.test.TestingUtil) AccessType(org.hibernate.cache.spi.access.AccessType) CacheEntry(org.hibernate.cache.spi.entry.CacheEntry) PutFromLoadValidator(org.infinispan.hibernate.cache.commons.access.PutFromLoadValidator) Predicate(java.util.function.Predicate) SessionAccess(org.infinispan.hibernate.cache.commons.access.SessionAccess) TestRegionAccessStrategy(org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess.TestRegionAccessStrategy) Serializable(java.io.Serializable) Objects(java.util.Objects) Matchers.any(org.mockito.Matchers.any) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) SoftLock(org.hibernate.cache.spi.access.SoftLock) ControlledTimeService(org.infinispan.util.ControlledTimeService) AfterClassOnce(org.hibernate.testing.AfterClassOnce) ExpectingInterceptor(org.infinispan.test.hibernate.cache.commons.util.ExpectingInterceptor) TestRegionFactory(org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory) Logger(org.jboss.logging.Logger) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Caches(org.infinispan.hibernate.cache.commons.util.Caches) Mockito.spy(org.mockito.Mockito.spy) ArrayList(java.util.ArrayList) VersionedEntry(org.infinispan.hibernate.cache.commons.util.VersionedEntry) RollbackException(javax.transaction.RollbackException) TestName(org.junit.rules.TestName) ClearCommand(org.infinispan.commands.write.ClearCommand) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) InfinispanBaseRegion(org.infinispan.hibernate.cache.commons.InfinispanBaseRegion) InvalidateCommand(org.infinispan.commands.write.InvalidateCommand) Rule(org.junit.Rule) Assert.assertNull(org.junit.Assert.assertNull) FutureUpdate(org.infinispan.hibernate.cache.commons.util.FutureUpdate) TombstoneUpdate(org.infinispan.hibernate.cache.commons.util.TombstoneUpdate) SystemException(javax.transaction.SystemException) ReadWriteKeyCommand(org.infinispan.commands.functional.ReadWriteKeyCommand) BeforeClassOnce(org.hibernate.testing.BeforeClassOnce) VisitableCommand(org.infinispan.commands.VisitableCommand) TestSynchronization(org.infinispan.test.hibernate.cache.commons.util.TestSynchronization) Assert.assertEquals(org.junit.Assert.assertEquals) ReadWriteKeyCommand(org.infinispan.commands.functional.ReadWriteKeyCommand) TombstoneUpdate(org.infinispan.hibernate.cache.commons.util.TombstoneUpdate) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

ReadWriteKeyCommand (org.infinispan.commands.functional.ReadWriteKeyCommand)6 List (java.util.List)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 AdvancedCache (org.infinispan.AdvancedCache)5 ExpectingInterceptor (org.infinispan.test.hibernate.cache.commons.util.ExpectingInterceptor)5 ArrayList (java.util.ArrayList)4 TimeUnit (java.util.concurrent.TimeUnit)4 AccessType (org.hibernate.cache.spi.access.AccessType)4 FutureUpdate (org.infinispan.hibernate.cache.commons.util.FutureUpdate)4 TestRegionFactory (org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory)4 Assert.assertEquals (org.junit.Assert.assertEquals)4 Predicate (java.util.function.Predicate)3 InfinispanMessageLogger (org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger)3 Serializable (java.io.Serializable)2 Arrays (java.util.Arrays)2 Map (java.util.Map)2 Objects (java.util.Objects)2 RollbackException (javax.transaction.RollbackException)2 SystemException (javax.transaction.SystemException)2 Session (org.hibernate.Session)2