Search in sources :

Example 1 with ModifiedExpiryPolicy

use of javax.cache.expiry.ModifiedExpiryPolicy in project cache2k by cache2k.

the class JCacheBuilder method setupExpiryPolicy.

/**
 * Register a expiry policy to cache2k.
 *
 * <p>JSR107 requires that null values are deleted from the cache. We register an expiry policy
 * to cache2k to provide this behavior.
 */
private void setupExpiryPolicy() {
    if (cache2kConfiguration.getExpiryPolicy() != null) {
        org.cache2k.expiry.ExpiryPolicy<K, V> ep0;
        try {
            ep0 = cache2kConfiguration.getExpiryPolicy().supply(manager.getCache2kManager());
        } catch (Exception ex) {
            throw new CacheException("couldn't initialize expiry policy", ex);
        }
        final org.cache2k.expiry.ExpiryPolicy<K, V> ep = ep0;
        cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

            @Override
            public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                if (value == null) {
                    return NO_CACHE;
                }
                return ep.calculateExpiryTime(key, value, loadTime, oldEntry);
            }
        }));
        return;
    }
    if (config.getExpiryPolicyFactory() != null) {
        expiryPolicy = config.getExpiryPolicyFactory().create();
    }
    if (expiryPolicy == null || expiryPolicy instanceof EternalExpiryPolicy) {
        cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

            @Override
            public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                if (value == null) {
                    return NO_CACHE;
                }
                return ETERNAL;
            }
        }));
        return;
    }
    if (expiryPolicy instanceof ModifiedExpiryPolicy) {
        Duration d = expiryPolicy.getExpiryForCreation();
        final long _millisDuration = d.getTimeUnit().toMillis(d.getDurationAmount());
        if (_millisDuration == 0) {
            cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

                @Override
                public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                    return NO_CACHE;
                }
            }));
            return;
        }
        cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

            @Override
            public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                if (value == null) {
                    return NO_CACHE;
                }
                return loadTime + _millisDuration;
            }
        }));
        return;
    }
    if (expiryPolicy instanceof CreatedExpiryPolicy) {
        cache2kConfiguration.setEternal(true);
        Duration d = expiryPolicy.getExpiryForCreation();
        final long _millisDuration = d.getTimeUnit().toMillis(d.getDurationAmount());
        if (_millisDuration == 0) {
            cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

                @Override
                public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                    return NO_CACHE;
                }
            }));
            return;
        }
        cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

            @Override
            public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                if (value == null) {
                    return NO_CACHE;
                }
                if (oldEntry == null) {
                    return loadTime + _millisDuration;
                } else {
                    return NEUTRAL;
                }
            }
        }));
        return;
    }
    needsTouchyWrapper = true;
    cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new TouchyJCacheAdapter.ExpiryPolicyAdapter<K, V>(expiryPolicy)));
}
Also used : CacheException(javax.cache.CacheException) EternalExpiryPolicy(javax.cache.expiry.EternalExpiryPolicy) Duration(javax.cache.expiry.Duration) CreatedExpiryPolicy(javax.cache.expiry.CreatedExpiryPolicy) CacheEntry(org.cache2k.CacheEntry) CacheLoaderException(javax.cache.integration.CacheLoaderException) CacheException(javax.cache.CacheException) IOException(java.io.IOException) ModifiedExpiryPolicy(javax.cache.expiry.ModifiedExpiryPolicy) CreatedExpiryPolicy(javax.cache.expiry.CreatedExpiryPolicy) ExpiryPolicy(javax.cache.expiry.ExpiryPolicy) EternalExpiryPolicy(javax.cache.expiry.EternalExpiryPolicy) ModifiedExpiryPolicy(javax.cache.expiry.ModifiedExpiryPolicy)

Example 2 with ModifiedExpiryPolicy

use of javax.cache.expiry.ModifiedExpiryPolicy in project gora by apache.

the class JCacheStore method initialize.

@Override
public void initialize(Class<K> keyClass, Class<T> persistentClass, Properties properties) throws GoraException {
    super.initialize(keyClass, persistentClass, properties);
    String cachingProviderKey = properties.getProperty(GORA_DEFAULT_JCACHE_PROVIDER_KEY);
    if (cachingProviderKey != null) {
        cachingProvider = Caching.getCachingProvider(cachingProviderKey);
    } else {
        cachingProvider = Caching.getCachingProvider();
    }
    try {
        this.persistentDataStore = DataStoreFactory.getDataStore(keyClass, persistentClass, new Configuration());
    } catch (GoraException ex) {
        LOG.error("Couldn't initialize persistent DataStore.", ex);
        throw ex;
    }
    manager = cachingProvider.getCacheManager();
    if (((properties.getProperty(JCACHE_AUTO_CREATE_CACHE_PROPERTY_KEY) != null) && Boolean.valueOf(properties.getProperty(JCACHE_AUTO_CREATE_CACHE_PROPERTY_KEY))) || ((manager.getCache(super.getPersistentClass().getSimpleName(), keyClass, persistentClass) == null))) {
        cacheEntryList = new ConcurrentSkipListSet<>();
        MutableConfiguration mutableCacheConfig = new MutableConfiguration<>();
        mutableCacheConfig.setTypes(keyClass, persistentClass);
        if (properties.getProperty(JCACHE_READ_THROUGH_PROPERTY_KEY) != null) {
            mutableCacheConfig.setReadThrough(Boolean.valueOf(properties.getProperty(JCACHE_READ_THROUGH_PROPERTY_KEY)));
        } else {
            mutableCacheConfig.setReadThrough(true);
        }
        if (properties.getProperty(JCACHE_WRITE_THROUGH_PROPERTY_KEY) != null) {
            mutableCacheConfig.setWriteThrough(Boolean.valueOf(properties.getProperty(JCACHE_WRITE_THROUGH_PROPERTY_KEY)));
        } else {
            mutableCacheConfig.setWriteThrough(true);
        }
        if (properties.getProperty(JCACHE_STORE_BY_VALUE_PROPERTY_KEY) != null) {
            mutableCacheConfig.setStoreByValue(Boolean.valueOf(properties.getProperty(JCACHE_STORE_BY_VALUE_PROPERTY_KEY)));
        }
        if (properties.getProperty(JCACHE_STATISTICS_PROPERTY_KEY) != null) {
            mutableCacheConfig.setStatisticsEnabled(Boolean.valueOf(properties.getProperty(JCACHE_STATISTICS_PROPERTY_KEY)));
        }
        if (properties.getProperty(JCACHE_MANAGEMENT_PROPERTY_KEY) != null) {
            mutableCacheConfig.setStatisticsEnabled(Boolean.valueOf(properties.getProperty(JCACHE_MANAGEMENT_PROPERTY_KEY)));
        }
        if (properties.getProperty(JCACHE_EXPIRE_POLICY_PROPERTY_KEY) != null) {
            String expiryPolicyIdentifier = properties.getProperty(JCACHE_EXPIRE_POLICY_PROPERTY_KEY);
            if (expiryPolicyIdentifier.equals(JCACHE_ACCESSED_EXPIRY_IDENTIFIER)) {
                mutableCacheConfig.setExpiryPolicyFactory(FactoryBuilder.factoryOf(new AccessedExpiryPolicy(new Duration(TimeUnit.SECONDS, Integer.valueOf(properties.getProperty(JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY))))));
            } else if (expiryPolicyIdentifier.equals(JCACHE_CREATED_EXPIRY_IDENTIFIER)) {
                mutableCacheConfig.setExpiryPolicyFactory(FactoryBuilder.factoryOf(new CreatedExpiryPolicy(new Duration(TimeUnit.SECONDS, Integer.valueOf(properties.getProperty(JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY))))));
            } else if (expiryPolicyIdentifier.equals(JCACHE_MODIFIED_EXPIRY_IDENTIFIER)) {
                mutableCacheConfig.setExpiryPolicyFactory(FactoryBuilder.factoryOf(new ModifiedExpiryPolicy(new Duration(TimeUnit.SECONDS, Integer.valueOf(properties.getProperty(JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY))))));
            } else if (expiryPolicyIdentifier.equals(JCACHE_TOUCHED_EXPIRY_IDENTIFIER)) {
                mutableCacheConfig.setExpiryPolicyFactory(FactoryBuilder.factoryOf(new TouchedExpiryPolicy(new Duration(TimeUnit.SECONDS, Integer.valueOf(properties.getProperty(JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY))))));
            }
        }
        mutableCacheConfig.setCacheLoaderFactory(JCacheCacheFactoryBuilder.factoryOfCacheLoader(this.persistentDataStore, keyClass, persistentClass));
        mutableCacheConfig.setCacheWriterFactory(JCacheCacheFactoryBuilder.factoryOfCacheWriter(this.persistentDataStore, keyClass, persistentClass));
        cache = manager.createCache(persistentClass.getSimpleName(), mutableCacheConfig);
        cacheConfig = mutableCacheConfig;
    } else {
        cache = manager.getCache(super.getPersistentClass().getSimpleName(), keyClass, persistentClass);
        this.populateLocalCacheEntrySet(cache);
    }
    cache.registerCacheEntryListener(new MutableCacheEntryListenerConfiguration<>(JCacheCacheFactoryBuilder.factoryOfEntryListener(new JCacheCacheEntryListener<K, T>(cacheEntryList)), null, true, true));
    LOG.info("JCache Gora datastore initialized successfully.");
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) MutableConfiguration(javax.cache.configuration.MutableConfiguration) MutableCacheEntryListenerConfiguration(javax.cache.configuration.MutableCacheEntryListenerConfiguration) CompleteConfiguration(javax.cache.configuration.CompleteConfiguration) Duration(javax.cache.expiry.Duration) AccessedExpiryPolicy(javax.cache.expiry.AccessedExpiryPolicy) CreatedExpiryPolicy(javax.cache.expiry.CreatedExpiryPolicy) MutableConfiguration(javax.cache.configuration.MutableConfiguration) GoraException(org.apache.gora.util.GoraException) TouchedExpiryPolicy(javax.cache.expiry.TouchedExpiryPolicy) ModifiedExpiryPolicy(javax.cache.expiry.ModifiedExpiryPolicy)

Example 3 with ModifiedExpiryPolicy

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

the class IgniteCacheEntryListenerAbstractTest method testSynchronousEvents.

/**
 * @throws Exception If failed.
 */
@Test
public void testSynchronousEvents() throws Exception {
    final CacheEntryCreatedListener<Object, Object> lsnr = new CreateUpdateRemoveExpireListener() {

        @Override
        public void onRemoved(Iterable<CacheEntryEvent<?, ?>> evts) {
            super.onRemoved(evts);
            awaitLatch();
        }

        @Override
        public void onCreated(Iterable<CacheEntryEvent<?, ?>> evts) {
            super.onCreated(evts);
            awaitLatch();
        }

        @Override
        public void onUpdated(Iterable<CacheEntryEvent<?, ?>> evts) {
            super.onUpdated(evts);
            awaitLatch();
        }

        private void awaitLatch() {
            try {
                assertTrue(syncEvtLatch.await(5000, MILLISECONDS));
            } catch (InterruptedException e) {
                fail("Unexpected exception: " + e);
            }
        }
    };
    CacheEntryListenerConfiguration<Object, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>(new Factory<CacheEntryListener<Object, Object>>() {

        @Override
        public CacheEntryListener<Object, Object> create() {
            return lsnr;
        }
    }, null, true, true);
    IgniteCache<Object, Object> cache = jcache();
    cache.registerCacheEntryListener(lsnrCfg);
    try {
        for (Integer key : keys()) {
            log.info("Check synchronous create event [key=" + key + ']');
            syncEvent(key, 1, cache, 1);
            checkEvent(evts.iterator(), key, CREATED, 1, null);
            log.info("Check synchronous update event [key=" + key + ']');
            syncEvent(key, 2, cache, 1);
            checkEvent(evts.iterator(), key, UPDATED, 2, 1);
            log.info("Check synchronous remove event [key=" + key + ']');
            syncEvent(key, null, cache, 1);
            checkEvent(evts.iterator(), key, REMOVED, 2, 2);
            log.info("Check synchronous expire event [key=" + key + ']');
            syncEvent(key, 3, cache.withExpiryPolicy(new ModifiedExpiryPolicy(new Duration(MILLISECONDS, 1000))), eagerTtl() ? 2 : 1);
            checkEvent(evts.iterator(), key, CREATED, 3, null);
            if (!eagerTtl()) {
                U.sleep(1100);
                assertNull(primaryCache(key(key), cache.getName()).get(key(key)));
                evtsLatch.await(5000, MILLISECONDS);
                assertEquals(1, evts.size());
            }
            checkEvent(evts.iterator(), key, EXPIRED, 3, 3);
            assertEquals(0, evts.size());
        }
    } finally {
        cache.deregisterCacheEntryListener(lsnrCfg);
    }
}
Also used : MutableCacheEntryListenerConfiguration(javax.cache.configuration.MutableCacheEntryListenerConfiguration) CacheEntryListener(javax.cache.event.CacheEntryListener) Duration(javax.cache.expiry.Duration) ModifiedExpiryPolicy(javax.cache.expiry.ModifiedExpiryPolicy) Test(org.junit.Test)

Example 4 with ModifiedExpiryPolicy

use of javax.cache.expiry.ModifiedExpiryPolicy 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 5 with ModifiedExpiryPolicy

use of javax.cache.expiry.ModifiedExpiryPolicy in project caffeine by ben-manes.

the class JCacheUpdateExpiryTest method getConfiguration.

@Override
protected CaffeineConfiguration<Integer, Integer> getConfiguration() {
    CaffeineConfiguration<Integer, Integer> configuration = new CaffeineConfiguration<>();
    configuration.setExpiryPolicyFactory(() -> new ModifiedExpiryPolicy(new Duration(TimeUnit.MILLISECONDS, EXPIRY_DURATION)));
    configuration.setTickerFactory(() -> ticker::read);
    return configuration;
}
Also used : Duration(javax.cache.expiry.Duration) ModifiedExpiryPolicy(javax.cache.expiry.ModifiedExpiryPolicy) CaffeineConfiguration(com.github.benmanes.caffeine.jcache.configuration.CaffeineConfiguration)

Aggregations

Duration (javax.cache.expiry.Duration)11 ModifiedExpiryPolicy (javax.cache.expiry.ModifiedExpiryPolicy)11 MutableCacheEntryListenerConfiguration (javax.cache.configuration.MutableCacheEntryListenerConfiguration)3 CreatedExpiryPolicy (javax.cache.expiry.CreatedExpiryPolicy)3 ExpiryPolicy (javax.cache.expiry.ExpiryPolicy)3 Test (org.junit.Test)3 AccessedExpiryPolicy (javax.cache.expiry.AccessedExpiryPolicy)2 Ignite (org.apache.ignite.Ignite)2 GridAbsPredicate (org.apache.ignite.internal.util.lang.GridAbsPredicate)2 CaffeineConfiguration (com.github.benmanes.caffeine.jcache.configuration.CaffeineConfiguration)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Set (java.util.Set)1 TreeSet (java.util.TreeSet)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1