Search in sources :

Example 26 with IgniteBiPredicate

use of org.apache.ignite.lang.IgniteBiPredicate 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 27 with IgniteBiPredicate

use of org.apache.ignite.lang.IgniteBiPredicate in project ignite by apache.

the class UsingScanQueries method executingScanQueriesExample.

@Test
void executingScanQueriesExample() {
    try (Ignite ignite = Ignition.start()) {
        // tag::scanQry[]
        // tag::predicate[]
        // tag::transformer[]
        IgniteCache<Integer, Person> cache = ignite.getOrCreateCache("myCache");
        // end::scanQry[]
        // end::predicate[]
        // end::transformer[]
        Person person = new Person(1, "Vasya Ivanov");
        person.setSalary(2000);
        cache.put(1, person);
        // tag::scanQry[]
        QueryCursor<Cache.Entry<Integer, Person>> cursor = cache.query(new ScanQuery<>());
        // end::scanQry[]
        System.out.println("Scan query output:" + cursor.getAll().get(0).getValue().getName());
        // tag::predicate[]
        // Find the persons who earn more than 1,000.
        IgniteBiPredicate<Integer, Person> filter = (key, p) -> p.getSalary() > 1000;
        try (QueryCursor<Cache.Entry<Integer, Person>> qryCursor = cache.query(new ScanQuery<>(filter))) {
            qryCursor.forEach(entry -> System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()));
        }
        // end::predicate[]
        // tag::transformer[]
        // Get only keys for persons earning more than 1,000.
        List<Integer> keys = cache.query(new ScanQuery<>(// Remote filter
        (IgniteBiPredicate<Integer, Person>) (k, p) -> p.getSalary() > 1000), // Transformer
        (IgniteClosure<Cache.Entry<Integer, Person>, Integer>) Cache.Entry::getKey).getAll();
        // end::transformer[]
        System.out.println("Transformer example output:" + keys.get(0));
    }
}
Also used : QueryIndexType(org.apache.ignite.cache.QueryIndexType) Arrays(java.util.Arrays) IndexQueryCriteriaBuilder.gt(org.apache.ignite.cache.query.IndexQueryCriteriaBuilder.gt) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) IndexQueryCriteriaBuilder.eq(org.apache.ignite.cache.query.IndexQueryCriteriaBuilder.eq) Ignite(org.apache.ignite.Ignite) IndexQuery(org.apache.ignite.cache.query.IndexQuery) IgniteCache(org.apache.ignite.IgniteCache) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.jupiter.api.Test) List(java.util.List) Ignition(org.apache.ignite.Ignition) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) IgniteClosure(org.apache.ignite.lang.IgniteClosure) QueryCursor(org.apache.ignite.cache.query.QueryCursor) Cache(javax.cache.Cache) QueryEntity(org.apache.ignite.cache.QueryEntity) Collections(java.util.Collections) QueryIndex(org.apache.ignite.cache.QueryIndex) ScanQuery(org.apache.ignite.cache.query.ScanQuery) IgniteClosure(org.apache.ignite.lang.IgniteClosure) ScanQuery(org.apache.ignite.cache.query.ScanQuery) Ignite(org.apache.ignite.Ignite) IgniteCache(org.apache.ignite.IgniteCache) Cache(javax.cache.Cache) Test(org.junit.jupiter.api.Test)

Example 28 with IgniteBiPredicate

use of org.apache.ignite.lang.IgniteBiPredicate in project ignite by apache.

the class Events method remoteEvents.

void remoteEvents(Ignite ignite) {
    // tag::remote[]
    IgniteEvents events = ignite.events();
    IgnitePredicate<CacheEvent> filter = evt -> {
        System.out.println("remote event: " + evt.name());
        return true;
    };
    // Subscribe to the cache events on all nodes where the cache is hosted.
    UUID uuid = events.remoteListen(new IgniteBiPredicate<UUID, CacheEvent>() {

        @Override
        public boolean apply(UUID uuid, CacheEvent e) {
            // continue listening
            return true;
        }
    }, filter, EventType.EVT_CACHE_OBJECT_PUT);
// end::remote[]
}
Also used : IgniteEvents(org.apache.ignite.IgniteEvents) CacheEvent(org.apache.ignite.events.CacheEvent) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) EventType(org.apache.ignite.events.EventType) Collection(java.util.Collection) JobEvent(org.apache.ignite.events.JobEvent) UUID(java.util.UUID) Ignite(org.apache.ignite.Ignite) IgniteCache(org.apache.ignite.IgniteCache) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) Ignition(org.apache.ignite.Ignition) IgnitePredicate(org.apache.ignite.lang.IgnitePredicate) MemoryEventStorageSpi(org.apache.ignite.spi.eventstorage.memory.MemoryEventStorageSpi) IgniteEvents(org.apache.ignite.IgniteEvents) CacheEvent(org.apache.ignite.events.CacheEvent) UUID(java.util.UUID)

Example 29 with IgniteBiPredicate

use of org.apache.ignite.lang.IgniteBiPredicate in project ignite by apache.

the class GridCacheAdapter method localLoadCache.

/**
 * {@inheritDoc}
 */
@Override
public void localLoadCache(final IgniteBiPredicate<K, V> p, Object[] args) throws IgniteCheckedException {
    // TODO IGNITE-7954
    MvccUtils.verifyMvccOperationSupport(ctx, "Load");
    final boolean replicate = ctx.isDrEnabled();
    final AffinityTopologyVersion topVer = ctx.affinity().affinityTopologyVersion();
    CacheOperationContext opCtx = ctx.operationContextPerCall();
    ExpiryPolicy plc0 = opCtx != null ? opCtx.expiry() : null;
    final ExpiryPolicy plc = plc0 != null ? plc0 : ctx.expiry();
    final boolean keepBinary = opCtx != null && opCtx.isKeepBinary();
    if (p != null)
        ctx.kernalContext().resource().injectGeneric(p);
    try {
        if (ctx.store().isLocal()) {
            DataStreamerImpl ldr = ctx.kernalContext().dataStream().dataStreamer(ctx.name());
            try {
                ldr.skipStore(true);
                ldr.receiver(new IgniteDrDataStreamerCacheUpdater());
                ldr.keepBinary(keepBinary);
                LocalStoreLoadClosure c = new LocalStoreLoadClosure(p, ldr, plc);
                ctx.store().loadCache(c, args);
                c.onDone();
            } finally {
                ldr.closeEx(false);
            }
        } else {
            // Version for all loaded entries.
            final GridCacheVersion ver0 = ctx.versions().nextForLoad();
            ctx.store().loadCache(new CIX3<KeyCacheObject, Object, GridCacheVersion>() {

                @Override
                public void applyx(KeyCacheObject key, Object val, @Nullable GridCacheVersion ver) throws IgniteException {
                    assert ver == null;
                    long ttl = CU.ttlForLoad(plc);
                    if (ttl == CU.TTL_ZERO)
                        return;
                    loadEntry(key, val, ver0, (IgniteBiPredicate<Object, Object>) p, topVer, replicate, ttl);
                }
            }, args);
        }
    } finally {
        if (p instanceof PlatformCacheEntryFilter)
            ((PlatformCacheEntryFilter) p).onClose();
    }
}
Also used : IgniteDrDataStreamerCacheUpdater(org.apache.ignite.internal.processors.dr.IgniteDrDataStreamerCacheUpdater) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) DataStreamerImpl(org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl) PlatformCacheEntryFilter(org.apache.ignite.internal.processors.platform.cache.PlatformCacheEntryFilter) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) IgniteException(org.apache.ignite.IgniteException) ExpiryPolicy(javax.cache.expiry.ExpiryPolicy) IgniteExternalizableExpiryPolicy(org.apache.ignite.internal.processors.cache.distributed.IgniteExternalizableExpiryPolicy)

Example 30 with IgniteBiPredicate

use of org.apache.ignite.lang.IgniteBiPredicate in project ignite by apache.

the class CacheEventsExample method main.

/**
 * Executes example.
 *
 * @param args Command line arguments, none required.
 * @throws IgniteException If example execution failed.
 */
public static void main(String[] args) throws IgniteException, InterruptedException {
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println();
        System.out.println(">>> Cache events example started.");
        // Auto-close cache at the end of the example.
        try (IgniteCache<Integer, String> cache = ignite.getOrCreateCache(CACHE_NAME)) {
            // This optional local callback is called for each event notification
            // that passed remote predicate listener.
            IgniteBiPredicate<UUID, CacheEvent> locLsnr = new IgniteBiPredicate<UUID, CacheEvent>() {

                @Override
                public boolean apply(UUID uuid, CacheEvent evt) {
                    System.out.println("Received event [evt=" + evt.name() + ", key=" + evt.key() + ", oldVal=" + evt.oldValue() + ", newVal=" + evt.newValue());
                    // Continue listening.
                    return true;
                }
            };
            // Remote listener which only accepts events for keys that are
            // greater or equal than 10 and if event node is primary for this key.
            IgnitePredicate<CacheEvent> rmtLsnr = new IgnitePredicate<CacheEvent>() {

                @Override
                public boolean apply(CacheEvent evt) {
                    System.out.println("Cache event [name=" + evt.name() + ", key=" + evt.key() + ']');
                    int key = evt.key();
                    return key >= 10 && ignite.affinity(CACHE_NAME).isPrimary(ignite.cluster().localNode(), key);
                }
            };
            // Subscribe to specified cache events on all nodes that have cache running.
            // Cache events are explicitly enabled in examples/config/example-ignite.xml file.
            ignite.events(ignite.cluster().forCacheNodes(CACHE_NAME)).remoteListen(locLsnr, rmtLsnr, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_READ, EVT_CACHE_OBJECT_REMOVED);
            // Generate cache events.
            for (int i = 0; i < 20; i++) cache.put(i, Integer.toString(i));
            // Wait for a while while callback is notified about remaining puts.
            Thread.sleep(2000);
        } finally {
            // Distributed cache could be removed from cluster only by #destroyCache() call.
            ignite.destroyCache(CACHE_NAME);
        }
    }
}
Also used : IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) IgnitePredicate(org.apache.ignite.lang.IgnitePredicate) CacheEvent(org.apache.ignite.events.CacheEvent) Ignite(org.apache.ignite.Ignite) UUID(java.util.UUID)

Aggregations

IgniteBiPredicate (org.apache.ignite.lang.IgniteBiPredicate)57 Ignite (org.apache.ignite.Ignite)36 UUID (java.util.UUID)28 IgniteCache (org.apache.ignite.IgniteCache)22 Test (org.junit.Test)22 List (java.util.List)21 Collection (java.util.Collection)18 Map (java.util.Map)18 HashMap (java.util.HashMap)17 CountDownLatch (java.util.concurrent.CountDownLatch)17 ClusterNode (org.apache.ignite.cluster.ClusterNode)17 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)17 ArrayList (java.util.ArrayList)16 IgniteConfiguration (org.apache.ignite.configuration.IgniteConfiguration)16 ScanQuery (org.apache.ignite.cache.query.ScanQuery)15 IgniteEx (org.apache.ignite.internal.IgniteEx)15 IgnitePredicate (org.apache.ignite.lang.IgnitePredicate)15 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)13 IgniteException (org.apache.ignite.IgniteException)13 CacheConfiguration (org.apache.ignite.configuration.CacheConfiguration)13