Search in sources :

Example 6 with ExpiryPolicy

use of javax.cache.expiry.ExpiryPolicy in project ignite by apache.

the class GridDhtAtomicCache method get0.

/**
     *  @param key Key.
     *  @param deserializeBinary Deserialize binary.
     *  @param needVer Need version.
     *  @return Value.
     *  @throws IgniteCheckedException If failed.
     */
@Nullable
public V get0(K key, boolean deserializeBinary, boolean needVer) throws IgniteCheckedException {
    ctx.checkSecurity(SecurityPermission.CACHE_READ);
    if (keyCheck)
        validateCacheKey(key);
    String taskName = ctx.kernalContext().job().currentTaskName();
    CacheOperationContext opCtx = ctx.operationContextPerCall();
    UUID subjId = ctx.subjectIdPerCall(null, opCtx);
    final ExpiryPolicy expiryPlc = opCtx != null ? opCtx.expiry() : null;
    final boolean skipStore = opCtx != null && opCtx.skipStore();
    try {
        return getAsync0(ctx.toCacheKeyObject(key), !ctx.config().isReadFromBackup(), subjId, taskName, deserializeBinary, opCtx != null && opCtx.recovery(), expiryPlc, false, skipStore, true, needVer).get();
    } catch (IgniteException e) {
        if (e.getCause(IgniteCheckedException.class) != null)
            throw e.getCause(IgniteCheckedException.class);
        else
            throw e;
    }
}
Also used : CacheOperationContext(org.apache.ignite.internal.processors.cache.CacheOperationContext) IgniteException(org.apache.ignite.IgniteException) IgniteCacheExpiryPolicy(org.apache.ignite.internal.processors.cache.IgniteCacheExpiryPolicy) ExpiryPolicy(javax.cache.expiry.ExpiryPolicy) UUID(java.util.UUID) Nullable(org.jetbrains.annotations.Nullable)

Example 7 with ExpiryPolicy

use of javax.cache.expiry.ExpiryPolicy in project ignite by apache.

the class WebSessionFilter method cacheWithExpiryPolicy.

/**
 * @param maxInactiveInteval Interval to use in expiry policy.
 * @param cache Cache.
 * @param <T> Cached object type.
 * @return Cache with expiry policy if {@code maxInactiveInteval} greater than zero.
 */
private <T> IgniteCache<String, T> cacheWithExpiryPolicy(final int maxInactiveInteval, final IgniteCache<String, T> cache) {
    if (maxInactiveInteval > 0) {
        long ttl = maxInactiveInteval * 1000L;
        ExpiryPolicy plc = new ModifiedExpiryPolicy(new Duration(MILLISECONDS, ttl));
        return cache.withExpiryPolicy(plc);
    }
    return cache;
}
Also used : ModifiedExpiryPolicy(javax.cache.expiry.ModifiedExpiryPolicy) ExpiryPolicy(javax.cache.expiry.ExpiryPolicy) Duration(javax.cache.expiry.Duration) ModifiedExpiryPolicy(javax.cache.expiry.ModifiedExpiryPolicy)

Example 8 with ExpiryPolicy

use of javax.cache.expiry.ExpiryPolicy in project ignite by apache.

the class GridManagerAdapter method onKernalStart.

/**
 * {@inheritDoc}
 */
@Override
public final void onKernalStart(boolean active) throws IgniteCheckedException {
    for (final IgniteSpi spi : spis) {
        try {
            spi.onContextInitialized(new IgniteSpiContext() {

                @Override
                public boolean isStopping() {
                    return ctx.isStopping();
                }

                @Override
                public Collection<ClusterNode> remoteNodes() {
                    return ctx.discovery().remoteNodes();
                }

                @Override
                public Collection<ClusterNode> nodes() {
                    return ctx.discovery().allNodes();
                }

                @Override
                public ClusterNode localNode() {
                    return ctx.discovery().localNode();
                }

                @Override
                public Collection<ClusterNode> remoteDaemonNodes() {
                    final Collection<ClusterNode> all = ctx.discovery().daemonNodes();
                    return !localNode().isDaemon() ? all : F.view(all, new IgnitePredicate<ClusterNode>() {

                        @Override
                        public boolean apply(ClusterNode n) {
                            return n.isDaemon();
                        }
                    });
                }

                @Nullable
                @Override
                public ClusterNode node(UUID nodeId) {
                    A.notNull(nodeId, "nodeId");
                    return ctx.discovery().node(nodeId);
                }

                @Override
                public boolean pingNode(UUID nodeId) {
                    A.notNull(nodeId, "nodeId");
                    try {
                        return ctx.discovery().pingNode(nodeId);
                    } catch (IgniteCheckedException e) {
                        throw U.convertException(e);
                    }
                }

                @Override
                public void send(ClusterNode node, Serializable msg, String topic) throws IgniteSpiException {
                    A.notNull(node, "node");
                    A.notNull(msg, "msg");
                    A.notNull(topic, "topic");
                    try {
                        if (msg instanceof Message)
                            ctx.io().sendToCustomTopic(node, topic, (Message) msg, SYSTEM_POOL);
                        else
                            ctx.io().sendUserMessage(Collections.singletonList(node), msg, topic, false, 0, false);
                    } catch (IgniteCheckedException e) {
                        throw unwrapException(e);
                    }
                }

                @Override
                public void addLocalMessageListener(Object topic, IgniteBiPredicate<UUID, ?> p) {
                    A.notNull(topic, "topic");
                    A.notNull(p, "p");
                    ctx.io().addUserMessageListener(topic, p);
                }

                @Override
                public void removeLocalMessageListener(Object topic, IgniteBiPredicate<UUID, ?> p) {
                    A.notNull(topic, "topic");
                    A.notNull(topic, "p");
                    ctx.io().removeUserMessageListener(topic, p);
                }

                @SuppressWarnings("deprecation")
                @Override
                public void addMessageListener(GridMessageListener lsnr, String topic) {
                    A.notNull(lsnr, "lsnr");
                    A.notNull(topic, "topic");
                    ctx.io().addMessageListener(topic, lsnr);
                }

                @SuppressWarnings("deprecation")
                @Override
                public boolean removeMessageListener(GridMessageListener lsnr, String topic) {
                    A.notNull(lsnr, "lsnr");
                    A.notNull(topic, "topic");
                    return ctx.io().removeMessageListener(topic, lsnr);
                }

                @Override
                public void addLocalEventListener(GridLocalEventListener lsnr, int... types) {
                    A.notNull(lsnr, "lsnr");
                    ctx.event().addLocalEventListener(lsnr, types);
                }

                @Override
                public boolean removeLocalEventListener(GridLocalEventListener lsnr) {
                    A.notNull(lsnr, "lsnr");
                    return ctx.event().removeLocalEventListener(lsnr);
                }

                @Override
                public boolean isEventRecordable(int... types) {
                    for (int t : types) if (!ctx.event().isRecordable(t))
                        return false;
                    return true;
                }

                @Override
                public void recordEvent(Event evt) {
                    A.notNull(evt, "evt");
                    if (ctx.event().isRecordable(evt.type()))
                        ctx.event().record(evt);
                }

                @Override
                public void registerPort(int port, IgnitePortProtocol proto) {
                    ctx.ports().registerPort(port, proto, spi.getClass());
                }

                @Override
                public void deregisterPort(int port, IgnitePortProtocol proto) {
                    ctx.ports().deregisterPort(port, proto, spi.getClass());
                }

                @Override
                public void deregisterPorts() {
                    ctx.ports().deregisterPorts(spi.getClass());
                }

                @Nullable
                @Override
                public <K, V> V get(String cacheName, K key) {
                    return ctx.cache().<K, V>jcache(cacheName).get(key);
                }

                @Nullable
                @Override
                public <K, V> V put(String cacheName, K key, V val, long ttl) {
                    try {
                        if (ttl > 0) {
                            ExpiryPolicy plc = new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl));
                            IgniteCache<K, V> cache = ctx.cache().<K, V>publicJCache(cacheName).withExpiryPolicy(plc);
                            return cache.getAndPut(key, val);
                        } else
                            return ctx.cache().<K, V>jcache(cacheName).getAndPut(key, val);
                    } catch (IgniteCheckedException e) {
                        throw CU.convertToCacheException(e);
                    }
                }

                @Nullable
                @Override
                public <K, V> V putIfAbsent(String cacheName, K key, V val, long ttl) {
                    try {
                        if (ttl > 0) {
                            ExpiryPolicy plc = new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl));
                            IgniteCache<K, V> cache = ctx.cache().<K, V>publicJCache(cacheName).withExpiryPolicy(plc);
                            return cache.getAndPutIfAbsent(key, val);
                        } else
                            return ctx.cache().<K, V>jcache(cacheName).getAndPutIfAbsent(key, val);
                    } catch (IgniteCheckedException e) {
                        throw CU.convertToCacheException(e);
                    }
                }

                @Nullable
                @Override
                public <K, V> V remove(String cacheName, K key) {
                    return ctx.cache().<K, V>jcache(cacheName).getAndRemove(key);
                }

                @Override
                public <K> boolean containsKey(String cacheName, K key) {
                    return ctx.cache().cache(cacheName).containsKey(key);
                }

                @Override
                public int partition(String cacheName, Object key) {
                    return ctx.cache().cache(cacheName).affinity().partition(key);
                }

                @Override
                public IgniteNodeValidationResult validateNode(ClusterNode node) {
                    for (GridComponent comp : ctx) {
                        IgniteNodeValidationResult err = comp.validateNode(node);
                        if (err != null)
                            return err;
                    }
                    return null;
                }

                @Nullable
                @Override
                public IgniteNodeValidationResult validateNode(ClusterNode node, DiscoveryDataBag discoData) {
                    for (GridComponent comp : ctx) {
                        if (comp.discoveryDataType() == null)
                            continue;
                        IgniteNodeValidationResult err = comp.validateNode(node, discoData.newJoinerDiscoveryData(comp.discoveryDataType().ordinal()));
                        if (err != null)
                            return err;
                    }
                    return null;
                }

                @Override
                public Collection<SecuritySubject> authenticatedSubjects() {
                    try {
                        return ctx.security().authenticatedSubjects();
                    } catch (IgniteCheckedException e) {
                        throw U.convertException(e);
                    }
                }

                @Override
                public SecuritySubject authenticatedSubject(UUID subjId) {
                    try {
                        return ctx.security().authenticatedSubject(subjId);
                    } catch (IgniteCheckedException e) {
                        throw U.convertException(e);
                    }
                }

                @Override
                public MessageFormatter messageFormatter() {
                    return ctx.io().formatter();
                }

                @Override
                public MessageFactory messageFactory() {
                    return ctx.io().messageFactory();
                }

                @Override
                public boolean tryFailNode(UUID nodeId, @Nullable String warning) {
                    return ctx.discovery().tryFailNode(nodeId, warning);
                }

                @Override
                public void failNode(UUID nodeId, @Nullable String warning) {
                    ctx.discovery().failNode(nodeId, warning);
                }

                @Override
                public void addTimeoutObject(IgniteSpiTimeoutObject obj) {
                    ctx.timeout().addTimeoutObject(new GridSpiTimeoutObject(obj));
                }

                @Override
                public void removeTimeoutObject(IgniteSpiTimeoutObject obj) {
                    ctx.timeout().removeTimeoutObject(new GridSpiTimeoutObject(obj));
                }

                @Override
                public Map<String, Object> nodeAttributes() {
                    return ctx.nodeAttributes();
                }

                /**
                 * @param e Exception to handle.
                 * @return GridSpiException Converted exception.
                 */
                private IgniteSpiException unwrapException(IgniteCheckedException e) {
                    // Avoid double-wrapping.
                    if (e.getCause() instanceof IgniteSpiException)
                        return (IgniteSpiException) e.getCause();
                    return new IgniteSpiException("Failed to execute SPI context method.", e);
                }
            });
        } catch (IgniteSpiException e) {
            throw new IgniteCheckedException("Failed to initialize SPI context.", e);
        }
    }
    onKernalStart0();
}
Also used : IgniteSpiContext(org.apache.ignite.spi.IgniteSpiContext) Serializable(java.io.Serializable) IgniteSpiTimeoutObject(org.apache.ignite.spi.IgniteSpiTimeoutObject) Message(org.apache.ignite.plugin.extensions.communication.Message) GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) IgniteNodeValidationResult(org.apache.ignite.spi.IgniteNodeValidationResult) GridComponent(org.apache.ignite.internal.GridComponent) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) MessageFormatter(org.apache.ignite.plugin.extensions.communication.MessageFormatter) GridSpiTimeoutObject(org.apache.ignite.internal.processors.timeout.GridSpiTimeoutObject) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgnitePortProtocol(org.apache.ignite.spi.IgnitePortProtocol) DiscoveryDataBag(org.apache.ignite.spi.discovery.DiscoveryDataBag) TouchedExpiryPolicy(javax.cache.expiry.TouchedExpiryPolicy) ExpiryPolicy(javax.cache.expiry.ExpiryPolicy) TouchedExpiryPolicy(javax.cache.expiry.TouchedExpiryPolicy) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) UUID(java.util.UUID) ClusterNode(org.apache.ignite.cluster.ClusterNode) MessageFactory(org.apache.ignite.plugin.extensions.communication.MessageFactory) SecuritySubject(org.apache.ignite.plugin.security.SecuritySubject) IgniteCache(org.apache.ignite.IgniteCache) IgniteSpi(org.apache.ignite.spi.IgniteSpi) Duration(javax.cache.expiry.Duration) Collection(java.util.Collection) Event(org.apache.ignite.events.Event) IgniteSpiTimeoutObject(org.apache.ignite.spi.IgniteSpiTimeoutObject) GridSpiTimeoutObject(org.apache.ignite.internal.processors.timeout.GridSpiTimeoutObject) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) Nullable(org.jetbrains.annotations.Nullable)

Example 9 with ExpiryPolicy

use of javax.cache.expiry.ExpiryPolicy in project ignite by apache.

the class GridCacheAdapter method loadAll.

/**
 * @param keys Keys.
 * @param replaceExisting Replace existing values flag.
 * @return Load future.
 */
public IgniteInternalFuture<?> loadAll(final Set<? extends K> keys, boolean replaceExisting) {
    A.notNull(keys, "keys");
    for (Object key : keys) A.notNull(key, "key");
    if (!ctx.store().configured())
        return new GridFinishedFuture<>();
    CacheOperationContext opCtx = ctx.operationContextPerCall();
    ExpiryPolicy plc = opCtx != null ? opCtx.expiry() : null;
    final boolean keepBinary = opCtx != null && opCtx.isKeepBinary();
    if (replaceExisting) {
        if (ctx.store().isLocal())
            return runLoadKeysCallable(keys, plc, keepBinary, true);
        else {
            return ctx.closures().callLocalSafe(new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    localLoadAndUpdate(keys);
                    return null;
                }
            });
        }
    } else
        return runLoadKeysCallable(keys, plc, keepBinary, false);
}
Also used : ExpiryPolicy(javax.cache.expiry.ExpiryPolicy) IgniteExternalizableExpiryPolicy(org.apache.ignite.internal.processors.cache.distributed.IgniteExternalizableExpiryPolicy) IgniteTxRollbackCheckedException(org.apache.ignite.internal.transactions.IgniteTxRollbackCheckedException) InvalidObjectException(java.io.InvalidObjectException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) EntryProcessorException(javax.cache.processor.EntryProcessorException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) ClusterTopologyServerNotFoundException(org.apache.ignite.internal.cluster.ClusterTopologyServerNotFoundException) IOException(java.io.IOException) ObjectStreamException(java.io.ObjectStreamException) IgniteException(org.apache.ignite.IgniteException) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) ClusterTopologyException(org.apache.ignite.cluster.ClusterTopologyException) NoSuchElementException(java.util.NoSuchElementException) IgniteTxHeuristicCheckedException(org.apache.ignite.internal.transactions.IgniteTxHeuristicCheckedException) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException) GridDhtInvalidPartitionException(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtInvalidPartitionException)

Example 10 with ExpiryPolicy

use of javax.cache.expiry.ExpiryPolicy in project ignite by apache.

the class IgnitePersistentStoreCacheGroupsTest method _testExpiryPolicy.

/**
 * @throws Exception If failed.
 */
public void _testExpiryPolicy() throws Exception {
    long ttl = 10000;
    CacheConfiguration[] ccfgs1 = new CacheConfiguration[5];
    ccfgs1[0] = cacheConfiguration(GROUP1, "c1", PARTITIONED, ATOMIC, 1);
    ccfgs1[1] = cacheConfiguration(GROUP1, "c2", PARTITIONED, TRANSACTIONAL, 1);
    ccfgs1[2] = cacheConfiguration(GROUP2, "c3", PARTITIONED, ATOMIC, 1);
    ccfgs1[3] = cacheConfiguration(GROUP2, "c4", PARTITIONED, TRANSACTIONAL, 1);
    ccfgs1[4] = cacheConfiguration(null, "c5", PARTITIONED, ATOMIC, 1);
    String[] caches = { "c1", "c2", "c3", "c4", "c5" };
    startGrids(3);
    Ignite node = ignite(0);
    node.active(true);
    node.createCaches(Arrays.asList(ccfgs1));
    ExpiryPolicy plc = new PlatformExpiryPolicy(ttl, -2, -2);
    for (String cacheName : caches) {
        IgniteCache<Object, Object> cache = node.cache(cacheName).withExpiryPolicy(plc);
        for (int i = 0; i < entriesCount(); i++) cache.put(i, cacheName + i);
    }
    long deadline = System.currentTimeMillis() + (long) (ttl * 1.2);
    stopAllGrids();
    startGrids(3);
    node = ignite(0);
    node.active(true);
    for (String cacheName : caches) {
        IgniteCache<Object, Object> cache = node.cache(cacheName);
        for (int i = 0; i < entriesCount(); i++) assertEquals(cacheName + i, cache.get(i));
        assertEquals(entriesCount(), cache.size());
    }
    // Wait for expiration.
    Thread.sleep(Math.max(deadline - System.currentTimeMillis(), 0));
    for (String cacheName : caches) {
        IgniteCache<Object, Object> cache = node.cache(cacheName);
        assertEquals(0, cache.size());
    }
}
Also used : PlatformExpiryPolicy(org.apache.ignite.internal.processors.platform.cache.expiry.PlatformExpiryPolicy) ExpiryPolicy(javax.cache.expiry.ExpiryPolicy) Ignite(org.apache.ignite.Ignite) PlatformExpiryPolicy(org.apache.ignite.internal.processors.platform.cache.expiry.PlatformExpiryPolicy) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration)

Aggregations

ExpiryPolicy (javax.cache.expiry.ExpiryPolicy)54 Duration (javax.cache.expiry.Duration)23 TouchedExpiryPolicy (javax.cache.expiry.TouchedExpiryPolicy)15 IgniteCacheExpiryPolicy (org.apache.ignite.internal.processors.cache.IgniteCacheExpiryPolicy)13 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)12 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)12 GridCacheEntryRemovedException (org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException)11 KeyCacheObject (org.apache.ignite.internal.processors.cache.KeyCacheObject)11 CacheObject (org.apache.ignite.internal.processors.cache.CacheObject)10 CacheOperationContext (org.apache.ignite.internal.processors.cache.CacheOperationContext)9 GridCacheVersion (org.apache.ignite.internal.processors.cache.version.GridCacheVersion)9 GridAbsPredicate (org.apache.ignite.internal.util.lang.GridAbsPredicate)9 CacheOperationProvider (com.hazelcast.cache.impl.CacheOperationProvider)7 UUID (java.util.UUID)7 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)7 Transaction (org.apache.ignite.transactions.Transaction)7 Map (java.util.Map)5 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)5 GridCacheEntryEx (org.apache.ignite.internal.processors.cache.GridCacheEntryEx)5 IgniteTxTimeoutCheckedException (org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException)5