001package com.identityworksllc.iiq.common.cache;
002
003import java.io.Serializable;
004
005/**
006 * A variant on {@link CacheMap} intended for use in plugin-heavy environments, when
007 * you may want to clear a cache upon plugin installation or update. An entry will
008 * be considered expired when {@link CacheEntry#isExpired()} returns true or else
009 * when the plugin version has changed.
010 *
011 * All other behavior is identical.
012 *
013 * @param <K> The key type
014 * @param <V> The value type
015 */
016public class VersionedCacheMap<K, V> extends CacheMap<K, V> implements Serializable {
017    /**
018     * Caches the value using a {@link VersionedCacheEntry}
019     *
020     * @param value The value to cache
021     * @return The cache entry
022     */
023    @Override
024    protected CacheEntry<V> cache(V value) {
025        return new VersionedCacheEntry<>(value, getNewExpirationDate());
026    }
027
028    /**
029     * @see CacheMap#putAllInternal(CacheMap)
030     */
031    @Override
032    public void putAllInternal(CacheMap<? extends K, ? extends V> other) {
033        for (K key : other.keySet()) {
034            CacheEntry<? extends V> value = other.getInternalMap().get(key);
035            if (!value.isExpired()) {
036                VersionedCacheEntry<? extends V> newValue = VersionedCacheEntry.of(value);
037                getInternalMap().put(key, newValue);
038            }
039        }
040    }
041}