back up maps in the database as a collection of key value pairs

this allows all objects to be used as keys and not only strings
This commit is contained in:
Bernhard 2019-03-29 15:58:35 +01:00
parent 1883320445
commit a80ee81ba4
2 changed files with 39 additions and 12 deletions

View File

@ -0,0 +1,36 @@
package org.telegram.abilitybots.api.db;
import org.telegram.abilitybots.api.util.Pair;
import java.util.*;
public class BackupMap<K, V> extends AbstractCollection<Pair<K, V>> implements Collection<Pair<K, V>> {
private Collection<Pair<K, V>> entries = new HashSet<>();
public BackupMap(){}
public BackupMap(Map<K, V> map) {
map.forEach((key, value) -> entries.add(Pair.of(key, value)));
}
public Map<K, V> toMap() {
Map<K, V> map = new HashMap<>();
entries.forEach(e -> map.put(e.a(), e.b()));
return map;
}
@Override
public Iterator<Pair<K, V>> iterator() {
return entries.iterator();
}
@Override
public int size() {
return entries.size();
}
@Override
public boolean add(Pair<K, V> kvPair) {
return entries.add(kvPair);
}
}

View File

@ -184,7 +184,7 @@ public class MapDBContext implements DBContext {
else if (struct instanceof List)
return Pair.of(entry.getKey(), newArrayList((List) struct));
else if (struct instanceof Map)
return Pair.of(entry.getKey(), newHashMap((Map) struct));
return Pair.of(entry.getKey(), new BackupMap((Map) struct));
else
return Pair.of(entry.getKey(), struct);
}).collect(toMap(pair -> (String) pair.a(), Pair::b));
@ -197,17 +197,8 @@ public class MapDBContext implements DBContext {
if (value instanceof Set) {
Set entrySet = (Set) value;
getSet(name).addAll(entrySet);
} else if (value instanceof Map) {
Map<Object, Object> entryMap = (Map) value;
// TODO: This is ugly
// Special handling of USERS since the key is an integer. JSON by default considers a map a JSONObject.
// Keys are serialized and deserialized as String
if (name.equals(USERS))
entryMap = entryMap.entrySet().stream()
.map(entry -> Pair.of(Integer.parseInt(entry.getKey().toString()), entry.getValue()))
.collect(toMap(Pair::a, Pair::b));
} else if (value instanceof BackupMap) {
Map<Object, Object> entryMap = ((BackupMap)value).toMap();
getMap(name).putAll(entryMap);
} else if (value instanceof List) {
List entryList = (List) value;