|
| 1 | +package configuration; |
| 2 | + |
| 3 | +import org.w3c.dom.Document; |
| 4 | +import org.w3c.dom.Element; |
| 5 | +import org.w3c.dom.NodeList; |
| 6 | + |
| 7 | +import javax.xml.parsers.DocumentBuilderFactory; |
| 8 | +import java.io.File; |
| 9 | +import java.util.HashMap; |
| 10 | +import java.util.Map; |
| 11 | + |
| 12 | +/** |
| 13 | + * HashCodeRegistry — loads admin-defined hashcodes from nwe-config.xml. |
| 14 | + * |
| 15 | + * Config format: |
| 16 | + * <hashcodes> |
| 17 | + * <entry class="NitroWebExpress">1234567890</entry> |
| 18 | + * <entry class="MessageQueueSorter">9876543210</entry> |
| 19 | + * </hashcodes> |
| 20 | + * |
| 21 | + * Call HashCodeRegistry.resolve(object) instead of object.hashCode() |
| 22 | + * to get the admin-overridden value (or default if not configured). |
| 23 | + */ |
| 24 | +public final class HashCodeRegistry |
| 25 | +{ |
| 26 | + private static final String CONFIG_FILE = "configuration/nwe-config.xml"; |
| 27 | + private static Map<String, Integer> OVERRIDES; |
| 28 | + |
| 29 | + private HashCodeRegistry() {} |
| 30 | + |
| 31 | + public static int resolve(Object owner) |
| 32 | + { |
| 33 | + if (OVERRIDES == null) load(); |
| 34 | + String name = owner.getClass().getSimpleName(); |
| 35 | + Integer override = OVERRIDES.get(name); |
| 36 | + return override != null ? override : owner.hashCode(); |
| 37 | + } |
| 38 | + |
| 39 | + private static synchronized void load() |
| 40 | + { |
| 41 | + OVERRIDES = new HashMap<>(); |
| 42 | + try |
| 43 | + { |
| 44 | + File file = new File(CONFIG_FILE); |
| 45 | + if (!file.exists()) return; |
| 46 | + |
| 47 | + Document doc = DocumentBuilderFactory.newInstance() |
| 48 | + .newDocumentBuilder().parse(file); |
| 49 | + doc.getDocumentElement().normalize(); |
| 50 | + |
| 51 | + NodeList hcNodes = doc.getElementsByTagName("hashcodes"); |
| 52 | + if (hcNodes.getLength() == 0) return; |
| 53 | + |
| 54 | + Element hcEl = (Element) hcNodes.item(0); |
| 55 | + NodeList entries = hcEl.getElementsByTagName("entry"); |
| 56 | + for (int i = 0; i < entries.getLength(); i++) |
| 57 | + { |
| 58 | + Element entry = (Element) entries.item(i); |
| 59 | + String className = entry.getAttribute("class"); |
| 60 | + String value = entry.getTextContent().trim(); |
| 61 | + if (!className.isEmpty() && !value.isEmpty()) |
| 62 | + { |
| 63 | + try { OVERRIDES.put(className, Integer.parseUnsignedInt(value)); } |
| 64 | + catch (NumberFormatException ignored) {} |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + catch (Exception ignored) {} |
| 69 | + } |
| 70 | + |
| 71 | + /** Force reload (e.g. after config change). */ |
| 72 | + public static void reload() { OVERRIDES = null; } |
| 73 | +} |
0 commit comments