diff --git a/tools/src/main/java/org/thingsboard/client/tools/i18n/TranslationPruner.java b/tools/src/main/java/org/thingsboard/client/tools/i18n/TranslationPruner.java new file mode 100644 index 0000000000..0e4516cd63 --- /dev/null +++ b/tools/src/main/java/org/thingsboard/client/tools/i18n/TranslationPruner.java @@ -0,0 +1,84 @@ +package org.thingsboard.client.tools.i18n; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import java.io.File; +import java.io.IOException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + + +public class TranslationPruner { + + /** + * Recursively collect all JSON keys in dot notation from the given node. + */ + private static void collectKeys(JsonNode node, String prefix, Set keys) { + if (!node.isObject()) return; + Iterator> fields = node.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + String key = entry.getKey(); + String fullKey = prefix.isEmpty() ? key : prefix + "." + key; + keys.add(fullKey); + collectKeys(entry.getValue(), fullKey, keys); + } + } + + /** + * Prune the translation ObjectNode, keeping only fields whose dot-keys are in the valid set. + */ + private static ObjectNode pruneNode(ObjectNode node, Set keys, String prefix, ObjectMapper mapper) { + ObjectNode pruned = mapper.createObjectNode(); + Iterator> fields = node.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + String key = entry.getKey(); + JsonNode value = entry.getValue(); + String fullKey = prefix.isEmpty() ? key : prefix + "." + key; + if (keys.contains(fullKey)) { + if (value.isObject()) { + ObjectNode child = pruneNode((ObjectNode) value, keys, fullKey, mapper); + pruned.set(key, child); + } else { + pruned.set(key, value); + } + } + } + return pruned; + } + + public static void main(String[] args) { + if (args.length < 3) { + System.err.println("Usage: java TranslationPruner [output.json]"); + System.exit(1); + } + try { + File sourceFile = new File(args[0]); + File referenceFile = new File(args[1]); + File outputFile = new File(args[2]); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode usRoot = mapper.readTree(referenceFile); + Set validKeys = new HashSet<>(); + collectKeys(usRoot, "", validKeys); + + JsonNode sourceRoot = mapper.readTree(sourceFile); + if (!sourceRoot.isObject()) { + throw new IllegalArgumentException("Source JSON must be an object at root"); + } + ObjectNode pruned = pruneNode((ObjectNode) sourceRoot, validKeys, "", mapper); + + mapper.writerWithDefaultPrettyPrinter().writeValue(outputFile, pruned); + System.out.println("Pruned translation written to " + outputFile.getPath()); + } catch (IOException e) { + e.printStackTrace(); + System.exit(2); + } + } + +}