1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
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> 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<String, LuckyActionHolder> eventsMap = (Map<String, LuckyActionHolder>) field.get(r);
if (eventsMap != null) {
eventsMap.clear();
for (Map.Entry<String, JsonElement> entry : sectionJson.entrySet()) {
String k = entry.getKey().replace("-", "_");
LuckyActionHolder holder = gson.fromJson(entry.getValue(), LuckyActionHolder.class);
eventsMap.put(k, holder);
}
}
}
}
}
}
|