Search in sources :

Example 21 with EntryProcessor

use of javax.cache.processor.EntryProcessor in project ignite by apache.

the class GridCacheCommandHandler method appendOrPrepend.

/**
     * Handles append and prepend commands.
     *
     * @param ctx Kernal context.
     * @param cache Cache.
     * @param key Key.
     * @param req Request.
     * @param prepend Whether to prepend.
     * @return Future of operation result.
     * @throws IgniteCheckedException In case of any exception.
     */
private static IgniteInternalFuture<?> appendOrPrepend(final GridKernalContext ctx, final IgniteInternalCache<Object, Object> cache, final Object key, GridRestCacheRequest req, final boolean prepend) throws IgniteCheckedException {
    assert cache != null;
    assert key != null;
    assert req != null;
    final Object val = req.value();
    if (val == null)
        throw new IgniteCheckedException(GridRestCommandHandlerAdapter.missingParameter("val"));
    return ctx.closure().callLocalSafe(new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            EntryProcessorResult<Boolean> res = cache.invoke(key, new EntryProcessor<Object, Object, Boolean>() {

                @Override
                public Boolean process(MutableEntry<Object, Object> entry, Object... objects) throws EntryProcessorException {
                    try {
                        Object curVal = entry.getValue();
                        if (curVal == null)
                            return false;
                        // Modify current value with appendix one.
                        Object newVal = appendOrPrepend(curVal, val, !prepend);
                        // Put new value asynchronously.
                        entry.setValue(newVal);
                        return true;
                    } catch (IgniteCheckedException e) {
                        throw new EntryProcessorException(e);
                    }
                }
            });
            try {
                return res.get();
            } catch (EntryProcessorException e) {
                throw new IgniteCheckedException(e.getCause());
            }
        }
    }, false);
}
Also used : EntryProcessor(javax.cache.processor.EntryProcessor) EntryProcessorResult(javax.cache.processor.EntryProcessorResult) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) EntryProcessorException(javax.cache.processor.EntryProcessorException) MutableEntry(javax.cache.processor.MutableEntry) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) EntryProcessorException(javax.cache.processor.EntryProcessorException)

Example 22 with EntryProcessor

use of javax.cache.processor.EntryProcessor in project ignite by apache.

the class CacheContinuousQueryExecuteInPrimaryTest method executeQuery.

private void executeQuery(IgniteCache<Integer, String> cache, ContinuousQuery<Integer, String> qry, boolean isTransactional) {
    try (QueryCursor<Cache.Entry<Integer, String>> qryCursor = cache.query(qry)) {
        Transaction tx = null;
        if (isTransactional)
            tx = cache.unwrap(Ignite.class).transactions().txStart();
        try {
            for (int key = 0; key < 8; key++) cache.put(key, Integer.toString(key));
            Map<Integer, String> map = new HashMap<>(8);
            for (int key = 8; key < 16; key++) map.put(key, Integer.toString(key));
            cache.putAll(map);
            if (isTransactional)
                tx.commit();
        } finally {
            if (isTransactional)
                tx.close();
        }
        for (int key = 0; key < 8; key++) {
            cache.invoke(key, new EntryProcessor<Integer, String, Object>() {

                @Override
                public Object process(MutableEntry<Integer, String> entry, Object... objects) throws EntryProcessorException {
                    entry.setValue(Integer.toString(entry.getKey() + 1));
                    return null;
                }
            });
        }
        Map<Integer, EntryProcessor<Integer, String, Object>> invokeMap = new HashMap<>(8);
        for (int key = 8; key < 16; key++) {
            invokeMap.put(key, new EntryProcessor<Integer, String, Object>() {

                @Override
                public Object process(MutableEntry<Integer, String> entry, Object... objects) throws EntryProcessorException {
                    entry.setValue(Integer.toString(entry.getKey() - 1));
                    return null;
                }
            });
        }
        cache.invokeAll(invokeMap);
    }
}
Also used : HashMap(java.util.HashMap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MutableEntry(javax.cache.processor.MutableEntry) EntryProcessor(javax.cache.processor.EntryProcessor) Transaction(org.apache.ignite.transactions.Transaction) EntryProcessorException(javax.cache.processor.EntryProcessorException)

Example 23 with EntryProcessor

use of javax.cache.processor.EntryProcessor in project ignite by apache.

the class GridCacheInterceptorAbstractSelfTest method cacheUpdate.

/**
     * @param grid Grid index.
     * @param rmv If {@code true} then executes remove.
     * @param op Operation type.
     * @param key Key.
     * @param val Value.
     * @param expOld Expected expOld value.
     * @param expRmvRet Expected remove result.
     * @throws Exception If failed.
     */
@SuppressWarnings("unchecked")
private void cacheUpdate(int grid, boolean rmv, Operation op, String key, final Integer val, @Nullable final Integer expOld, @Nullable final Integer expRmvRet) throws Exception {
    IgniteCache<String, Integer> cache = jcache(grid);
    if (rmv) {
        assertNull(val);
        switch(op) {
            case UPDATE:
                {
                    assertEquals(expRmvRet, cache.getAndRemove(key));
                    break;
                }
            case UPDATEX:
                {
                    cache.remove(key);
                    break;
                }
            case TRANSFORM:
                {
                    cache.invoke(key, new EntryProcessor<String, Integer, Void>() {

                        @Override
                        public Void process(MutableEntry<String, Integer> e, Object... args) {
                            Integer old = e.getValue();
                            assertEquals(expOld, old);
                            e.remove();
                            return null;
                        }
                    });
                    break;
                }
            default:
                fail();
        }
    } else {
        switch(op) {
            case UPDATE:
                {
                    assertEquals(expOld, cache.getAndPut(key, val));
                    break;
                }
            case UPDATEX:
                {
                    cache.put(key, val);
                    break;
                }
            case TRANSFORM:
                {
                    cache.invoke(key, new EntryProcessor<String, Integer, Void>() {

                        @Override
                        public Void process(MutableEntry<String, Integer> e, Object... args) {
                            Integer old = e.getValue();
                            assertEquals(expOld, old);
                            e.setValue(val);
                            return null;
                        }
                    });
                    break;
                }
            default:
                fail();
        }
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EntryProcessor(javax.cache.processor.EntryProcessor) MutableEntry(javax.cache.processor.MutableEntry)

Example 24 with EntryProcessor

use of javax.cache.processor.EntryProcessor in project ignite by apache.

the class IgniteTxLocalAdapter method addInvokeResult.

/**
     * @param txEntry Entry.
     * @param cacheVal Value.
     * @param ret Return value to update.
     * @param ver Entry version.
     */
protected final void addInvokeResult(IgniteTxEntry txEntry, CacheObject cacheVal, GridCacheReturn ret, GridCacheVersion ver) {
    GridCacheContext ctx = txEntry.context();
    Object key0 = null;
    Object val0 = null;
    try {
        Object res = null;
        for (T2<EntryProcessor<Object, Object, Object>, Object[]> t : txEntry.entryProcessors()) {
            CacheInvokeEntry<Object, Object> invokeEntry = new CacheInvokeEntry<>(txEntry.key(), key0, cacheVal, val0, ver, txEntry.keepBinary(), txEntry.cached());
            EntryProcessor<Object, Object, ?> entryProcessor = t.get1();
            res = entryProcessor.process(invokeEntry, t.get2());
            val0 = invokeEntry.value();
            key0 = invokeEntry.key();
        }
        if (res != null)
            ret.addEntryProcessResult(ctx, txEntry.key(), key0, res, null, txEntry.keepBinary());
    } catch (Exception e) {
        ret.addEntryProcessResult(ctx, txEntry.key(), key0, null, e, txEntry.keepBinary());
    }
}
Also used : EntryProcessor(javax.cache.processor.EntryProcessor) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) CacheInvokeEntry(org.apache.ignite.internal.processors.cache.CacheInvokeEntry) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) GridCacheFilterFailedException(org.apache.ignite.internal.processors.cache.GridCacheFilterFailedException) IgniteTxRollbackCheckedException(org.apache.ignite.internal.transactions.IgniteTxRollbackCheckedException) IgniteTxTimeoutCheckedException(org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) TransactionDeadlockException(org.apache.ignite.transactions.TransactionDeadlockException) StorageException(org.apache.ignite.internal.pagemem.wal.StorageException) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) GridCacheIndexUpdateException(org.apache.ignite.internal.processors.cache.GridCacheIndexUpdateException) IgniteTxHeuristicCheckedException(org.apache.ignite.internal.transactions.IgniteTxHeuristicCheckedException) GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException)

Example 25 with EntryProcessor

use of javax.cache.processor.EntryProcessor in project ignite by apache.

the class IgfsMetaManager method createFileOrDirectory.

/**
     * Create file or directory.
     *
     * @param dir Directory flag.
     * @param pathIds Path IDs.
     * @param lockInfos Lock infos.
     * @param dirProps Directory properties.
     * @param fileProps File properties.
     * @param blockSize Block size.
     * @param affKey Affinity key.
     * @param evictExclude Evict exclude flag.
     * @param secondaryCtx Secondary file system create context.
     * @param secondaryOutHolder Secondary output stream holder.
     * @return Result.
     * @throws IgniteCheckedException If failed.
     */
@SuppressWarnings("unchecked")
private IgfsPathsCreateResult createFileOrDirectory(boolean dir, IgfsPathIds pathIds, Map<IgniteUuid, IgfsEntryInfo> lockInfos, Map<String, String> dirProps, Map<String, String> fileProps, int blockSize, @Nullable IgniteUuid affKey, boolean evictExclude, @Nullable IgfsSecondaryFileSystemCreateContext secondaryCtx, @Nullable T1<OutputStream> secondaryOutHolder) throws IgniteCheckedException {
    // This is our starting point.
    int lastExistingIdx = pathIds.lastExistingIndex();
    IgfsEntryInfo lastExistingInfo = lockInfos.get(pathIds.lastExistingId());
    // If current info already contains entry with the same name as it's child, then something
    // has changed concurrently. We must re-try because we cannot get info of this unexpected
    // element due to possible deadlocks.
    int curIdx = lastExistingIdx + 1;
    String curPart = pathIds.part(curIdx);
    IgniteUuid curId = pathIds.surrogateId(curIdx);
    if (lastExistingInfo.hasChild(curPart))
        return null;
    // Create entry in the secondary file system if needed.
    if (secondaryCtx != null) {
        assert secondaryOutHolder != null;
        secondaryOutHolder.set(secondaryCtx.create());
    }
    Map<IgniteUuid, EntryProcessor> procMap = new HashMap<>();
    // First step: add new entry to the last existing element.
    procMap.put(lastExistingInfo.id(), new IgfsMetaDirectoryListingAddProcessor(curPart, new IgfsListingEntry(curId, dir || !pathIds.isLastIndex(curIdx))));
    // Events support.
    IgfsPath lastCreatedPath = pathIds.lastExistingPath();
    List<IgfsPath> createdPaths = new ArrayList<>(pathIds.count() - curIdx);
    // Second step: create middle directories.
    long curTime = System.currentTimeMillis();
    while (curIdx < pathIds.count() - 1) {
        lastCreatedPath = new IgfsPath(lastCreatedPath, curPart);
        int nextIdx = curIdx + 1;
        String nextPart = pathIds.part(nextIdx);
        IgniteUuid nextId = pathIds.surrogateId(nextIdx);
        long accessTime;
        long modificationTime;
        Map<String, String> props;
        if (secondaryCtx != null) {
            accessTime = 0L;
            modificationTime = 0L;
            props = null;
        } else {
            accessTime = curTime;
            modificationTime = curTime;
            props = dirProps;
        }
        procMap.put(curId, new IgfsMetaDirectoryCreateProcessor(accessTime, modificationTime, props, nextPart, new IgfsListingEntry(nextId, dir || !pathIds.isLastIndex(nextIdx))));
        // Save event.
        createdPaths.add(lastCreatedPath);
        // Advance things further.
        curIdx++;
        curPart = nextPart;
        curId = nextId;
    }
    // Third step: create leaf.
    if (dir) {
        long accessTime;
        long modificationTime;
        Map<String, String> props;
        if (secondaryCtx != null) {
            accessTime = 0L;
            modificationTime = 0L;
            props = null;
        } else {
            accessTime = curTime;
            modificationTime = curTime;
            props = dirProps;
        }
        procMap.put(curId, new IgfsMetaDirectoryCreateProcessor(accessTime, modificationTime, props));
    } else {
        long newAccessTime;
        long newModificationTime;
        Map<String, String> newProps;
        long newLen;
        int newBlockSize;
        if (secondaryCtx != null) {
            newAccessTime = 0L;
            newModificationTime = 0L;
            newProps = null;
        } else {
            newAccessTime = curTime;
            newModificationTime = curTime;
            newProps = fileProps;
        }
        newLen = 0L;
        newBlockSize = blockSize;
        procMap.put(curId, new IgfsMetaFileCreateProcessor(newAccessTime, newModificationTime, newProps, newBlockSize, affKey, createFileLockId(false), evictExclude, newLen));
    }
    createdPaths.add(pathIds.path());
    // Execute cache operations.
    Map<Object, EntryProcessorResult> invokeRes = ((IgniteInternalCache) id2InfoPrj).invokeAll(procMap);
    IgfsEntryInfo info = (IgfsEntryInfo) invokeRes.get(curId).get();
    return new IgfsPathsCreateResult(createdPaths, info);
}
Also used : IgfsMetaDirectoryListingAddProcessor(org.apache.ignite.internal.processors.igfs.meta.IgfsMetaDirectoryListingAddProcessor) HashMap(java.util.HashMap) IgfsMetaFileCreateProcessor(org.apache.ignite.internal.processors.igfs.meta.IgfsMetaFileCreateProcessor) ArrayList(java.util.ArrayList) IgniteInternalCache(org.apache.ignite.internal.processors.cache.IgniteInternalCache) IgfsPath(org.apache.ignite.igfs.IgfsPath) EntryProcessor(javax.cache.processor.EntryProcessor) EntryProcessorResult(javax.cache.processor.EntryProcessorResult) IgniteUuid(org.apache.ignite.lang.IgniteUuid) IgfsMetaDirectoryCreateProcessor(org.apache.ignite.internal.processors.igfs.meta.IgfsMetaDirectoryCreateProcessor)

Aggregations

EntryProcessor (javax.cache.processor.EntryProcessor)26 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)12 ArrayList (java.util.ArrayList)10 HashMap (java.util.HashMap)9 CacheObject (org.apache.ignite.internal.processors.cache.CacheObject)9 KeyCacheObject (org.apache.ignite.internal.processors.cache.KeyCacheObject)9 LinkedHashMap (java.util.LinkedHashMap)8 GridCacheEntryRemovedException (org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException)7 CacheInvokeEntry (org.apache.ignite.internal.processors.cache.CacheInvokeEntry)6 GridCacheVersion (org.apache.ignite.internal.processors.cache.version.GridCacheVersion)6 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)5 Map (java.util.Map)4 EntryProcessorResult (javax.cache.processor.EntryProcessorResult)4 MutableEntry (javax.cache.processor.MutableEntry)4 IgniteException (org.apache.ignite.IgniteException)4 StorageException (org.apache.ignite.internal.pagemem.wal.StorageException)4 CacheOperationContext (org.apache.ignite.internal.processors.cache.CacheOperationContext)4 IgniteTxTimeoutCheckedException (org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException)4 GridClosureException (org.apache.ignite.internal.util.lang.GridClosureException)4 SQLException (java.sql.SQLException)3