/
YAMLConfig.java
110 lines (98 loc) · 2.87 KB
/
YAMLConfig.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
package net.ME1312.SubServers.Bungee.Library.Config;
import net.ME1312.SubServers.Bungee.Library.Util;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
import java.io.*;
import java.util.LinkedHashMap;
/**
* YAML Config Class
*/
@SuppressWarnings("unused")
public class YAMLConfig {
private File file;
private Yaml yaml;
private YAMLSection config;
/**
* Creates/Loads a YAML Formatted Config
*
* @param file
* @throws IOException
* @throws YAMLException
*/
@SuppressWarnings("unchecked")
public YAMLConfig(File file) throws IOException, YAMLException {
if (Util.isNull(file)) throw new NullPointerException();
this.file = file;
this.yaml = new Yaml(getDumperOptions());
if (file.exists()) {
InputStream stream = new FileInputStream(file);
this.config = new YAMLSection((LinkedHashMap<String, ?>) yaml.loadAs(stream, LinkedHashMap.class), null, null, yaml);
stream.close();
} else {
this.config = new YAMLSection(null, null, null, yaml);
}
}
/**
* Get Config Contents
*
* @return Config Contents
*/
public YAMLSection get() {
return config;
}
/**
* Set Config Contents
*
* @param value Value
*/
public void set(YAMLSection value) {
if (Util.isNull(value)) throw new NullPointerException();
config = value;
}
/**
* Reload Config Contents
*
* @throws IOException
*/
@SuppressWarnings("unchecked")
public void reload() throws IOException {
if (file.exists()) {
InputStream stream = new FileInputStream(file);
this.config = new YAMLSection((LinkedHashMap<String, ?>) yaml.loadAs(stream, LinkedHashMap.class), null, null, yaml);
stream.close();
} else {
this.config = new YAMLSection(null, null, null, yaml);
}
}
/**
* Save Config Contents
*
* @throws IOException
*/
public void save() throws IOException {
if (!file.exists()) file.createNewFile();
FileWriter writer = new FileWriter(file);
yaml.dump(config.map, writer);
writer.close();
}
@Override
public boolean equals(Object object) {
if (object instanceof YAMLConfig) {
return get().equals(((YAMLConfig) object).get());
} else {
return super.equals(object);
}
}
@Override
public String toString() {
return yaml.dump(config.map);
}
protected static DumperOptions getDumperOptions() {
DumperOptions options = new DumperOptions();
options.setAllowUnicode(false);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setIndent(2);
return options;
}
}