-
Notifications
You must be signed in to change notification settings - Fork 429
Expand file tree
/
Copy pathConfig.java
More file actions
584 lines (495 loc) · 17.3 KB
/
Config.java
File metadata and controls
584 lines (495 loc) · 17.3 KB
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
package cn.nukkit.utils;
import cn.nukkit.Server;
import cn.nukkit.scheduler.FileWriteTask;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
/**
* author: MagicDroidX
* Nukkit
*/
public class Config {
public static final int DETECT = -1; //Detect by file extension
public static final int PROPERTIES = 0; // .properties
public static final int CNF = Config.PROPERTIES; // .cnf
public static final int JSON = 1; // .js, .json
public static final int YAML = 2; // .yml, .yaml
//public static final int EXPORT = 3; // .export, .xport
//public static final int SERIALIZED = 4; // .sl
public static final int ENUM = 5; // .txt, .list, .enum
public static final int ENUMERATION = Config.ENUM;
//private LinkedHashMap<String, Object> config = new LinkedHashMap<>();
private ConfigSection config = new ConfigSection();
private File file;
private boolean correct = false;
private int type = Config.DETECT;
public static final Map<String, Integer> format = new TreeMap<>();
static {
format.put("properties", Config.PROPERTIES);
format.put("con", Config.PROPERTIES);
format.put("conf", Config.PROPERTIES);
format.put("config", Config.PROPERTIES);
format.put("js", Config.JSON);
format.put("json", Config.JSON);
format.put("yml", Config.YAML);
format.put("yaml", Config.YAML);
//format.put("sl", Config.SERIALIZED);
//format.put("serialize", Config.SERIALIZED);
format.put("txt", Config.ENUM);
format.put("list", Config.ENUM);
format.put("enum", Config.ENUM);
}
/**
* Constructor for Config instance with undefined file object
*
* @param type - Config type
*/
public Config(int type) {
this.type = type;
this.correct = true;
this.config = new ConfigSection();
}
/**
* Constructor for Config (YAML) instance with undefined file object
*/
public Config() {
this(Config.YAML);
}
public Config(String file) {
this(file, Config.DETECT);
}
public Config(File file) {
this(file.toString(), Config.DETECT);
}
public Config(String file, int type) {
this(file, type, new ConfigSection());
}
public Config(File file, int type) {
this(file.toString(), type, new ConfigSection());
}
@Deprecated
public Config(String file, int type, LinkedHashMap<String, Object> defaultMap) {
this.load(file, type, new ConfigSection(defaultMap));
}
public Config(String file, int type, ConfigSection defaultMap) {
this.load(file, type, defaultMap);
}
public Config(File file, int type, ConfigSection defaultMap) {
this.load(file.toString(), type, defaultMap);
}
@Deprecated
public Config(File file, int type, LinkedHashMap<String, Object> defaultMap) {
this(file.toString(), type, new ConfigSection(defaultMap));
}
public void reload() {
this.config.clear();
this.correct = false;
//this.load(this.file.toString());
if (this.file == null) throw new IllegalStateException("Failed to reload Config. File object is undefined.");
this.load(this.file.toString(), this.type);
}
public boolean load(String file) {
return this.load(file, Config.DETECT);
}
public boolean load(String file, int type) {
return this.load(file, type, new ConfigSection());
}
public boolean load(String file, int type, ConfigSection defaultMap) {
this.correct = true;
this.type = type;
this.file = new File(file);
if (!this.file.exists()) {
try {
this.file.getParentFile().mkdirs();
this.file.createNewFile();
} catch (IOException e) {
MainLogger.getLogger().error("Could not create Config " + this.file.toString(), e);
}
this.config = defaultMap;
this.save();
} else {
if (this.type == Config.DETECT) {
String extension = "";
if (this.file.getName().lastIndexOf(".") != -1 && this.file.getName().lastIndexOf(".") != 0) {
extension = this.file.getName().substring(this.file.getName().lastIndexOf(".") + 1);
}
if (format.containsKey(extension)) {
this.type = format.get(extension);
} else {
this.correct = false;
}
}
if (this.correct) {
String content = "";
try {
content = Utils.readFile(this.file);
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
}
this.parseContent(content);
if (!this.correct) return false;
if (this.setDefault(defaultMap) > 0) {
this.save();
}
} else {
return false;
}
}
return true;
}
public boolean load(InputStream inputStream) {
if (inputStream == null) return false;
if (this.correct) {
String content;
try {
content = Utils.readFile(inputStream);
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
return false;
}
this.parseContent(content);
}
return correct;
}
public boolean check() {
return this.correct;
}
public boolean isCorrect() {
return correct;
}
/**
* Save configuration into provided file. Internal file object will be set to new file.
*
* @param file
* @param async
* @return
*/
public boolean save(File file, boolean async) {
this.file = file;
return save(async);
}
public boolean save(File file) {
this.file = file;
return save();
}
public boolean save() {
return this.save(false);
}
public boolean save(Boolean async) {
if (this.file == null) throw new IllegalStateException("Failed to save Config. File object is undefined.");
if (this.correct) {
StringBuilder content = new StringBuilder();
switch (this.type) {
case Config.PROPERTIES:
content = new StringBuilder(this.writeProperties());
break;
case Config.JSON:
content = new StringBuilder(new GsonBuilder().setPrettyPrinting().create().toJson(this.config));
break;
case Config.YAML:
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
content = new StringBuilder(yaml.dump(this.config));
break;
case Config.ENUM:
for (Object o : this.config.entrySet()) {
Map.Entry entry = (Map.Entry) o;
content.append(entry.getKey()).append("\r\n");
}
break;
}
if (async) {
Server.getInstance().getScheduler().scheduleAsyncTask(new FileWriteTask(this.file, content.toString()));
} else {
try {
Utils.writeFile(this.file, content.toString());
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
}
}
return true;
} else {
return false;
}
}
public void set(final String key, Object value) {
this.config.set(key, value);
}
public Object get(String key) {
return this.get(key, null);
}
public <T> T get(String key, T defaultValue) {
return this.correct ? this.config.get(key, defaultValue) : defaultValue;
}
public ConfigSection getSection(String key) {
return this.correct ? this.config.getSection(key) : new ConfigSection();
}
public boolean isSection(String key) {
return config.isSection(key);
}
public ConfigSection getSections(String key) {
return this.correct ? this.config.getSections(key) : new ConfigSection();
}
public ConfigSection getSections() {
return this.correct ? this.config.getSections() : new ConfigSection();
}
public int getInt(String key) {
return this.getInt(key, 0);
}
public int getInt(String key, int defaultValue) {
return this.correct ? this.config.getInt(key, defaultValue) : defaultValue;
}
public boolean isInt(String key) {
return config.isInt(key);
}
public long getLong(String key) {
return this.getLong(key, 0);
}
public long getLong(String key, long defaultValue) {
return this.correct ? this.config.getLong(key, defaultValue) : defaultValue;
}
public boolean isLong(String key) {
return config.isLong(key);
}
public double getDouble(String key) {
return this.getDouble(key, 0);
}
public double getDouble(String key, double defaultValue) {
return this.correct ? this.config.getDouble(key, defaultValue) : defaultValue;
}
public boolean isDouble(String key) {
return config.isDouble(key);
}
public String getString(String key) {
return this.getString(key, "");
}
public String getString(String key, String defaultValue) {
return this.correct ? this.config.getString(key, defaultValue) : defaultValue;
}
public boolean isString(String key) {
return config.isString(key);
}
public boolean getBoolean(String key) {
return this.getBoolean(key, false);
}
public boolean getBoolean(String key, boolean defaultValue) {
return this.correct ? this.config.getBoolean(key, defaultValue) : defaultValue;
}
public boolean isBoolean(String key) {
return config.isBoolean(key);
}
public List getList(String key) {
return this.getList(key, null);
}
public List getList(String key, List defaultList) {
return this.correct ? this.config.getList(key, defaultList) : defaultList;
}
public boolean isList(String key) {
return config.isList(key);
}
public Map getMap(String key) {
return this.getMap(key, null);
}
public Map getMap(String key, List defaultList) {
return this.correct ? this.config.getMap(key, defaultList) : defaultList;
}
public boolean isMap(String key) {
return config.isMap(key);
}
public List<String> getStringList(String key) {
return config.getStringList(key);
}
public List<Integer> getIntegerList(String key) {
return config.getIntegerList(key);
}
public List<Boolean> getBooleanList(String key) {
return config.getBooleanList(key);
}
public List<Double> getDoubleList(String key) {
return config.getDoubleList(key);
}
public List<Float> getFloatList(String key) {
return config.getFloatList(key);
}
public List<Long> getLongList(String key) {
return config.getLongList(key);
}
public List<Byte> getByteList(String key) {
return config.getByteList(key);
}
public List<Character> getCharacterList(String key) {
return config.getCharacterList(key);
}
public List<Short> getShortList(String key) {
return config.getShortList(key);
}
public List<Map> getMapList(String key) {
return config.getMapList(key);
}
public void setAll(LinkedHashMap<String, Object> map) {
this.config = new ConfigSection(map);
}
public void setAll(ConfigSection section) {
this.config = section;
}
public boolean exists(String key) {
return config.exists(key);
}
public boolean exists(String key, boolean ignoreCase) {
return config.exists(key, ignoreCase);
}
public void remove(String key) {
config.remove(key);
}
public Map<String, Object> getAll() {
return this.config.getAllMap();
}
/**
* Get root (main) config section of the Config
*
* @return
*/
public ConfigSection getRootSection() {
return config;
}
public int setDefault(LinkedHashMap<String, Object> map) {
return setDefault(new ConfigSection(map));
}
public int setDefault(ConfigSection map) {
int size = this.config.size();
this.config = this.fillDefaults(map, this.config);
return this.config.size() - size;
}
private ConfigSection fillDefaults(ConfigSection defaultMap, ConfigSection data) {
for (String key : defaultMap.keySet()) {
if (!data.containsKey(key)) {
data.put(key, defaultMap.get(key));
}
}
return data;
}
private void parseList(String content) {
content = content.replace("\r\n", "\n");
for (String v : content.split("\n")) {
if (v.trim().isEmpty()) {
continue;
}
config.put(v, true);
}
}
private String writeProperties() {
StringBuilder content = new StringBuilder("#Properties Config file\r\n#" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "\r\n");
for (Object o : this.config.entrySet()) {
Map.Entry entry = (Map.Entry) o;
Object v = entry.getValue();
Object k = entry.getKey();
if (v instanceof Boolean) {
v = (Boolean) v ? "on" : "off";
}
content.append(k).append("=").append(v).append("\r\n");
}
return content.toString();
}
private void parseProperties(String content) {
for (final String line : content.split("\n")) {
if (Pattern.compile("[a-zA-Z0-9\\-_.]*+=+[^\\r\\n]*").matcher(line).matches()) {
final int splitIndex = line.indexOf('=');
if (splitIndex == -1) {
continue;
}
final String key = line.substring(0, splitIndex);
final String value = line.substring(splitIndex + 1);
final String valueLower = value.toLowerCase();
if (this.config.containsKey(key)) {
MainLogger.getLogger().debug("[Config] Repeated property " + key + " on file " + this.file.toString());
}
switch (valueLower) {
case "on":
case "true":
case "yes":
this.config.put(key, true);
break;
case "off":
case "false":
case "no":
this.config.put(key, false);
break;
default:
this.config.put(key, value);
break;
}
}
}
}
/**
* @deprecated use {@link #get(String)} instead
*/
@Deprecated
public Object getNested(String key) {
return get(key);
}
/**
* @deprecated use {@link #get(String, Object)} instead
*/
@Deprecated
public <T> T getNested(String key, T defaultValue) {
return get(key, defaultValue);
}
/**
* @deprecated use {@link #get(String)} instead
*/
@Deprecated
@SuppressWarnings("unchecked")
public <T> T getNestedAs(String key, Class<T> type) {
return (T) get(key);
}
/**
* @deprecated use {@link #remove(String)} instead
*/
@Deprecated
public void removeNested(String key) {
remove(key);
}
private void parseContent(String content) {
switch (this.type) {
case Config.PROPERTIES:
this.parseProperties(content);
break;
case Config.JSON:
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
this.config = new ConfigSection(gson.fromJson(content, new TypeToken<LinkedHashMap<String, Object>>() {
}.getType()));
break;
case Config.YAML:
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
this.config = new ConfigSection(yaml.loadAs(content, LinkedHashMap.class));
break;
// case Config.SERIALIZED
case Config.ENUM:
this.parseList(content);
break;
default:
this.correct = false;
}
}
public Set<String> getKeys() {
if (this.correct) return config.getKeys();
return new HashSet<>();
}
public Set<String> getKeys(boolean child) {
if (this.correct) return config.getKeys(child);
return new HashSet<>();
}
}