package luckyblock.configurations; import com.google.gson.*; import luckyblock.Main; import luckyblock.action.LuckyActionHolder; import java.io.*; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.util.Map; public class Configuration { private final File file; private final Object impl; private final Gson gson = new GsonBuilder().setPrettyPrinting().create(); public Configuration(File file, Object impl) { this.file = file; this.impl = impl; this.loadFromResources(this.impl); if (!file.exists()) { this.loadDefault(); } } public Configuration(String path, Object impl) { this(new File(path), impl); } private void loadFromResources(Object r) { try (InputStream input = Main.class.getResourceAsStream("/settings.json")) { if (input == null) return; JsonObject root = JsonParser.parseReader(new InputStreamReader(input, StandardCharsets.UTF_8)).getAsJsonObject(); this.model(r, root); } catch (Exception e) { throw new RuntimeException(e); } } protected void loadDefault() { try { file.getParentFile().mkdirs(); JsonObject root = new JsonObject(); String section = (String) this.impl.getClass().getField("section").get(this.impl); root.add(section, gson.toJsonTree(this.impl).getAsJsonObject().get("events")); try (FileWriter writer = new FileWriter(file)) { gson.toJson(root, writer); } } catch (Exception e) { throw new RuntimeException(e); } } public T load() { try { if (!file.exists() || file.length() == 0) { this.loadDefault(); } JsonObject root = JsonParser.parseReader(new FileReader(file)).getAsJsonObject(); this.model(this.impl, root); return (T) this.impl; } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") private void model(Object r, JsonObject root) throws Exception { String section = (String) r.getClass().getField("section").get(r); if (!root.has(section)) return; JsonObject sectionJson = root.getAsJsonObject(section); for (Field field : r.getClass().getDeclaredFields()) { if (field.getName().equals("section")) continue; field.setAccessible(true); if (Map.class.isAssignableFrom(field.getType())) { Map eventsMap = (Map) field.get(r); if (eventsMap != null) { eventsMap.clear(); for (Map.Entry entry : sectionJson.entrySet()) { String k = entry.getKey().replace("-", "_"); LuckyActionHolder holder = gson.fromJson(entry.getValue(), LuckyActionHolder.class); eventsMap.put(k, holder); } } } } } }