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

The following examples show how to use org.apache.ignite.IgniteCache#invoke() . 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: CacheNearDisabledTransactionalInvokeRestartSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected void updateCache(IgniteEx ignite, IgniteCache cache) {
    final int k = ThreadLocalRandom.current().nextInt(RANGE);

    final String[] keys = new String[KEYS_CNT];

    for (int i = 0; i < keys.length; i++)
        keys[i] = "key-" + k + "-" + i;

    for (String key : keys) {
        cache.invoke(key, new IncrementCacheEntryProcessor());

        AtomicLong prevVal = map.putIfAbsent(key, new AtomicLong(0));

        if (prevVal != null)
            prevVal.incrementAndGet();
    }
}
 
Example 2
Source File: IgnteCacheClientWriteBehindStoreNonCoalescingTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Update random key in async mode.
 *
 * @param cache Cache to use.
 * @return IgniteFuture.
 */
private IgniteFuture<?> updateKey(IgniteCache<Integer, Integer> cache) {
    IgniteCache asyncCache = cache.withAsync();

    // Using EntryProcessor.invokeAll to increment every value in place.
    asyncCache.invoke(rnd.nextInt(100), new EntryProcessor<Integer, Integer, Object>() {
        @Override public Object process(MutableEntry<Integer, Integer> entry, Object... arguments)
            throws EntryProcessorException {
            entry.setValue(entry.getValue() + 1);

            return null;
        }
    });

    return asyncCache.future();
}
 
Example 3
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param concurrency Concurrency.
 * @throws Exception If failed.
 */
private void checkTransformAfterRemove(TransactionConcurrency concurrency) throws Exception {
    IgniteCache<String, Integer> cache = jcache();

    cache.put("key", 4);

    Transaction tx = txShouldBeUsed() ? ignite(0).transactions().txStart(concurrency, READ_COMMITTED) : null;

    try {
        cache.remove("key");

        cache.invoke("key", INCR_PROCESSOR);
        cache.invoke("key", INCR_PROCESSOR);
        cache.invoke("key", INCR_PROCESSOR);

        if (tx != null)
            tx.commit();
    }
    finally {
        if (tx != null)
            tx.close();
    }

    assertEquals((Integer)3, cache.get("key"));
}
 
Example 4
Source File: CacheEntryProcessorExternalizableFailedTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param node Ignite node.
 * @param cache Node cache.
 * @param txConcurrency Transaction concurrency.
 * @param txIsolation TransactionIsolation.
 */
@SuppressWarnings({"unchecked", "ThrowableNotThrown"})
private void checkExplicitTxInvoke(Ignite node, IgniteCache cache, TransactionConcurrency txConcurrency,
    TransactionIsolation txIsolation) {
    try (final Transaction tx = node.transactions().txStart(txConcurrency, txIsolation)) {
        cache.put(KEY, WRONG_VALUE);

        cache.invoke(KEY, createEntryProcessor());

        GridTestUtils.assertThrowsWithCause(new Callable<Object>() {
            @Override public Object call() throws Exception {
                tx.commit();

                return null;
            }
        }, UnsupportedOperationException.class);
    }
}
 
Example 5
Source File: GridTransformSpringInjectionSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param cache Cache.
 * @throws Exception If failed.
 */
private void doTransformResourceInjection(IgniteCache<String, Integer> cache) throws Exception {
    final Collection<ResourceType> required = Arrays.asList(
        ResourceType.SPRING_APPLICATION_CONTEXT,
        ResourceType.SPRING_BEAN);

    Integer flags = cache.invoke(UUID.randomUUID().toString(), new SpringResourceInjectionEntryProcessor());

    assertTrue("Processor result is null", flags != null);

    log.info("Injection flag: " + Integer.toBinaryString(flags));

    Collection<ResourceType> notInjected = ResourceInfoSet.valueOf(flags).notInjected(required);

    if (!notInjected.isEmpty())
        fail("Can't inject resource(s): " + Arrays.toString(notInjected.toArray()));

    Set<String> keys = new HashSet<>(Arrays.asList(UUID.randomUUID().toString(),
        UUID.randomUUID().toString(),
        UUID.randomUUID().toString(),
        UUID.randomUUID().toString()));

    Map<String, EntryProcessorResult<Integer>> results = cache.invokeAll(keys,
        new SpringResourceInjectionEntryProcessor());

    assertEquals(keys.size(), results.size());

    for (EntryProcessorResult<Integer> res : results.values()) {
        Collection<ResourceType> notInjected1 = ResourceInfoSet.valueOf(res.get()).notInjected(required);

        if (!notInjected1.isEmpty())
            fail("Can't inject resource(s): " + Arrays.toString(notInjected1.toArray()));
    }
}
 
Example 6
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Tests invoke for single key.
 *
 * @param cache Cache.
 * @param required Expected injected resources.
 * @param async Use async API.
 * @param oldAsync Use old async API.
 */
private void checkResourceInjectionOnInvoke(IgniteCache<String, Integer> cache,
    Collection<ResourceType> required, boolean async, boolean oldAsync) {

    String key = UUID.randomUUID().toString();

    Integer flags;

    if (async) {
        if (oldAsync) {
            IgniteCache<String, Integer> acache = cache.withAsync();

            acache.invoke(key, new GridCacheAbstractFullApiSelfTest.ResourceInjectionEntryProcessor());

            flags = acache.<Integer>future().get();
        }
        else
            flags = cache.invokeAsync(key,
                new GridCacheAbstractFullApiSelfTest.ResourceInjectionEntryProcessor()).get();
    }
    else
        flags = cache.invoke(key, new GridCacheAbstractFullApiSelfTest.ResourceInjectionEntryProcessor());

    if (cache.isAsync())
        flags = cache.<Integer>future().get();

    assertTrue("Processor result is null", flags != null);

    Collection<ResourceType> notInjected = ResourceInfoSet.valueOf(flags).notInjected(required);

    if (!notInjected.isEmpty())
        fail("Can't inject resource(s): " + Arrays.toString(notInjected.toArray()));
}
 
Example 7
Source File: GridCacheAbstractMetricsSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param emptyCache Empty cache.
 * @throws IgniteCheckedException If failed.
 */
private void testReadOnlyInvocations(final boolean emptyCache) throws IgniteCheckedException {
    IgniteCache<Integer, Integer> cache0 = grid(0).cache(DEFAULT_CACHE_NAME);

    final Integer key = primaryKey(jcache(0));

    if (emptyCache)
        cache0.remove(key);
    else
        cache0.put(key, 0);

    cache0.invoke(key, readingProcessor);

    assertEquals(1, cache0.localMetrics().getEntryProcessorReadOnlyInvocations());

    if (emptyCache) {
        assertEquals(1, cache0.localMetrics().getEntryProcessorMisses());

        assertEquals(100f, cache0.localMetrics().getEntryProcessorMissPercentage());
        assertEquals(0f, cache0.localMetrics().getEntryProcessorHitPercentage());
    }
    else {
        assertEquals(1, cache0.localMetrics().getEntryProcessorHits());

        assertEquals(0f, cache0.localMetrics().getEntryProcessorMissPercentage());
        assertEquals(100f, cache0.localMetrics().getEntryProcessorHitPercentage());
    }

    for (int i = 1; i < gridCount(); i++)
        assertEquals(0, jcache(i).localMetrics().getEntryProcessorReadOnlyInvocations());

    assertEquals(1, cache0.localMetrics().getEntryProcessorInvocations());
}
 
Example 8
Source File: GridCacheAbstractMetricsSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
     * @throws IgniteCheckedException If failed.
     */
    private void testInvocationRemoves(boolean emptyCache) throws IgniteCheckedException {
        IgniteCache<Integer, Integer> cache0 = grid(0).cache(DEFAULT_CACHE_NAME);

        final Integer key = primaryKey(cache0);

        if (emptyCache)
            cache0.remove(key);
        else
            cache0.put(key, 0);

        cache0.invoke(key, removingProcessor);

        assertEquals(1, cache0.localMetrics().getEntryProcessorRemovals());

//        if (emptyCache) {
//            assertEquals(1, cache0.localMetrics().getEntryProcessorMisses());
//
//            assertEquals(100f, cache0.localMetrics().getEntryProcessorMissPercentage());
//            assertEquals(0f, cache0.localMetrics().getEntryProcessorHitPercentage());
//        }
//        else {
//            assertEquals(1, cache0.localMetrics().getEntryProcessorHits());
//
//            assertEquals(0f, cache0.localMetrics().getEntryProcessorMissPercentage());
//            assertEquals(100f, cache0.localMetrics().getEntryProcessorHitPercentage());
//        }
//
//        for (int i = 1; i < gridCount(); i++) {
//            Ignite ignite = ignite(i);
//
//            IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME);
//
//            if (affinity(cache).isPrimaryOrBackup(ignite.cluster().localNode(), key))
//                assertEquals(1, cache.localMetrics().getEntryProcessorRemovals());
//        }
//
//        assertEquals(1, cache0.localMetrics().getEntryProcessorInvocations());
    }
 
Example 9
Source File: CacheClientStoreSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testCorrectStore() throws Exception {
    nearEnabled = false;
    cacheMode = CacheMode.PARTITIONED;
    factory = new Factory1();

    startGrids(2);

    Ignite ignite = startClientGrid("client-1");

    IgniteCache<Object, Object> cache = ignite.cache(CACHE_NAME);

    cache.get(0);
    cache.getAll(F.asSet(0, 1));
    cache.getAndPut(0, 0);
    cache.getAndPutIfAbsent(0, 0);
    cache.getAndRemove(0);
    cache.getAndReplace(0, 0);
    cache.put(0, 0);
    cache.putAll(F.asMap(0, 0, 1, 1));
    cache.putIfAbsent(0, 0);
    cache.remove(0);
    cache.remove(0, 0);
    cache.removeAll(F.asSet(0, 1));
    cache.removeAll();
    cache.invoke(0, new EP());
    cache.invokeAll(F.asSet(0, 1), new EP());
}
 
Example 10
Source File: IgniteCacheEntryProcessorSequentialCallTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Test for sequential entry processor invoking not null value on primary cache.
 * In this test entry processor gets value from local node.
 *
 * @param transactionConcurrency Transaction concurrency.
 * @param transactionIsolation Transaction isolation.
 */
public void transactionInvokeSequentialCallOnPrimaryNode(TransactionConcurrency transactionConcurrency,
    TransactionIsolation transactionIsolation) throws Exception {
    TestKey key = new TestKey(1L);
    TestValue val = new TestValue();
    val.value("1");

    Ignite primaryIgnite;

    if (ignite(0).affinity(cacheName).isPrimary(ignite(0).cluster().localNode(), key))
        primaryIgnite = ignite(0);
    else
        primaryIgnite = ignite(1);

    IgniteCache<TestKey, TestValue> cache = primaryIgnite.cache(cacheName);

    cache.put(key, val);

    NotNullCacheEntryProcessor cacheEntryProcessor = new NotNullCacheEntryProcessor();

    try (Transaction transaction = primaryIgnite.transactions().txStart(transactionConcurrency,
        transactionIsolation)) {

        cache.invoke(key, cacheEntryProcessor);
        cache.invoke(key, cacheEntryProcessor);

        transaction.commit();
    }

    cache.remove(key);
}
 
Example 11
Source File: IgniteCacheConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param put Whether to put value.
 * @param concurrency Concurrency.
 * @param isolation Isolation.
 * @throws Exception If failed.
 */
private void checkInvokeReturnValue(boolean put,
    TransactionConcurrency concurrency,
    TransactionIsolation isolation)
    throws Exception {
    IgniteCache<Object, Object> cache = jcache();

    Object key = key(1);
    Object val1 = value(1);
    Object val2 = value(2);

    if (!put)
        cache.put(key, val1);

    Transaction tx = txShouldBeUsed() ? ignite(0).transactions().txStart(concurrency, isolation) : null;

    try {
        if (put)
            cache.put(key, val1);

        cache.invoke(key, INCR_PROCESSOR, dataMode);

        assertEquals(val2, cache.get(key));

        if (tx != null) {
            // Second get inside tx. Make sure read value is not transformed twice.
            assertEquals(val2, cache.get(key));

            tx.commit();
        }
    }
    finally {
        if (tx != null)
            tx.close();
    }
}
 
Example 12
Source File: IgniteCacheConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param concurrency Concurrency.
 * @throws Exception If failed.
 */
private void checkInvokeAfterRemove(TransactionConcurrency concurrency) throws Exception {
    IgniteCache<Object, Object> cache = jcache();

    Object key = key(1);

    cache.put(key, value(4));

    Transaction tx = txShouldBeUsed() ? ignite(0).transactions().txStart(concurrency, READ_COMMITTED) : null;

    try {
        cache.remove(key);

        cache.invoke(key, INCR_PROCESSOR, dataMode);
        cache.invoke(key, INCR_PROCESSOR, dataMode);
        cache.invoke(key, INCR_PROCESSOR, dataMode);

        if (tx != null)
            tx.commit();
    }
    finally {
        if (tx != null)
            tx.close();
    }

    assertEquals(value(3), cache.get(key));
}
 
Example 13
Source File: GridCacheNearMetricsSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes entry processor, which removes key from cache.
 *
 * @param cache Cache.
 * @param key Key.
 */
private void removeKeyByEntryProcessor(IgniteCache<Integer, Integer> cache, int key) {
    cache.invoke(key, new CacheEntryProcessor<Integer, Integer, Object>() {
        @Override public Object process(MutableEntry<Integer, Integer> entry,
            Object... arguments) throws EntryProcessorException {
            entry.remove();

            return null;
        }
    });
}
 
Example 14
Source File: GridCacheNearMetricsSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes entry processor, which sets value "1" for key into cache.
 *
 * @param cache Cache.
 * @param key Key.
 */
private void setValue1ByEntryProcessor(IgniteCache<Integer, Integer> cache, int key) {
    cache.invoke(key, new CacheEntryProcessor<Integer, Integer, Object>() {
        @Override public Object process(MutableEntry<Integer, Integer> entry,
            Object... arguments) throws EntryProcessorException {
            entry.setValue(1);

            return null;
        }
    });
}
 
Example 15
Source File: IgniteCacheEntryProcessorSequentialCallTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Test for sequential entry processor invoking not null value on near cache.
 * In this test entry processor fetches value from remote node.
 *
 * @param transactionConcurrency Transaction concurrency.
 * @param transactionIsolation Transaction isolation.
 */
public void transactionInvokeSequentialCallOnNearNode(TransactionConcurrency transactionConcurrency,
    TransactionIsolation transactionIsolation) throws Exception {
    TestKey key = new TestKey(1L);
    TestValue val = new TestValue();
    val.value("1");

    Ignite nearIgnite;
    Ignite primaryIgnite;

    if (ignite(0).affinity(cacheName).isPrimary(ignite(0).cluster().localNode(), key)) {
        primaryIgnite = ignite(0);

        nearIgnite = ignite(1);
    }
    else {
        primaryIgnite = ignite(1);

        nearIgnite = ignite(0);
    }

    primaryIgnite.cache(cacheName).put(key, val);

    IgniteCache<TestKey, TestValue> nearCache = nearIgnite.cache(cacheName);

    NotNullCacheEntryProcessor cacheEntryProcessor = new NotNullCacheEntryProcessor();

    try (Transaction transaction = nearIgnite.transactions().txStart(transactionConcurrency,
        transactionIsolation)) {

        nearCache.invoke(key, cacheEntryProcessor);
        nearCache.invoke(key, cacheEntryProcessor);

        transaction.commit();
    }

    primaryIgnite.cache(cacheName).remove(key);
}
 
Example 16
Source File: IgniteAlertsStore.java    From spring-boot-ignite with Apache License 2.0 5 votes vote down vote up
@Override
public void updateAlertEntry(String serviceId, String serviceCode, AlertEntry alertEntry) {
    final IgniteCache<String, AlertEntry> alertsCache = getAlertsCache();
    // update the alert entry via cache invoke for atomicity
    alertsCache.invoke(alertEntry.getAlertId(), (mutableEntry, objects) -> {
        if (mutableEntry.exists() && mutableEntry.getValue() != null) {
            logger.debug("updating alert entry into the cache store invoke: {},{}", serviceId, serviceCode);
            mutableEntry.setValue(alertEntry);
        } else {
            throw new ResourceNotFoundException(String.format("Alert for %s with %s not found", serviceId, serviceCode));
        }
        // by api design nothing needed here
        return null;
    });
}
 
Example 17
Source File: IgniteCacheBinaryEntryProcessorSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param cacheMode Cache mode to test.
 * @param atomicityMode Atomicity mode to test.
 * @throws Exception
 */
private void checkInvokeBinaryObject(CacheMode cacheMode, CacheAtomicityMode atomicityMode) throws Exception {
    Ignite client = ignite(SRV_CNT);

    IgniteCache<Integer, TestValue> clientCache = client.createCache(cacheConfiguration(cacheMode, atomicityMode));

    try {
        IgniteBinary binary = client.binary();

        for (int i = 0; i < 100; i++) {
            clientCache.put(i, new TestValue(i, "value-" + i));

            BinaryObjectBuilder bldr = binary.builder("NoClass");

            bldr.setField("val", i);
            bldr.setField("strVal", "value-" + i);

            clientCache.withKeepBinary().put(-(i + 1), bldr.build());
        }

        IgniteCache<Integer, BinaryObject> binaryClientCache = clientCache.withKeepBinary();

        for (int i = 0; i < 100; i++) {
            binaryClientCache.invoke(i, new TestEntryProcessor());
            binaryClientCache.invoke(-(i + 1), new TestEntryProcessor());
        }

        for (int g = 0; g < NODES; g++) {
            IgniteCache<Integer, TestValue> nodeCache = ignite(g).cache(DEFAULT_CACHE_NAME);
            IgniteCache<Integer, BinaryObject> nodeBinaryCache = nodeCache.withKeepBinary();

            for (int i = 0; i < 100; i++) {
                TestValue updated = nodeCache.get(i);

                assertEquals((Integer)(i + 1), updated.value());
                assertEquals("updated-" + i, updated.stringValue());

                BinaryObject updatedBinary = nodeBinaryCache.get(i);
                assertEquals(new Integer(i + 1), updatedBinary.field("val"));
                assertEquals("updated-" + i, updatedBinary.field("strVal"));

                updatedBinary = nodeBinaryCache.get(-(i + 1));
                assertEquals(new Integer(i + 1), updatedBinary.field("val"));
                assertEquals("updated-" + i, updatedBinary.field("strVal"));
            }
        }
    }
    finally {
        client.destroyCache(DEFAULT_CACHE_NAME);
    }
}
 
Example 18
Source File: CacheOffheapBatchIndexingSingleTypeTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Tests removal using EntryProcessor.
 *
 * @throws Exception If failed.
 */
@Test
public void testBatchRemove() throws Exception {
    Ignite ignite = grid(0);

    CacheConfiguration<Object, Object> ccfg = cacheConfiguration(
        new Class<?>[] {Integer.class, CacheOffheapBatchIndexingBaseTest.Organization.class});

    final IgniteCache<Object, Object> cache = ignite.createCache(ccfg);

    try {
        int iterations = 50;

        while (iterations-- >= 0) {
            int total = 1000;

            for (int id = 0; id < total; id++)
                cache.put(id, new CacheOffheapBatchIndexingBaseTest.Organization(id, "Organization " + id));

            cache.invoke(0, new CacheEntryProcessor<Object, Object, Object>() {
                @Override public Object process(MutableEntry<Object, Object> entry, Object... args) {
                    entry.remove();

                    return null;
                }
            });

            QueryCursor<List<?>> q = cache.query(new SqlFieldsQuery("select _key,_val from Organization where id=0"));

            assertEquals(0, q.getAll().size());

            q = cache.query(new SqlFieldsQuery("select _key,_val from Organization where id=1"));

            assertEquals(1, q.getAll().size());

            assertEquals(total - 1, cache.size());

            cache.removeAll();
        }
    }
    finally {
        cache.destroy();
    }
}
 
Example 19
Source File: IgniteInvokeBenchmark.java    From ignite with Apache License 2.0 3 votes vote down vote up
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
    int key = nextRandom(args.range());

    IgniteCache<Integer, Object> cache = cacheForOperation();

    cache.invoke(key, new SetValueEntryProcessor(new SampleValue(key)));

    return true;
}
 
Example 20
Source File: CacheNearDisabledAtomicInvokeRestartSelfTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/** {@inheritDoc} */
@Override protected void updateCache(IgniteEx ignite, IgniteCache cache) {
    final int k = ThreadLocalRandom.current().nextInt(RANGE);

    String key = "key-" + k;

    AtomicLong nextAtomicVal = nextValMap.putIfAbsent(key, new AtomicLong(FIRST_VAL));

    Long nextVal = FIRST_VAL;

    if (nextAtomicVal != null)
        nextVal = nextAtomicVal.incrementAndGet();

    cache.invoke(key, new AddInSetEntryProcessor(), nextVal);
}