-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
SimpleMetadataStore.java
101 lines (86 loc) · 2.95 KB
/
SimpleMetadataStore.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package net.citizensnpcs.api.npc;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import net.citizensnpcs.api.util.DataKey;
public class SimpleMetadataStore implements MetadataStore {
private final Map<String, MetadataObject> metadata = Maps.newHashMap();
private void checkPrimitive(Object data) {
Preconditions.checkNotNull(data, "data cannot be null");
boolean isPrimitive = data instanceof String || data instanceof Boolean || data instanceof Number;
if (!isPrimitive) {
throw new IllegalArgumentException("data is not primitive");
}
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(String key) {
Preconditions.checkNotNull(key, "key cannot be null");
MetadataObject normal = metadata.get(key);
return normal == null ? null : (T) normal.value;
}
@Override
public <T> T get(String key, T def) {
T t = get(key);
if (t == null) {
set(key, def);
return def;
}
return t;
}
@Override
public boolean has(String key) {
Preconditions.checkNotNull(key, "key cannot be null");
return metadata.containsKey(key);
}
@Override
public void loadFrom(DataKey key) {
Iterator<Entry<String, MetadataObject>> itr = metadata.entrySet().iterator();
while (itr.hasNext()) {
if (itr.next().getValue().persistent) {
itr.remove();
}
}
for (DataKey subKey : key.getSubKeys()) {
setPersistent(subKey.name(), subKey.getRaw(""));
}
}
@Override
public void remove(String key) {
metadata.remove(key);
}
@Override
public void saveTo(DataKey key) {
Preconditions.checkNotNull(key, "key cannot be null");
for (Entry<String, MetadataObject> entry : metadata.entrySet()) {
if (entry.getValue().persistent) {
key.setRaw(entry.getKey(), entry.getValue().value);
}
}
}
@Override
public void set(String key, Object data) {
Preconditions.checkNotNull(key, "key cannot be null");
if (data == null) {
remove(key);
} else {
metadata.put(key, new MetadataObject(data, false));
}
}
@Override
public void setPersistent(String key, Object data) {
Preconditions.checkNotNull(key, "key cannot be null");
checkPrimitive(data);
metadata.put(key, new MetadataObject(data, true));
}
private static class MetadataObject {
final boolean persistent;
final Object value;
public MetadataObject(Object raw, boolean persistent) {
value = raw;
this.persistent = persistent;
}
}
}