-
Notifications
You must be signed in to change notification settings - Fork 1
/
JsonConfiguration.java
556 lines (502 loc) · 13.8 KB
/
JsonConfiguration.java
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
package com.github.sanctum.labyrinth.data;
import com.github.sanctum.labyrinth.LabyrinthProvider;
import com.github.sanctum.labyrinth.api.Service;
import com.github.sanctum.labyrinth.library.EasyTypeAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
/**
* @author Hempfest
* @version 1.0
*/
public class JsonConfiguration extends Configurable {
protected final Plugin plugin;
private final File file;
private final File parent;
private final String name;
private final String directory;
protected JSONObject json;
private final JSONParser parser;
protected JsonConfiguration(Plugin plugin, String fileType, String name, String directory) {
this.parser = new JSONParser();
this.name = name;
this.plugin = plugin;
this.directory = directory;
final File pluginDataDir = plugin.getDataFolder();
if (!pluginDataDir.exists()) {
//noinspection ResultOfMethodCallIgnored
pluginDataDir.mkdir();
}
final File parent = (directory == null || directory.isEmpty()) ? pluginDataDir : new File(pluginDataDir, directory);
if (!parent.exists()) {
//noinspection ResultOfMethodCallIgnored
parent.mkdir();
}
this.parent = parent;
if (fileType == null) fileType = "data";
this.file = new File(parent, name.concat("." + fileType));
try {
if (file.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
json = (JSONObject) parser.parse(reader);
reader.close();
fileInputStream.close();
} else {
json = new JSONObject();
}
} catch (Exception ex) {
json = new JSONObject();
}
}
@Override
public void reload() {
try {
if (!file.exists()) {
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.print("{");
writer.print("}");
writer.flush();
writer.close();
}
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
json = (JSONObject) parser.parse(reader);
reader.close();
fileInputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public boolean save() {
try {
Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
Gson g = JsonAdapter.getJsonBuilder().setPrettyPrinting().disableHtmlEscaping().enableComplexMapKeySerialization().serializeNulls().serializeSpecialFloatingPointValues().create();
g.toJson(json, Map.class, writer);
writer.flush();
writer.close();
return true;
} catch (Exception ex) {
LabyrinthProvider.getService(Service.MESSENGER).getEmptyMailer().error("- An object of unknown origin was attempted to be saved and failed.").deploy();
ex.printStackTrace();
return false;
}
}
@Override
public boolean delete() {
return file.delete();
}
@Override
public boolean create() throws IOException {
if (parent.exists()) {
if (!file.exists()) {
reload();
return true;
} else {
return false;
}
}
return parent.mkdirs() && file.createNewFile();
}
@Override
public boolean exists() {
return parent.exists() && file.exists();
}
@Override
public String getName() {
return this.name;
}
@Override
public String getDirectory() {
return this.directory;
}
@Override
public File getParent() {
return file;
}
@Override
@SuppressWarnings("unchecked")
public void set(String key, Object o) {
String[] a = key.split("\\.");
String k = a[Math.max(0, a.length - 1)];
JSONObject ob = json;
for (int i = 0; i < a.length - 1; i++) {
String pathKey = a[i];
Object os = ob.get(pathKey);
if (os instanceof JSONObject) {
ob = (JSONObject) os;
} else {
JSONObject n = new JSONObject();
ob.put(pathKey, n);
ob = (JSONObject) ob.get(pathKey);
}
}
if (o == null) {
ob.remove(k);
return;
}
if (o instanceof Map) {
ob.put(k, new JSONObject((Map<?, ?>) o));
return;
}
if (o instanceof Collection) {
JSONArray ar = new JSONArray();
ar.addAll((List<?>) o);
ob.put(k, ar);
return;
}
ob.put(k, o);
}
@SuppressWarnings("unchecked")
Object checkObject(Type type, boolean array, Object object) {
Object target = object;
try {
Class<?> cl = Class.forName(type.getTypeName());
//if (type == ItemStack.class) type = JsonItemStack.class;
if (target instanceof JSONObject) {
JSONObject j = (JSONObject) object;
Gson g = JsonAdapter.getJsonBuilder().create();
Map.Entry<String, JsonAdapterInput<?>> d = serializers.entrySet().stream().filter(de -> de.getKey().equals(cl.getTypeName()) || cl.isAssignableFrom(de.getValue().getClassType())).findFirst().orElse(null);
if (d != null) {
if (j.containsKey(d.getKey())) {
Object ob = j.get(d.getKey());
Object o;
if (ob instanceof String) {
Map<String, Object> map = g.fromJson((String) ob, new EasyTypeAdapter<Map<String, Object>>());
o = d.getValue().read(map);
} else {
o = d.getValue().read((Map<String, Object>) ob);
}
if (o != null) {
target = o;
}
}
}
return target;
}
if (target instanceof JSONArray && array) {
JSONArray j = (JSONArray) object;
Map.Entry<String, JsonAdapterInput<?>> d = serializers.entrySet().stream().filter(de -> cl.isAssignableFrom(de.getValue().getClassType())).findFirst().orElse(null);
if (d != null) {
Object[] copy = (Object[]) Array.newInstance(cl, j.size());
for (int i = 0; i < j.size(); i++) {
Map<String, Object> map = (Map<String, Object>) j.get(i);
copy[i] = d.getValue().read(map.containsKey(d.getKey()) ? (Map<String, Object>) map.get(d.getKey()) : map);
}
target = copy;
}
}
} catch (ClassNotFoundException exception) {
LabyrinthProvider.getService(Service.MESSENGER).getEmptyMailer().error("- An issue occurred while attempting to deserialize object " + type.getTypeName()).deploy();
exception.printStackTrace();
}
return target;
}
@Override
protected Object get(String key) {
String[] a = key.split("\\.");
String k = a[Math.max(0, a.length - 1)];
JSONObject o = json;
for (int i = 0; i < a.length - 1; i++) {
String pathKey = a[i];
Object obj = o.get(pathKey);
if (obj instanceof JSONObject) {
JSONObject js = (JSONObject) obj;
if (js.containsKey(k)) {
return js.get(k);
} else {
o = js;
}
} else {
return obj;
}
}
return o.get(k);
}
@Override
protected <T> T get(String key, Class<T> type) {
boolean stop = false;
Object ob = null;
String[] a = key.split("\\.");
String k = a[Math.max(0, a.length - 1)];
JSONObject o = json;
for (int i = 0; i < a.length - 1; i++) {
String pathKey = a[i];
Object obj = o.get(pathKey);
if (obj instanceof JSONObject) {
JSONObject js = (JSONObject) obj;
if (js.containsKey(k)) {
ob = checkObject(type, false, js.get(k));
stop = true;
} else {
o = js;
}
} else {
ob = checkObject(type.isArray() ? type.getComponentType() : type, obj instanceof JSONArray, obj);
stop = true;
}
}
if (!stop) {
Object object = o.get(k);
ob = checkObject(type.isArray() ? type.getComponentType() : type, (object instanceof JSONArray), object);
}
if (ob == null) return null;
if (!type.isArray() && !type.isAssignableFrom(ob.getClass())) return null;
return type.cast(ob);
}
@Override
public Node getNode(String key) {
return (Node) memory.entrySet().stream().filter(n -> n.getKey().equals(key)).map(Map.Entry::getValue).findFirst().orElseGet(() -> {
ConfigurableNode n = new ConfigurableNode(key, this);
memory.put(n.getPath(), n);
return n;
});
}
@SuppressWarnings("unchecked")
@Override
public Set<String> getKeys(boolean deep) {
Set<String> keys;
if (deep) {
return MapDecompressionUtils.getInstance().decompress((Set<Map.Entry<String, Object>>)json.entrySet(), '.', null).toSet();
} else {
keys = new HashSet<>((Set<String>) json.keySet());
}
return keys;
}
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> getValues(boolean deep) {
Map<String, Object> map = new HashMap<>();
if (deep) {
return MapDecompressionUtils.getInstance().decompress((Set<Map.Entry<String, Object>>)json.entrySet(), '.', null).toMap();
} else {
json.entrySet().forEach(e -> {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>)e;
map.put(entry.getKey(), entry.getValue());
});
}
return map;
}
@Override
public Location getLocation(String key) {
return get(key, Location.class);
}
@Override
public ItemStack getItemStack(String key) {
return get(key, ItemStack.class);
}
@Override
public String getString(String key) {
Object o = get(key);
return String.valueOf(o);
}
@Override
public boolean getBoolean(String key) {
return Boolean.parseBoolean(getString(key));
}
@Override
public boolean isLocation(String key) {
return getLocation(key) != null;
}
@Override
public boolean isList(String key) {
return get(key) instanceof List;
}
@Override
public boolean isStringList(String key) {
return !getStringList(key).isEmpty();
}
@Override
public boolean isFloatList(String key) {
return !getFloatList(key).isEmpty();
}
@Override
public boolean isDoubleList(String key) {
return !getDoubleList(key).isEmpty();
}
@Override
public boolean isLongList(String key) {
return !getLongList(key).isEmpty();
}
@Override
public boolean isIntegerList(String key) {
return !getIntegerList(key).isEmpty();
}
@Override
public boolean isItemStack(String key) {
return getItemStack(key) != null;
}
@Override
public boolean isBoolean(String key) {
return get(key) instanceof Boolean;
}
@Override
public boolean isDouble(String key) {
return get(key) instanceof Double;
}
@Override
public boolean isInt(String key) {
return get(key) instanceof Integer;
}
@Override
public boolean isLong(String key) {
return get(key) instanceof Long;
}
@Override
public boolean isFloat(String key) {
return get(key) instanceof Float;
}
@Override
public boolean isString(String key) {
return get(key) instanceof String;
}
@Override
public String getPath() {
String s = "/" + getName() + "/";
if (getDirectory() != null) {
s = s + getDirectory();
}
return s;
}
@Override
public boolean isNode(String key) {
String[] a = key.split("\\.");
String k = a[Math.max(0, a.length - 1)];
JSONObject o = json;
for (int i = 0; i < a.length - 1; i++) {
String pathKey = a[i];
Object obj = o.get(pathKey);
if (obj instanceof JSONObject) {
JSONObject js = (JSONObject) obj;
if (js.containsKey(k)) {
return js.get(k) instanceof JSONObject;
} else {
o = js;
}
}
}
return o.get(k) instanceof JSONObject;
}
@Override
public double getDouble(String key) {
try {
return Double.parseDouble(getString(key));
} catch (Exception ignored) {
}
return 0.0;
}
@Override
public long getLong(String key) {
try {
return Long.parseLong(getString(key));
} catch (Exception ignored) {
}
return 0L;
}
@Override
public float getFloat(String key) {
try {
return Float.parseFloat(getString(key));
} catch (Exception ignored) {
}
return 0.0f;
}
@Override
public int getInt(String key) {
try {
return Integer.parseInt(getString(key));
} catch (Exception ignored) {
}
return 0;
}
@Override
public Map<?, ?> getMap(String key) {
Object o = get(key);
if (o instanceof Map) {
return (Map<?, ?>) o;
}
return new HashMap<>();
}
@Override
public List<?> getList(String key) {
Object o = get(key);
if (o instanceof List) {
return (List<?>) o;
}
return new ArrayList<>();
}
@SuppressWarnings("unchecked")
@Override
public List<String> getStringList(String key) {
List<?> l = getList(key);
if (l.isEmpty()) return new ArrayList<>();
if (!(l.get(0) instanceof String)) return new ArrayList<>();
return (List<String>) l;
}
@SuppressWarnings("unchecked")
@Override
public List<Integer> getIntegerList(String key) {
List<?> l = getList(key);
if (l.isEmpty()) return new ArrayList<>();
if (!(l.get(0) instanceof Integer) || !(l.get(0) instanceof Long)) return new ArrayList<>();
return (List<Integer>) l;
}
@SuppressWarnings("unchecked")
@Override
public List<Double> getDoubleList(String key) {
List<?> l = getList(key);
if (l.isEmpty()) return new ArrayList<>();
if (!(l.get(0) instanceof Double) || !(l.get(0) instanceof Float)) return new ArrayList<>();
return (List<Double>) l;
}
@SuppressWarnings("unchecked")
@Override
public List<Float> getFloatList(String key) {
List<?> l = getList(key);
if (l.isEmpty()) return new ArrayList<>();
if (!(l.get(0) instanceof Float) || !(l.get(0) instanceof Double)) return new ArrayList<>();
return (List<Float>) l;
}
@SuppressWarnings("unchecked")
@Override
public List<Long> getLongList(String key) {
List<?> l = getList(key);
if (l.isEmpty()) return new ArrayList<>();
if (!(l.get(0) instanceof Long) || !(l.get(0) instanceof Integer)) return new ArrayList<>();
return (List<Long>) l;
}
@Override
public FileExtension getType() {
return FileType.JSON;
}
@Override
public String toString() {
return json.toString();
}
}