View Javadoc
1   /*
2    * Copyright 2016 The Lannister Project
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   */
16  package net.anyflow.lannister.cluster;
17  
18  import java.util.HashMap;
19  
20  import com.google.common.collect.Maps;
21  import com.hazelcast.core.IdGenerator;
22  
23  public class HazelcastSetValueMap<K, V> implements Map<K, Set<V>> {
24  	private static final IdGenerator ID_GENERATOR = Hazelcast.INSTANCE.getIdGenerator("HazelcastSetValueMap");
25  
26  	private final com.hazelcast.core.IMap<K, String> engine;
27  	private final HashMap<String, Set<V>> values;
28  	private final String valueKeyPrefix;
29  
30  	public HazelcastSetValueMap(String name) {
31  		engine = Hazelcast.INSTANCE.getMap(name);
32  		values = Maps.newHashMap();
33  		valueKeyPrefix = Long.toString(ID_GENERATOR.newId());
34  	}
35  
36  	@Override
37  	public void put(K key, Set<V> value) {
38  		String valueKey = valueKey(key);
39  
40  		Set<V> prev = values.put(valueKey, value);
41  		if (prev != null) {
42  			prev.dispose();
43  		}
44  
45  		engine.set(key, valueKey);
46  	}
47  
48  	private String valueKey(K key) {
49  		return valueKeyPrefix + "_" + key.toString();
50  	}
51  
52  	@Override
53  	public Set<V> get(K key) {
54  		return values.get(engine.get(key));
55  	}
56  
57  	@Override
58  	public Set<V> remove(K key) {
59  		String valueKey = engine.remove(key);
60  		if (valueKey == null) { return null; }
61  
62  		return values.remove(valueKey);
63  	}
64  
65  	@Override
66  	public int size() {
67  		return engine.size();
68  	}
69  
70  	@Override
71  	public void dispose() {
72  		engine.destroy();
73  	}
74  
75  	@Override
76  	public boolean containsKey(K key) {
77  		return engine.containsKey(key);
78  	}
79  
80  	@Override
81  	public java.util.Set<K> keySet() {
82  		return engine.keySet();
83  	}
84  }