From 80219f38cbc0848ef052b4e7c4e331304ee80fe2 Mon Sep 17 00:00:00 2001 From: tastybento Date: Sat, 7 Sep 2024 11:06:51 -0700 Subject: [PATCH] Add protection around meta data being written that is immutable --- .../bentobox/database/objects/Players.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/main/java/world/bentobox/bentobox/database/objects/Players.java b/src/main/java/world/bentobox/bentobox/database/objects/Players.java index ca384ed12..883072d7c 100644 --- a/src/main/java/world/bentobox/bentobox/database/objects/Players.java +++ b/src/main/java/world/bentobox/bentobox/database/objects/Players.java @@ -253,10 +253,32 @@ public class Players implements DataObject, MetaDataAble { public Optional> getMetaData() { if (metaData == null) { metaData = new HashMap<>(); + } else if (isImmutable(metaData)) { + metaData = new HashMap<>(metaData); // Convert immutable map to mutable } return Optional.of(metaData); } + private boolean isImmutable(Map map) { + try { + String testKey = "testKey"; + MetaDataValue testValue = new MetaDataValue("test"); + + // If the map already contains keys, use one of them + if (!map.isEmpty()) { + String existingKey = map.keySet().iterator().next(); + map.put(existingKey, map.get(existingKey)); // Attempt to replace value + } else { + // Use a unique key-value pair + map.put(testKey, testValue); + map.remove(testKey); + } + return false; // No exception means the map is mutable + } catch (UnsupportedOperationException e) { + return true; // Exception means the map is immutable + } + } + /** * @param metaData the metaData to set * @since 1.15.4 @@ -264,6 +286,9 @@ public class Players implements DataObject, MetaDataAble { */ @Override public void setMetaData(Map metaData) { + if (isImmutable(metaData)) { + throw new IllegalArgumentException("Provided map is immutable and cannot be set."); + } this.metaData = metaData; }