Refactor ServerUtilsConfig#set to delete existing objects at path
This commit is contained in:
parent
90b248f321
commit
d2928b4a04
5 changed files with 67 additions and 21 deletions
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue