Browse Source

Minor improvement

feature/user-settings
Andrii Shvaika 4 years ago
parent
commit
a62a28a77f
  1. 58
      dao/src/main/java/org/thingsboard/server/dao/user/UserSettingsServiceImpl.java

58
dao/src/main/java/org/thingsboard/server/dao/user/UserSettingsServiceImpl.java

@ -132,51 +132,25 @@ public class UserSettingsServiceImpl extends AbstractCachedService<UserId, UserS
} }
public JsonNode update(JsonNode mainNode, JsonNode updateNode) { public JsonNode update(JsonNode mainNode, JsonNode updateNode) {
DocumentContext dcOldSettings = JsonPath.parse(mainNode.toString());
Iterator<String> fieldNames = updateNode.fieldNames(); Iterator<String> fieldNames = updateNode.fieldNames();
while (fieldNames.hasNext()) { while (fieldNames.hasNext()) {
String fieldName = fieldNames.next(); String fieldExpression = fieldNames.next();
createPathIfNotExists(dcOldSettings, "$."+ fieldName); String[] fieldPath = fieldExpression.trim().split("\\.");
dcOldSettings = dcOldSettings.set("$." + fieldName, getValueByNodeType(updateNode.get(fieldName))); var node = (ObjectNode) mainNode;
} for (int i = 0; i < fieldPath.length; i++) {
try { var fieldName = fieldPath[i];
return new ObjectMapper().readValue(dcOldSettings.jsonString(), ObjectNode.class); var last = i == (fieldPath.length - 1);
} catch (JsonProcessingException e) { if (last) {
throw new RuntimeException(e); node.set(fieldName, updateNode.get(fieldExpression));
} } else {
} if (!node.has(fieldName)) {
node.set(fieldName, JacksonUtil.newObjectNode());
private static String createPathIfNotExists(DocumentContext dcOldSettings, String path) { }
try { node = (ObjectNode) node.get(fieldName);
dcOldSettings.read(path); }
return path; }
} catch (PathNotFoundException e) {
String lastElement = path.substring(path.lastIndexOf(".") + 1);
String pathToLastElement = path.substring(0, path.lastIndexOf("."));
dcOldSettings.put(createPathIfNotExists(dcOldSettings, pathToLastElement), lastElement, new LinkedHashMap<String, Object>());
return path;
}
}
private static Object getValueByNodeType(final JsonNode value)
{
final NodeType type = NodeType.getNodeType(value);
switch (type) {
case STRING:
return value.textValue();
case NUMBER:
case INTEGER:
return value.bigIntegerValue();
case NULL:
case ARRAY:
return value;
case OBJECT:
return new ObjectMapper().convertValue(value, new TypeReference<Map<String, Object>>() {});
case BOOLEAN:
return value.booleanValue();
default:
throw new UnsupportedOperationException();
} }
return mainNode;
} }
} }

Loading…
Cancel
Save