Search in sources :

Example 31 with CacheEntryEvent

use of javax.cache.event.CacheEntryEvent in project ignite by apache.

the class CacheContinuousQueryRandomOperationsTest method waitAndCheckEvent.

/**
     *  @param evtsQueues Queue.
     * @param partCntrs Counters.
     * @param aff Affinity.
     * @param vals Values.
     * @param expData Expected data.
     */
private void waitAndCheckEvent(List<BlockingQueue<CacheEntryEvent<?, ?>>> evtsQueues, Map<Integer, Long> partCntrs, Map<Object, Long> evtCntrs, Affinity<Object> aff, SortedMap<Object, Object> vals, Map<Object, Object> expData) throws Exception {
    for (BlockingQueue<CacheEntryEvent<?, ?>> evtsQueue : evtsQueues) {
        Map<Object, CacheEntryEvent> rcvEvts = new HashMap<>();
        for (int i = 0; i < vals.size(); i++) {
            CacheEntryEvent<?, ?> evt = evtsQueue.poll(5, SECONDS);
            rcvEvts.put(evt.getKey(), evt);
        }
        assertEquals(vals.size(), rcvEvts.size());
        for (Map.Entry<Object, Object> e : vals.entrySet()) {
            Object key = e.getKey();
            Object val = e.getValue();
            Object oldVal = expData.get(key);
            if (val == null && oldVal == null) {
                checkNoEvent(evtsQueues);
                continue;
            }
            CacheEntryEvent evt = rcvEvts.get(key);
            assertNotNull("Failed to wait for event [key=" + key + ", val=" + val + ", oldVal=" + oldVal + ']', evt);
            assertEquals(key, evt.getKey());
            assertEquals(val, evt.getValue());
            assertEquals(oldVal, evt.getOldValue());
            Long curPartCntr = partCntrs.get(aff.partition(key));
            Long cntr = evtCntrs.get(key);
            CacheQueryEntryEvent qryEntryEvt = (CacheQueryEntryEvent) evt.unwrap(CacheQueryEntryEvent.class);
            assertNotNull(cntr);
            assertNotNull(curPartCntr);
            assertNotNull(qryEntryEvt);
            assertTrue(cntr <= curPartCntr);
            assertEquals((long) cntr, qryEntryEvt.getPartitionUpdateCounter());
        }
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) CacheQueryEntryEvent(org.apache.ignite.cache.query.CacheQueryEntryEvent) CacheEntryEvent(javax.cache.event.CacheEntryEvent) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) TreeMap(java.util.TreeMap)

Example 32 with CacheEntryEvent

use of javax.cache.event.CacheEntryEvent in project ignite by apache.

the class CacheContinuousQueryVariationsTest method waitAndCheckEvent.

/**
     * @param evtsQueues Event queue.
     * @param key Key.
     * @param val Value.
     * @param oldVal Old value.
     * @param keepBinary Keep binary.
     * @param withFilter With filter.
     * @throws Exception If failed.
     */
private void waitAndCheckEvent(List<BlockingQueue<CacheEntryEvent<?, ?>>> evtsQueues, Object key, Object val, Object oldVal, boolean keepBinary, boolean withFilter) throws Exception {
    if (val == null && oldVal == null || (withFilter && val != null && !isAccepted(val, false, dataMode))) {
        checkNoEvent(evtsQueues);
        return;
    }
    for (BlockingQueue<CacheEntryEvent<?, ?>> evtsQueue : evtsQueues) {
        CacheEntryEvent<?, ?> evt = evtsQueue.poll(5, SECONDS);
        assertNotNull("Failed to wait for event [key=" + key + ", val=" + val + ", oldVal=" + oldVal + ']', evt);
        Object actKey = evt.getKey();
        Object actVal = evt.getValue();
        Object actOldVal = evt.getOldValue();
        if (keepBinary) {
            actKey = checkAndGetObject(actKey);
            actVal = checkAndGetObject(actVal);
            actOldVal = checkAndGetObject(actOldVal);
        }
        assertEquals(key, actKey);
        assertEquals(val, actVal);
        assertEquals(oldVal, actOldVal);
    }
}
Also used : BinaryObject(org.apache.ignite.binary.BinaryObject) CacheEntryEvent(javax.cache.event.CacheEntryEvent)

Example 33 with CacheEntryEvent

use of javax.cache.event.CacheEntryEvent in project ignite by apache.

the class ContinuousQueryPeerClassLoadingTest method check.

/**
     * @param node1Name Node 1 name.
     * @param node2Name Node 2 name.
     * @param node3Name Node 3 name.
     */
private void check(String node1Name, String node2Name, String node3Name) throws Exception {
    final Ignite node1 = startGrid(node1Name);
    final IgniteCache<Integer, String> cache = node1.getOrCreateCache(CACHE_NAME);
    for (int i = 0; i < 10; i++) cache.put(i, String.valueOf(i));
    final Ignite node2 = startGrid(node2Name);
    final ContinuousQuery<Integer, String> qry1 = new ContinuousQuery<>();
    final ContinuousQuery<Integer, String> qry2 = new ContinuousQuery<>();
    qry1.setRemoteFilterFactory(new DummyEventFilterFactory());
    qry2.setRemoteFilterFactory(new DummyEventFilterFactory());
    final AtomicInteger client1Evts = new AtomicInteger(0);
    final AtomicInteger client2Evts = new AtomicInteger(0);
    final CountDownLatch latch1 = new CountDownLatch(20);
    final CountDownLatch latch2 = new CountDownLatch(10);
    qry1.setLocalListener(new CacheEntryUpdatedListener<Integer, String>() {

        @Override
        public void onUpdated(final Iterable<CacheEntryEvent<? extends Integer, ? extends String>> evts) throws CacheEntryListenerException {
            System.out.println(">> Client 1 events " + evts);
            for (CacheEntryEvent<? extends Integer, ? extends String> evt : evts) latch1.countDown();
        }
    });
    qry2.setLocalListener(new CacheEntryUpdatedListener<Integer, String>() {

        @Override
        public void onUpdated(final Iterable<CacheEntryEvent<? extends Integer, ? extends String>> evts) throws CacheEntryListenerException {
            System.out.println(">> Client 2 events " + evts);
            for (CacheEntryEvent<? extends Integer, ? extends String> evt : evts) latch2.countDown();
        }
    });
    final IgniteCache<Integer, String> cache1 = node2.cache(CACHE_NAME);
    cache1.query(qry1);
    for (int i = 10; i < 20; i++) cache.put(i, String.valueOf(i));
    // Fail on start second client.
    final Ignite node3 = startGrid(node3Name);
    final IgniteCache<Integer, String> cache2 = node3.cache(CACHE_NAME);
    cache2.query(qry2);
    for (int i = 20; i < 30; i++) cache.put(i, String.valueOf(i));
    assert latch1.await(5, TimeUnit.SECONDS) : latch1.getCount();
    assert latch2.await(5, TimeUnit.SECONDS) : latch2.getCount();
}
Also used : DummyEventFilterFactory(org.apache.ignite.custom.DummyEventFilterFactory) CountDownLatch(java.util.concurrent.CountDownLatch) CacheEntryListenerException(javax.cache.event.CacheEntryListenerException) CacheEntryEvent(javax.cache.event.CacheEntryEvent) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Ignite(org.apache.ignite.Ignite)

Example 34 with CacheEntryEvent

use of javax.cache.event.CacheEntryEvent in project ignite by apache.

the class CacheContinuousAsyncQueryExample method main.

/**
     * Executes example.
     *
     * @param args Command line arguments, none required.
     * @throws Exception If example execution failed.
     */
public static void main(String[] args) throws Exception {
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println();
        System.out.println(">>> Cache continuous query example started.");
        // Auto-close cache at the end of the example.
        try (IgniteCache<Integer, String> cache = ignite.getOrCreateCache(CACHE_NAME)) {
            int keyCnt = 20;
            // These entries will be queried by initial predicate.
            for (int i = 0; i < keyCnt; i++) cache.put(i, Integer.toString(i));
            // Create new continuous query.
            ContinuousQuery<Integer, String> qry = new ContinuousQuery<>();
            qry.setInitialQuery(new ScanQuery<>(new IgniteBiPredicate<Integer, String>() {

                @Override
                public boolean apply(Integer key, String val) {
                    return key > 10;
                }
            }));
            // Callback that is called locally when update notifications are received.
            qry.setLocalListener(new CacheEntryUpdatedListener<Integer, String>() {

                @Override
                public void onUpdated(Iterable<CacheEntryEvent<? extends Integer, ? extends String>> evts) {
                    for (CacheEntryEvent<? extends Integer, ? extends String> e : evts) System.out.println("Updated entry [key=" + e.getKey() + ", val=" + e.getValue() + ']');
                }
            });
            // This filter will be evaluated remotely on all nodes.
            // Entry that pass this filter will be sent to the caller.
            qry.setRemoteFilterFactory(new Factory<CacheEntryEventFilter<Integer, String>>() {

                @Override
                public CacheEntryEventFilter<Integer, String> create() {
                    return new CacheEntryFilter();
                }
            });
            // Execute query.
            try (QueryCursor<Cache.Entry<Integer, String>> cur = cache.query(qry)) {
                // Iterate through existing data.
                for (Cache.Entry<Integer, String> e : cur) System.out.println("Queried existing entry [key=" + e.getKey() + ", val=" + e.getValue() + ']');
                // Add a few more keys and watch more query notifications.
                for (int i = 0; i < keyCnt; i++) cache.put(i, Integer.toString(i));
                // Wait for a while while callback is notified about remaining puts.
                Thread.sleep(2000);
            }
            // Iterate through entries which was updated from filter.
            for (int i = 0; i < 10; i++) System.out.println("Entry updated from filter [key=" + i + ", val=" + cache.get(i) + ']');
        } finally {
            // Distributed cache could be removed from cluster only by #destroyCache() call.
            ignite.destroyCache(CACHE_NAME);
        }
    }
}
Also used : IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) CacheEntryEventFilter(javax.cache.event.CacheEntryEventFilter) CacheEntryEvent(javax.cache.event.CacheEntryEvent) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) Ignite(org.apache.ignite.Ignite) IgniteCache(org.apache.ignite.IgniteCache) Cache(javax.cache.Cache)

Example 35 with CacheEntryEvent

use of javax.cache.event.CacheEntryEvent in project ignite by apache.

the class CacheContinuousQueryManager method existingEntries.

/**
     * @param keepBinary Keep binary flag.
     * @param filter Filter.
     * @return Iterable for events created for existing cache entries.
     * @throws IgniteCheckedException If failed.
     */
public Iterable<CacheEntryEvent<?, ?>> existingEntries(final boolean keepBinary, final CacheEntryEventFilter filter) throws IgniteCheckedException {
    final Iterator<Cache.Entry<?, ?>> it = cctx.cache().igniteIterator(keepBinary);
    final Cache cache = cctx.kernalContext().cache().jcache(cctx.name());
    return new Iterable<CacheEntryEvent<?, ?>>() {

        @Override
        public Iterator<CacheEntryEvent<?, ?>> iterator() {
            return new Iterator<CacheEntryEvent<?, ?>>() {

                private CacheQueryEntryEvent<?, ?> next;

                {
                    advance();
                }

                @Override
                public boolean hasNext() {
                    return next != null;
                }

                @Override
                public CacheEntryEvent<?, ?> next() {
                    if (!hasNext())
                        throw new NoSuchElementException();
                    CacheEntryEvent next0 = next;
                    advance();
                    return next0;
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }

                private void advance() {
                    next = null;
                    while (next == null) {
                        if (!it.hasNext())
                            break;
                        Cache.Entry e = it.next();
                        next = new CacheEntryEventImpl(cache, CREATED, e.getKey(), e.getValue());
                        if (filter != null && !filter.evaluate(next))
                            next = null;
                    }
                }
            };
        }
    };
}
Also used : Iterator(java.util.Iterator) CacheQueryEntryEvent(org.apache.ignite.cache.query.CacheQueryEntryEvent) CacheEntryEvent(javax.cache.event.CacheEntryEvent) NoSuchElementException(java.util.NoSuchElementException) Cache(javax.cache.Cache)

Aggregations

CacheEntryEvent (javax.cache.event.CacheEntryEvent)55 ContinuousQuery (org.apache.ignite.cache.query.ContinuousQuery)41 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)28 CountDownLatch (java.util.concurrent.CountDownLatch)24 ArrayList (java.util.ArrayList)18 CacheEntryListenerException (javax.cache.event.CacheEntryListenerException)14 Ignite (org.apache.ignite.Ignite)13 HashMap (java.util.HashMap)11 List (java.util.List)11 IgniteCache (org.apache.ignite.IgniteCache)8 PA (org.apache.ignite.internal.util.typedef.PA)8 QueryCursor (org.apache.ignite.cache.query.QueryCursor)7 T2 (org.apache.ignite.internal.util.typedef.T2)7 IgniteException (org.apache.ignite.IgniteException)6 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)5 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)5 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)5 ConcurrentMap (java.util.concurrent.ConcurrentMap)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4