Java Code Examples for org.apache.ignite.IgniteCache#registerCacheEntryListener()

The following examples show how to use org.apache.ignite.IgniteCache#registerCacheEntryListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IgniteCacheEntryListenerAbstractTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param cache Cache.
 * @param lsnrFactory Listener factory.
 * @param key Key.
 * @param create {@code True} if listens for create events.
 * @param update {@code True} if listens for update events.
 * @param rmv {@code True} if listens for remove events.
 * @param expire {@code True} if listens for expire events.
 * @throws Exception If failed.
 */
private void checkEvents(
    final IgniteCache<Object, Object> cache,
    final Factory<CacheEntryListener<Object, Object>> lsnrFactory,
    Integer key,
    boolean create,
    boolean update,
    boolean rmv,
    boolean expire) throws Exception {
    CacheEntryListenerConfiguration<Object, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>(
        lsnrFactory,
        null,
        true,
        false
    );

    cache.registerCacheEntryListener(lsnrCfg);

    try {
        checkEvents(cache, lsnrCfg, key, create, update, rmv, expire, true);
    }
    finally {
        cache.deregisterCacheEntryListener(lsnrCfg);
    }
}
 
Example 2
Source File: CacheContinuousQueryLostPartitionTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param cache Cache.
 * @return Event listener.
 */
private AllEventListener<Integer, String> registerCacheListener(IgniteCache<Integer, String> cache) {
    AllEventListener<Integer, String> lsnr = new AllEventListener<>();

    cache.registerCacheEntryListener(
        new MutableCacheEntryListenerConfiguration<>(factoryOf(lsnr), null, true, false));

    return lsnr;
}
 
Example 3
Source File: IgniteCacheEntryListenerExpiredEventsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param ccfg Cache configuration.
 * @throws Exception If failed.
 */
private void checkExpiredEvents(CacheConfiguration<Object, Object> ccfg) throws Exception {
    IgniteCache<Object, Object> cache = ignite(0).createCache(ccfg);

    try {
        evtCntr = new AtomicInteger();

        CacheEntryListenerConfiguration<Object, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>(
            new ExpiredListenerFactory(),
            null,
            true,
            false
        );

        cache.registerCacheEntryListener(lsnrCfg);

        IgniteCache<Object, Object> expiryCache =
            cache.withExpiryPolicy(new ModifiedExpiryPolicy(new Duration(MILLISECONDS, 500)));

        expiryCache.put(1, 1);

        for (int i = 0; i < 10; i++)
            cache.get(i);

        boolean wait = GridTestUtils.waitForCondition(new GridAbsPredicate() {
            @Override public boolean apply() {
                return evtCntr.get() > 0;
            }
        }, 5000);

        assertTrue(wait);

        U.sleep(100);

        assertEquals(1, evtCntr.get());
    }
    finally {
        ignite(0).destroyCache(cache.getName());
    }
}
 
Example 4
Source File: IgniteCacheEntryListenerAbstractTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testNoOldValue() throws Exception {
    CacheEntryListenerConfiguration<Object, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>(
        new Factory<CacheEntryListener<Object, Object>>() {
            @Override public CacheEntryListener<Object, Object> create() {
                return new CreateUpdateRemoveExpireListener();
            }
        },
        null,
        false,
        true
    );

    IgniteCache<Object, Object> cache = jcache();

    try {
        for (Integer key : keys()) {
            log.info("Check create/update/remove/expire events, no old value [key=" + key + ']');

            cache.registerCacheEntryListener(lsnrCfg);

            checkEvents(cache, lsnrCfg, key, true, true, true, true, false);
        }
    }
    finally {
        cache.deregisterCacheEntryListener(lsnrCfg);
    }
}
 
Example 5
Source File: GridCacheContinuousQueryMultiNodesFilteringTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** */
private Ignite startGrid(final int idx, boolean isClientMode) throws Exception {
    String igniteInstanceName = getTestIgniteInstanceName(idx);

    IgniteConfiguration cfg = optimize(getConfiguration(igniteInstanceName)).setClientMode(isClientMode);

    cfg.setUserAttributes(Collections.singletonMap("idx", idx));

    Ignite node = startGrid(igniteInstanceName, cfg);

    IgnitePredicate<ClusterNode> nodeFilter = new NodeFilter(idx);

    String partCacheName = "part" + idx;

    IgniteCache partCache = node.createCache(defaultCacheConfiguration().setName("part" + idx)
        .setCacheMode(PARTITIONED).setBackups(1).setNodeFilter(nodeFilter));

    opCounts.put(partCacheName + "_ins", new AtomicInteger());
    opCounts.put(partCacheName + "_upd", new AtomicInteger());
    opCounts.put(partCacheName + "_rmv", new AtomicInteger());

    partCache.registerCacheEntryListener(new ListenerConfiguration(partCacheName, ListenerConfiguration.Op.INSERT));
    partCache.registerCacheEntryListener(new ListenerConfiguration(partCacheName, ListenerConfiguration.Op.UPDATE));
    partCache.registerCacheEntryListener(new ListenerConfiguration(partCacheName, ListenerConfiguration.Op.REMOVE));

    String replCacheName = "repl" + idx;

    IgniteCache replCache = node.createCache(defaultCacheConfiguration().setName("repl" + idx)
        .setCacheMode(REPLICATED).setNodeFilter(nodeFilter));

    opCounts.put(replCacheName + "_ins", new AtomicInteger());
    opCounts.put(replCacheName + "_upd", new AtomicInteger());
    opCounts.put(replCacheName + "_rmv", new AtomicInteger());

    replCache.registerCacheEntryListener(new ListenerConfiguration(replCacheName, ListenerConfiguration.Op.INSERT));
    replCache.registerCacheEntryListener(new ListenerConfiguration(replCacheName, ListenerConfiguration.Op.UPDATE));
    replCache.registerCacheEntryListener(new ListenerConfiguration(replCacheName, ListenerConfiguration.Op.REMOVE));

    opCounts.put("qry" + idx + "_total", new AtomicInteger());

    ContinuousQuery qry = new ContinuousQuery();
    qry.setRemoteFilterFactory(new EntryEventFilterFactory(idx));
    qry.setLocalListener(new CacheEntryUpdatedListener() {
        /** {@inheritDoc} */
        @Override public void onUpdated(Iterable evts) {
            opCounts.get("qry" + idx + "_total").incrementAndGet();
        }
    });

    partCache.query(qry);
    replCache.query(qry);

    return node;
}
 
Example 6
Source File: CacheContinuousQueryOperationP2PTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param ccfg Cache configuration.
 * @param isClient Client.
 * @param joinNode If a node should be added to topology after a query is started.
 * @param evtFilterFactoryCls Remote filter factory class.
 * @throws Exception If failed.
 */
private void testContinuousQuery(CacheConfiguration<Object, Object> ccfg,
    boolean isClient, boolean joinNode,
    Class<Factory<CacheEntryEventFilter>> evtFilterFactoryCls) throws Exception {

    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    final CountDownLatch latch = new CountDownLatch(UPDATES);

    ContinuousQuery<Integer, Integer> qry = new ContinuousQuery<>();

    AtomicReference<String> err = new AtomicReference<>();

    TestLocalListener locLsnr = new TestLocalListener() {
        @Override protected void onEvent(Iterable<CacheEntryEvent<? extends Integer, ? extends Integer>> evts) {
            for (CacheEntryEvent<? extends Integer, ? extends Integer> evt : evts) {
                latch.countDown();

                log.info("Received event: " + evt);

                int key = evt.getKey();

                if (key % 2 == 0)
                    err.set("Event received on entry, that doesn't pass a filter: " + key);
            }
        }
    };

    qry.setLocalListener(locLsnr);

    qry.setRemoteFilterFactory(
        (Factory<? extends CacheEntryEventFilter<Integer, Integer>>)(Object)evtFilterFactoryCls.newInstance());

    MutableCacheEntryListenerConfiguration<Integer, Integer> lsnrCfg =
        new MutableCacheEntryListenerConfiguration<>(
            new FactoryBuilder.SingletonFactory<>(locLsnr),
            (Factory<? extends CacheEntryEventFilter<? super Integer, ? super Integer>>)
                (Object)evtFilterFactoryCls.newInstance(),
            true,
            true
        );

    IgniteCache<Integer, Integer> cache;

    cache = isClient
        ? grid(NODES - 1).cache(ccfg.getName())
        : grid(rnd.nextInt(NODES - 1)).cache(ccfg.getName());

    try (QueryCursor<?> cur = cache.query(qry)) {
        cache.registerCacheEntryListener(lsnrCfg);

        if (joinNode) {
            startGrid(NODES);
            awaitPartitionMapExchange();
        }

        for (int i = 0; i < UPDATES; i++)
            cache.put(i, i);

        assertTrue("Failed to wait for local listener invocations: " + latch.getCount(),
            latch.await(3, TimeUnit.SECONDS));

        assertNull(err.get(), err.get());
    }
}
 
Example 7
Source File: GridCacheReplicatedPreloadSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If test failed.
 */
@Test
public void testExternalClassesAtConfiguration() throws Exception {
    try {
        extClassloadingAtCfg = true;
        useExtClassLoader = true;

        Ignite g1 = startGrid(1);

        Ignite g2 = startGrid(2);  // Checks deserialization at node join.

        Ignite g3 = startClientGrid(3);

        IgniteCache<Integer, Object> cache1 = g1.cache(DEFAULT_CACHE_NAME);
        IgniteCache<Integer, Object> cache2 = g2.cache(DEFAULT_CACHE_NAME);
        IgniteCache<Integer, Object> cache3 = g3.cache(DEFAULT_CACHE_NAME);

        final Class<CacheEntryListener> cls1 = (Class<CacheEntryListener>) getExternalClassLoader().
            loadClass("org.apache.ignite.tests.p2p.CacheDeploymentCacheEntryListener");
        final Class<CacheEntryEventSerializableFilter> cls2 = (Class<CacheEntryEventSerializableFilter>) getExternalClassLoader().
            loadClass("org.apache.ignite.tests.p2p.CacheDeploymentCacheEntryEventSerializableFilter");

        CacheEntryListenerConfiguration<Integer, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>(
            new Factory<CacheEntryListener<Integer, Object>>() {
                @Override public CacheEntryListener<Integer, Object> create() {
                    try {
                        return cls1.newInstance();
                    }
                    catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            },
            new ClassFilterFactory(cls2),
            true,
            true
        );

        cache1.registerCacheEntryListener(lsnrCfg);

        cache1.put(1, 1);

        assertEquals(1, cache2.get(1));
        assertEquals(1, cache3.get(1));
    }
    finally {
        extClassloadingAtCfg = false;
        useExtClassLoader = false;
    }
}