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