Yuta HIGUCHI | 951e790 | 2014-09-23 14:45:11 -0700 | [diff] [blame] | 1 | package org.onlab.onos.store.impl; |
| 2 | |
| 3 | import static com.google.common.base.Preconditions.checkNotNull; |
| 4 | |
tom | 0755a36 | 2014-09-24 11:54:43 -0700 | [diff] [blame] | 5 | import org.onlab.onos.store.common.StoreService; |
Yuta HIGUCHI | 951e790 | 2014-09-23 14:45:11 -0700 | [diff] [blame] | 6 | |
| 7 | import com.google.common.base.Optional; |
| 8 | import com.google.common.cache.CacheLoader; |
| 9 | import com.hazelcast.core.IMap; |
| 10 | |
| 11 | /** |
| 12 | * CacheLoader to wrap Map value with Optional, |
| 13 | * to handle negative hit on underlying IMap. |
| 14 | * |
| 15 | * @param <K> IMap key type after deserialization |
| 16 | * @param <V> IMap value type after deserialization |
| 17 | */ |
| 18 | public final class OptionalCacheLoader<K, V> extends |
| 19 | CacheLoader<K, Optional<V>> { |
| 20 | |
| 21 | private final StoreService storeService; |
| 22 | private IMap<byte[], byte[]> rawMap; |
| 23 | |
| 24 | /** |
| 25 | * Constructor. |
| 26 | * |
| 27 | * @param storeService to use for serialization |
| 28 | * @param rawMap underlying IMap |
| 29 | */ |
| 30 | public OptionalCacheLoader(StoreService storeService, IMap<byte[], byte[]> rawMap) { |
| 31 | this.storeService = checkNotNull(storeService); |
| 32 | this.rawMap = checkNotNull(rawMap); |
| 33 | } |
| 34 | |
| 35 | @Override |
| 36 | public Optional<V> load(K key) throws Exception { |
| 37 | byte[] keyBytes = storeService.serialize(key); |
| 38 | byte[] valBytes = rawMap.get(keyBytes); |
| 39 | if (valBytes == null) { |
| 40 | return Optional.absent(); |
| 41 | } |
| 42 | V dev = storeService.deserialize(valBytes); |
| 43 | return Optional.of(dev); |
| 44 | } |
| 45 | } |