|
| 1 | +package com.nexoscript.servermanager.node.config; |
| 2 | + |
| 3 | +import org.json.JSONException; |
| 4 | +import org.json.JSONObject; |
| 5 | + |
| 6 | +import java.io.File; |
| 7 | +import java.io.FileWriter; |
| 8 | +import java.io.IOException; |
| 9 | +import java.nio.file.Files; |
| 10 | +import java.nio.file.Path; |
| 11 | + |
| 12 | +public class JsonConfig { |
| 13 | + private Path configFile; |
| 14 | + private JSONObject jsonObject; |
| 15 | + |
| 16 | + public JsonConfig(String configName) { |
| 17 | + this.create(".", configName); |
| 18 | + } |
| 19 | + |
| 20 | + public JsonConfig(String path, String configName) { |
| 21 | + this.create(path, configName); |
| 22 | + } |
| 23 | + |
| 24 | + private void create(String path, String configName) { |
| 25 | + this.configFile = Path.of(path, configName); |
| 26 | + File file = new File(this.configFile.toString()); |
| 27 | + try { |
| 28 | + if (!file.exists()) { |
| 29 | + if (file.createNewFile()) { |
| 30 | + this.jsonObject = new JSONObject(); |
| 31 | + this.save(); |
| 32 | + return; |
| 33 | + } |
| 34 | + throw new IOException("File can't created. " + file.getAbsolutePath()); |
| 35 | + } |
| 36 | + this.jsonObject = new JSONObject(new String(Files.readAllBytes(this.configFile))); |
| 37 | + } catch (IOException e) { |
| 38 | + throw new RuntimeException(e); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + public void addDefault(String key, Object value) { |
| 43 | + if (this.get(key) == null) { |
| 44 | + this.jsonObject.put(key, value); |
| 45 | + this.save(); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + public boolean set(String key, Object value) { |
| 50 | + try { |
| 51 | + this.jsonObject.put(key, value); |
| 52 | + this.save(); |
| 53 | + return true; |
| 54 | + } catch (JSONException e) { |
| 55 | + return false; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + public boolean remove(String key) { |
| 60 | + try { |
| 61 | + this.jsonObject.remove(key); |
| 62 | + this.save(); |
| 63 | + return true; |
| 64 | + } catch (JSONException ignored) { |
| 65 | + return false; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + public Object get(String key) { |
| 70 | + try { |
| 71 | + return this.jsonObject.get(key); |
| 72 | + } catch (JSONException e) { |
| 73 | + return null; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + public void save() { |
| 78 | + File file = new File(this.configFile.toString()); |
| 79 | + try (FileWriter fileWriter = new FileWriter(file)) { |
| 80 | + fileWriter.write(this.jsonObject.toString()); |
| 81 | + fileWriter.flush(); |
| 82 | + } catch (IOException e) { |
| 83 | + throw new RuntimeException(e); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + public Path getConfigFile() { |
| 88 | + return configFile; |
| 89 | + } |
| 90 | +} |
0 commit comments