Refactor ServerUtilsConfig#set to delete existing objects at path

This commit is contained in:
Frank van der Heijden 2021-08-04 16:25:30 +02:00
parent 90b248f321
commit d2928b4a04
No known key found for this signature in database
GPG key ID: B808721C2DD5B5B8
5 changed files with 67 additions and 21 deletions

View file

@ -137,7 +137,7 @@ public class JsonConfig implements ServerUtilsConfig {
}
@Override
public void set(String path, Object value) {
public void setUnsafe(String path, Object value) {
int lastDotIndex = path.lastIndexOf('.');
String memberName = path;
@ -158,6 +158,20 @@ public class JsonConfig implements ServerUtilsConfig {
jsonObject.add(memberName, gson.toJsonTree(value));
}
@Override
public void remove(String path) {
int lastDotIndex = path.lastIndexOf('.');
JsonObject object;
if (lastDotIndex == -1) {
object = config;
} else {
object = ((JsonConfig) get(path.substring(0, lastDotIndex))).config;
}
object.remove(path.substring(lastDotIndex + 1));
}
@Override
public String getString(String path) {
JsonElement element = getJsonElement(path);

View file

@ -40,7 +40,31 @@ public interface ServerUtilsConfig {
* @param path The path.
* @param value The object to set the path's value to.
*/
void set(String path, Object value);
default void set(String path, Object value) {
if (value == null) {
remove(path);
} else {
String pathSegment = path;
int lastDotIndex;
while ((lastDotIndex = pathSegment.lastIndexOf('.')) != -1) {
String parentPath = path.substring(0, lastDotIndex);
if (!(get(parentPath) instanceof ServerUtilsConfig)) {
remove(parentPath);
}
pathSegment = parentPath;
}
setUnsafe(path, value);
}
}
void setUnsafe(String path, Object value);
/**
* Removes a path.
*/
void remove(String path);
/**
* Retrieves a string from a path.
@ -122,7 +146,7 @@ public interface ServerUtilsConfig {
String defKey = (root.isEmpty() ? "" : root + ".") + key;
Object value = conf.get(key);
if (def.get(defKey) == null) {
conf.set(key, null);
conf.remove(key);
} else if (value instanceof ServerUtilsConfig) {
removeOldKeys(def, (ServerUtilsConfig) value, defKey);
}