Search in sources :

Example 6 with CacheListenerAdapter

use of org.apache.geode.cache.util.CacheListenerAdapter in project geode by apache.

the class MultiVMRegionTestCase method versionTestTombstones.

public void versionTestTombstones() {
    disconnectAllFromDS();
    Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);
    final int numEntries = 100;
    // create replicated regions in VM 0 and 1, then perform concurrent ops
    // on the same key while creating the region in VM2. Afterward make
    // sure that all three regions are consistent
    final long oldServerTimeout = TombstoneService.REPLICATE_TOMBSTONE_TIMEOUT;
    final long oldClientTimeout = TombstoneService.NON_REPLICATE_TOMBSTONE_TIMEOUT;
    final int oldExpiredTombstoneLimit = TombstoneService.EXPIRED_TOMBSTONE_LIMIT;
    final boolean oldIdleExpiration = TombstoneService.IDLE_EXPIRATION;
    final double oldLimit = TombstoneService.GC_MEMORY_THRESHOLD;
    final long oldMaxSleepTime = TombstoneService.MAX_SLEEP_TIME;
    try {
        SerializableRunnable setTimeout = new SerializableRunnable() {

            @Override
            public void run() {
                TombstoneService.REPLICATE_TOMBSTONE_TIMEOUT = 1000;
                TombstoneService.NON_REPLICATE_TOMBSTONE_TIMEOUT = 900;
                TombstoneService.EXPIRED_TOMBSTONE_LIMIT = numEntries;
                TombstoneService.IDLE_EXPIRATION = true;
                // turn this off so heap profile won't cause
                TombstoneService.GC_MEMORY_THRESHOLD = 0;
                // test to fail
                TombstoneService.MAX_SLEEP_TIME = 500;
            }
        };
        vm0.invoke(setTimeout);
        vm1.invoke(setTimeout);
        final String name = this.getUniqueName() + "-CC";
        SerializableRunnable createRegion = new SerializableRunnable("Create Region") {

            @Override
            public void run() {
                try {
                    RegionFactory f = getCache().createRegionFactory(getRegionAttributes());
                    CCRegion = (LocalRegion) f.create(name);
                    for (int i = 0; i < numEntries; i++) {
                        CCRegion.put("cckey" + i, "ccvalue");
                    }
                    if (CCRegion.getScope().isDistributedNoAck()) {
                        // flush the ops
                        sendSerialMessageToAll();
                    }
                } catch (CacheException ex) {
                    fail("While creating region", ex);
                }
            }
        };
        vm0.invoke(createRegion);
        vm1.invoke(createRegion);
        vm0.invoke(new SerializableRunnable("destroy entries and check tombstone count") {

            @Override
            public void run() {
                try {
                    for (int i = 0; i < numEntries; i++) {
                        CCRegion.destroy("cckey" + i);
                        assertTrue("entry should not exist", !CCRegion.containsKey("cckey" + i));
                        assertTrue("entry should not contain a value", !CCRegion.containsValueForKey("cckey" + i));
                    }
                    checkCCRegionTombstoneCount("after destroys in this vm ", numEntries);
                    assertTrue("region should not contain a tombstone", !CCRegion.containsValue(Token.TOMBSTONE));
                    if (CCRegion.getScope().isDistributedNoAck()) {
                        // flush the ops
                        sendSerialMessageToAll();
                    }
                } catch (CacheException e) {
                    fail("while performing destroy operations", e);
                }
            }
        });
        vm1.invoke(new SerializableRunnable("check tombstone count(2)") {

            @Override
            public void run() {
                checkCCRegionTombstoneCount("after destroys in other vm ", numEntries);
                WaitCriterion waitForExpiration = new WaitCriterion() {

                    @Override
                    public boolean done() {
                        return CCRegion.getTombstoneCount() == 0;
                    }

                    @Override
                    public String description() {
                        return "Waiting for all tombstones to expire.  There are now " + CCRegion.getTombstoneCount() + " tombstones left out of " + numEntries + " initial tombstones. " + CCRegion.getCache().getTombstoneService();
                    }
                };
                try {
                    Wait.waitForCriterion(waitForExpiration, TombstoneService.REPLICATE_TOMBSTONE_TIMEOUT + (TombstoneService.MAX_SLEEP_TIME * 9), 100, true);
                } catch (AssertionError e) {
                    CCRegion.dumpBackingMap();
                    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("tombstone service state: " + CCRegion.getCache().getTombstoneService());
                    throw e;
                }
            }
        });
        vm0.invoke(new SerializableRunnable("create/destroy entries and check tombstone count") {

            @Override
            public void run() {
                final int origCount = CCRegion.getTombstoneCount();
                try {
                    WaitCriterion waitForExpiration = new WaitCriterion() {

                        @Override
                        public boolean done() {
                            return CCRegion.getTombstoneCount() == 0;
                        }

                        @Override
                        public String description() {
                            return "Waiting for all tombstones to expire.  There are now " + CCRegion.getTombstoneCount() + " tombstones left out of " + origCount + " initial tombstones. " + CCRegion.getCache().getTombstoneService();
                        }
                    };
                    Wait.waitForCriterion(waitForExpiration, TombstoneService.REPLICATE_TOMBSTONE_TIMEOUT + (TombstoneService.MAX_SLEEP_TIME * 9), 100, true);
                    logger.debug("creating tombstones.  current count={}", CCRegion.getTombstoneCount());
                    for (int i = 0; i < numEntries; i++) {
                        CCRegion.create("cckey" + i, i);
                        CCRegion.destroy("cckey" + i);
                    }
                    logger.debug("done creating tombstones.  current count={}", CCRegion.getTombstoneCount());
                    checkCCRegionTombstoneCount("after create+destroy in this vm ", numEntries);
                    assertEquals(0, CCRegion.size());
                    afterCreates = 0;
                    AttributesMutator m = CCRegion.getAttributesMutator();
                    m.addCacheListener(new CacheListenerAdapter() {

                        @Override
                        public void afterCreate(EntryEvent event) {
                            afterCreates++;
                        }
                    });
                    if (CCRegion.getScope().isDistributedNoAck()) {
                        // flush the ops
                        sendSerialMessageToAll();
                    }
                } catch (AssertionError e) {
                    CCRegion.dumpBackingMap();
                    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("tombstone service state: " + CCRegion.getCache().getTombstoneService());
                    throw e;
                } catch (CacheException e) {
                    fail("while performing create/destroy operations", e);
                }
            }
        });
        vm1.invoke(new SerializableRunnable("check tombstone count and install listener") {

            @Override
            public void run() {
                checkCCRegionTombstoneCount("after create+destroy in other vm ", numEntries);
                afterCreates = 0;
                AttributesMutator m = CCRegion.getAttributesMutator();
                m.addCacheListener(new CacheListenerAdapter() {

                    @Override
                    public void afterCreate(EntryEvent event) {
                        afterCreates++;
                    }
                });
            }
        });
        // Now check to see if tombstones are resurrected by a create.
        // The entries should be created okay and the callback should be afterCreate.
        // The tombstone count won't go down until the entries are swept, but then
        // the count should fall to zero.
        vm0.invoke(new SerializableRunnable("create entries and check afterCreate and tombstone count") {

            @Override
            public void run() {
                try {
                    for (int i = 0; i < numEntries; i++) {
                        CCRegion.create("cckey" + i, i);
                    }
                    checkCCRegionTombstoneCount("after create in this vm", 0);
                    assertEquals("expected " + numEntries + " afterCreates", numEntries, afterCreates);
                    assertEquals(numEntries, CCRegion.size());
                    if (CCRegion.getScope().isDistributedNoAck()) {
                        // flush the ops
                        sendSerialMessageToAll();
                    }
                    WaitCriterion waitForExpiration = new WaitCriterion() {

                        @Override
                        public boolean done() {
                            return CCRegion.getCache().getTombstoneService().getScheduledTombstoneCount() == 0;
                        }

                        @Override
                        public String description() {
                            return "Waiting for all scheduled tombstones to be removed.  There are now " + CCRegion.getCache().getTombstoneService().getScheduledTombstoneCount() + " tombstones left out of " + numEntries + " initial tombstones. " + CCRegion.getCache().getTombstoneService();
                        }
                    };
                    Wait.waitForCriterion(waitForExpiration, TombstoneService.REPLICATE_TOMBSTONE_TIMEOUT * 5, 100, true);
                } catch (CacheException e) {
                    fail("while performing create operations", e);
                }
            }
        });
        vm1.invoke(new SerializableRunnable("check afterCreate and tombstone count") {

            @Override
            public void run() {
                checkCCRegionTombstoneCount("after create in other vm", 0);
                assertEquals("expected " + numEntries + " afterCreates", numEntries, afterCreates);
                assertEquals(numEntries, CCRegion.size());
                WaitCriterion waitForExpiration = new WaitCriterion() {

                    @Override
                    public boolean done() {
                        return CCRegion.getCache().getTombstoneService().getScheduledTombstoneCount() == 0;
                    }

                    @Override
                    public String description() {
                        return "Waiting for all scheduled tombstones to be removed.  There are now " + CCRegion.getCache().getTombstoneService().getScheduledTombstoneCount() + " tombstones left out of " + numEntries + " initial tombstones. " + CCRegion.getCache().getTombstoneService();
                    }
                };
                Wait.waitForCriterion(waitForExpiration, TombstoneService.REPLICATE_TOMBSTONE_TIMEOUT * 5, 100, true);
            }
        });
    } finally {
        SerializableRunnable resetTimeout = new SerializableRunnable() {

            @Override
            public void run() {
                TombstoneService.REPLICATE_TOMBSTONE_TIMEOUT = oldServerTimeout;
                TombstoneService.NON_REPLICATE_TOMBSTONE_TIMEOUT = oldClientTimeout;
                TombstoneService.EXPIRED_TOMBSTONE_LIMIT = oldExpiredTombstoneLimit;
                TombstoneService.IDLE_EXPIRATION = oldIdleExpiration;
                TombstoneService.GC_MEMORY_THRESHOLD = oldLimit;
                TombstoneService.MAX_SLEEP_TIME = oldMaxSleepTime;
            }
        };
        vm0.invoke(resetTimeout);
        vm1.invoke(resetTimeout);
    }
}
Also used : CacheException(org.apache.geode.cache.CacheException) SerializableRunnable(org.apache.geode.test.dunit.SerializableRunnable) Host(org.apache.geode.test.dunit.Host) WaitCriterion(org.apache.geode.test.dunit.WaitCriterion) RegionFactory(org.apache.geode.cache.RegionFactory) CacheListenerAdapter(org.apache.geode.cache.util.CacheListenerAdapter) VM(org.apache.geode.test.dunit.VM) EntryEvent(org.apache.geode.cache.EntryEvent) AttributesMutator(org.apache.geode.cache.AttributesMutator)

Example 7 with CacheListenerAdapter

use of org.apache.geode.cache.util.CacheListenerAdapter in project geode by apache.

the class DeltaPropagationStatsDUnitTest method createServerCache.

public static Integer createServerCache(Boolean flag, DataPolicy policy, Scope scope, Boolean listener) throws Exception {
    ConnectionTable.threadWantsSharedResources();
    DeltaPropagationStatsDUnitTest test = new DeltaPropagationStatsDUnitTest();
    Properties props = new Properties();
    if (!flag) {
        props.setProperty(DELTA_PROPAGATION, "false");
    }
    cache = test.createCache(props);
    AttributesFactory factory = new AttributesFactory();
    factory.setScope(scope);
    factory.setDataPolicy(policy);
    if (listener) {
        factory.addCacheListener(new CacheListenerAdapter() {

            public void afterCreate(EntryEvent event) {
                if (event.getKey().equals(LAST_KEY)) {
                    lastKeyReceived = true;
                }
            }
        });
    }
    Region region = cache.createRegion(REGION_NAME, factory.create());
    if (!policy.isReplicate()) {
        region.create("KEY", "KEY");
    }
    region.getAttributesMutator().setCloningEnabled(false);
    CacheServer server = cache.addCacheServer();
    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
    server.setPort(port);
    server.setNotifyBySubscription(true);
    server.start();
    return server.getPort();
}
Also used : AttributesFactory(org.apache.geode.cache.AttributesFactory) CacheListenerAdapter(org.apache.geode.cache.util.CacheListenerAdapter) EntryEvent(org.apache.geode.cache.EntryEvent) Region(org.apache.geode.cache.Region) CacheServer(org.apache.geode.cache.server.CacheServer) ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) Properties(java.util.Properties)

Example 8 with CacheListenerAdapter

use of org.apache.geode.cache.util.CacheListenerAdapter in project geode by apache.

the class DiskRegCbkChkJUnitTest method testAfterCallbacks.

@Test
public void testAfterCallbacks() {
    region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, getDiskRegionProperties(), Scope.LOCAL);
    // testing create callbacks
    region.getAttributesMutator().setCacheListener(new CacheListenerAdapter() {

        public void afterCreate(EntryEvent event) {
            intoCreateAfterCbk = true;
        }
    });
    region.getAttributesMutator().setCacheWriter(new CacheWriterAdapter() {

        public void beforeCreate(EntryEvent event) {
            region.clear();
        }
    });
    region.create("key1", "createValue");
    assertTrue("Create callback not called", intoCreateAfterCbk);
    // testing update callbacks
    region.getAttributesMutator().setCacheListener(new CacheListenerAdapter() {

        public void afterUpdate(EntryEvent event) {
            intoUpdateAfterCbk = true;
        }
    });
    region.getAttributesMutator().setCacheWriter(new CacheWriterAdapter() {

        public void beforeUpdate(EntryEvent event) {
            region.clear();
        }
    });
    region.create("key2", "createValue");
    region.put("key2", "updateValue");
    assertTrue("Update callback not called", intoUpdateAfterCbk);
    // testing destroy callbacks
    region.getAttributesMutator().setCacheListener(new CacheListenerAdapter() {

        public void afterDestroy(EntryEvent event) {
            intoDestroyAfterCbk = true;
        }
    });
    region.getAttributesMutator().setCacheWriter(new CacheWriterAdapter() {

        public void beforeDestroy(EntryEvent event) {
            region.clear();
        }
    });
    region.create("key3", "createValue");
    region.destroy("key3");
    assertTrue("Destroy callback not called", intoDestroyAfterCbk);
}
Also used : CacheWriterAdapter(org.apache.geode.cache.util.CacheWriterAdapter) CacheListenerAdapter(org.apache.geode.cache.util.CacheListenerAdapter) EntryEvent(org.apache.geode.cache.EntryEvent) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 9 with CacheListenerAdapter

use of org.apache.geode.cache.util.CacheListenerAdapter in project geode by apache.

the class MapInterface2JUnitTest method testBasicMapAfterClearCalback.

@Test
public void testBasicMapAfterClearCalback() {
    Region rgn = CacheUtils.getRegion("Portfolios");
    AttributesMutator atm = rgn.getAttributesMutator();
    atm.setCacheListener(new CacheListenerAdapter() {

        public void afterRegionClear(RegionEvent event) {
            synchronized (MapInterface2JUnitTest.this) {
                event.getRegion().getCache().getLogger().info("afterRegionClear call back " + event);
                afterClearCallbackOccurred = true;
                MapInterface2JUnitTest.this.notify();
            }
        }
    });
    int size = rgn.size();
    assertTrue("MapInterface2JUnitTest::basicMapClearNonTranxn: The init size of region is zero", size > 0);
    rgn.clear();
    if (rgn.size() != 0) {
        fail("The region size is non zero even after issuing clear");
    }
    if (rgn.size() != 0) {
        fail("The region size is non zero even after issuing clear");
    }
    try {
        synchronized (this) {
            if (!this.afterClearCallbackOccurred) {
                this.wait(10000);
            }
        }
    } catch (InterruptedException ie) {
        fail(ie.toString());
    }
    if (!this.afterClearCallbackOccurred) {
        fail("afterClear Callback not issued");
    }
}
Also used : CacheListenerAdapter(org.apache.geode.cache.util.CacheListenerAdapter) Region(org.apache.geode.cache.Region) RegionEvent(org.apache.geode.cache.RegionEvent) AttributesMutator(org.apache.geode.cache.AttributesMutator) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 10 with CacheListenerAdapter

use of org.apache.geode.cache.util.CacheListenerAdapter in project geode by apache.

the class HARegionQueueJUnitTest method testConcurrentEventExpiryAndTake.

/**
   * The basis of HARegionQueue's Add & remove operations etc , is that the event being added first
   * goes into DACE , Region etc and finally it is published by adding into the available IDs Set.
   * Similarly if an event is to be removed it should first be removed from availableIDs set & then
   * from behind the scenes. It will be the responsibility of the thread removing from available IDs
   * successfully which will remove the entry from all other places. Now if the expiry task makes
   * the event from underlying null before removing from available IDs , there is a potential
   * violation. This test will validate that behaviour
   */
@Test
public void testConcurrentEventExpiryAndTake() throws Exception {
    AtomicBoolean complete = new AtomicBoolean(false);
    AtomicBoolean expiryCalled = new AtomicBoolean(false);
    AtomicBoolean allowExpiryToProceed = new AtomicBoolean(false);
    HARegionQueueAttributes haa = new HARegionQueueAttributes();
    haa.setExpiryTime(3);
    RegionQueue regionqueue = new HARegionQueue.TestOnlyHARegionQueue(this.testName.getMethodName(), this.cache, haa) {

        @Override
        CacheListener createCacheListenerForHARegion() {
            return new CacheListenerAdapter() {

                @Override
                public void afterInvalidate(EntryEvent event) {
                    if (event.getKey() instanceof Long) {
                        synchronized (HARegionQueueJUnitTest.this) {
                            expiryCalled.set(true);
                            HARegionQueueJUnitTest.this.notifyAll();
                        }
                        Thread.yield();
                        synchronized (HARegionQueueJUnitTest.this) {
                            while (!allowExpiryToProceed.get()) {
                                try {
                                    HARegionQueueJUnitTest.this.wait();
                                } catch (InterruptedException e) {
                                    errorCollector.addError(e);
                                    break;
                                }
                            }
                        }
                        try {
                            expireTheEventOrThreadIdentifier(event);
                        } catch (CacheException e) {
                            errorCollector.addError(e);
                        } finally {
                            synchronized (HARegionQueueJUnitTest.this) {
                                complete.set(true);
                                HARegionQueueJUnitTest.this.notifyAll();
                            }
                        }
                    }
                }
            };
        }
    };
    EventID ev1 = new EventID(new byte[] { 1 }, 1, 1);
    Conflatable cf1 = new ConflatableObject("key", "value", ev1, true, this.testName.getMethodName());
    regionqueue.put(cf1);
    synchronized (this) {
        while (!expiryCalled.get()) {
            wait();
        }
    }
    try {
        Object o = regionqueue.take();
        assertThat(o, nullValue());
    } catch (Exception e) {
        throw new AssertionError("Test failed due to exception ", e);
    } finally {
        synchronized (this) {
            allowExpiryToProceed.set(true);
            notifyAll();
        }
    }
    synchronized (this) {
        while (!complete.get()) {
            wait();
        }
    }
}
Also used : CacheException(org.apache.geode.cache.CacheException) RegionQueue(org.apache.geode.internal.cache.RegionQueue) RegionExistsException(org.apache.geode.cache.RegionExistsException) IOException(java.io.IOException) CacheException(org.apache.geode.cache.CacheException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CacheListenerAdapter(org.apache.geode.cache.util.CacheListenerAdapter) EntryEvent(org.apache.geode.cache.EntryEvent) EventID(org.apache.geode.internal.cache.EventID) Conflatable(org.apache.geode.internal.cache.Conflatable) ClientSubscriptionTest(org.apache.geode.test.junit.categories.ClientSubscriptionTest) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Aggregations

CacheListenerAdapter (org.apache.geode.cache.util.CacheListenerAdapter)66 EntryEvent (org.apache.geode.cache.EntryEvent)55 AttributesFactory (org.apache.geode.cache.AttributesFactory)40 Region (org.apache.geode.cache.Region)30 Test (org.junit.Test)25 RegionAttributes (org.apache.geode.cache.RegionAttributes)21 Properties (java.util.Properties)20 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)16 ConfigurationProperties (org.apache.geode.distributed.ConfigurationProperties)15 VM (org.apache.geode.test.dunit.VM)14 CacheException (org.apache.geode.cache.CacheException)11 CacheListener (org.apache.geode.cache.CacheListener)11 LocalRegion (org.apache.geode.internal.cache.LocalRegion)9 Host (org.apache.geode.test.dunit.Host)9 RegionEvent (org.apache.geode.cache.RegionEvent)8 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)8 PartitionAttributesFactory (org.apache.geode.cache.PartitionAttributesFactory)7 CacheServer (org.apache.geode.cache.server.CacheServer)7 SerializableRunnable (org.apache.geode.test.dunit.SerializableRunnable)7 SubscriptionAttributes (org.apache.geode.cache.SubscriptionAttributes)6