blob: 574f80d843ca1b0519dbfe7548907b5401e95631 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
2 * Copyright 2014 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Yuta HIGUCHI41f2ec02014-10-27 09:54:43 -070016package org.onlab.onos.store.hz;
Yuta HIGUCHI951e7902014-09-23 14:45:11 -070017
18import static com.google.common.base.Preconditions.checkNotNull;
19
Yuta HIGUCHI971addc2014-10-07 23:23:17 -070020import org.onlab.onos.store.serializers.StoreSerializer;
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070021
Yuta HIGUCHI951e7902014-09-23 14:45:11 -070022import com.google.common.base.Optional;
23import com.google.common.cache.CacheLoader;
24import com.hazelcast.core.IMap;
25
26/**
27 * CacheLoader to wrap Map value with Optional,
28 * to handle negative hit on underlying IMap.
29 *
30 * @param <K> IMap key type after deserialization
31 * @param <V> IMap value type after deserialization
32 */
33public final class OptionalCacheLoader<K, V> extends
34 CacheLoader<K, Optional<V>> {
35
Yuta HIGUCHI971addc2014-10-07 23:23:17 -070036 private final StoreSerializer serializer;
Yuta HIGUCHI951e7902014-09-23 14:45:11 -070037 private IMap<byte[], byte[]> rawMap;
38
39 /**
40 * Constructor.
41 *
Yuta HIGUCHI672488d2014-10-07 09:23:43 -070042 * @param serializer to use for serialization
Yuta HIGUCHI951e7902014-09-23 14:45:11 -070043 * @param rawMap underlying IMap
44 */
Yuta HIGUCHI971addc2014-10-07 23:23:17 -070045 public OptionalCacheLoader(StoreSerializer serializer, IMap<byte[], byte[]> rawMap) {
Yuta HIGUCHI672488d2014-10-07 09:23:43 -070046 this.serializer = checkNotNull(serializer);
Yuta HIGUCHI951e7902014-09-23 14:45:11 -070047 this.rawMap = checkNotNull(rawMap);
48 }
49
50 @Override
51 public Optional<V> load(K key) throws Exception {
Yuta HIGUCHI672488d2014-10-07 09:23:43 -070052 byte[] keyBytes = serializer.encode(key);
Yuta HIGUCHI951e7902014-09-23 14:45:11 -070053 byte[] valBytes = rawMap.get(keyBytes);
54 if (valBytes == null) {
55 return Optional.absent();
56 }
Yuta HIGUCHI672488d2014-10-07 09:23:43 -070057 V dev = serializer.decode(valBytes);
Yuta HIGUCHI951e7902014-09-23 14:45:11 -070058 return Optional.of(dev);
59 }
60}