public class ConfigStorage {
public final Logger logger = Logger.getLogger(ConfigStorage.class.getName());
public final File CONFIG_DIR = new File(Minecraft.getInstance().gameDir, "verist/configs");
public final File AUTOCFG_FILE = new File(CONFIG_DIR, "autocfg.cfg");
public void init() throws IOException {
setupFolder();
addShutdownHook();
}
public void setupFolder() {
if (!CONFIG_DIR.exists()) {
CONFIG_DIR.mkdirs();
} else if (AUTOCFG_FILE.exists()) {
loadConfiguration("autocfg");
logger.log(Level.SEVERE, "Load system configuration...");
} else {
logger.log(Level.SEVERE, "Creating system configuration...");
try {
AUTOCFG_FILE.createNewFile();
logger.log(Level.SEVERE, "Created!");
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to create system configuration file", e);
}
}
}
public void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
saveConfiguration("autocfg");
logger.log(Level.INFO, "Configuration saved as autocfg on exit.");
} catch (Exception e) {
logger.log(Level.SEVERE, "Failed to save configuration on exit", e);
}
}));
}
public boolean isEmpty() {
return getConfigs().isEmpty();
}
public List<Config> getConfigs() {
List<Config> configs = new ArrayList<>();
File[] configFiles = CONFIG_DIR.listFiles();
if (configFiles != null) {
for (File configFile : configFiles) {
if (configFile.isFile() && configFile.getName().endsWith(".cfg")) {
String configName = configFile.getName().replace(".cfg", "");
Config config = findConfig(configName);
if (config != null) {
configs.add(config);
}
}
}
}
return configs;
}
public void loadConfiguration(String configuration) {
Config config = findConfig(configuration);
try {
FileReader reader = new FileReader(config.getFile());
JsonObject object = new JsonParser().parse(reader).getAsJsonObject();
config.loadConfig(object);
reader.close();
} catch (FileNotFoundException e) {
logger.log(Level.WARNING, "Not Found Exception", e);
} catch (IOException | NullPointerException e) {
logger.log(Level.WARNING, "Fatal error in Config!", e);
}
}
public void saveConfiguration(String configuration) {
Config config = findConfig(configuration);
if (config == null) {
config = new Config(configuration);
}
String contentPrettyPrint = new GsonBuilder().setPrettyPrinting().create().toJson(config.saveConfig());
try {
FileWriter writer = new FileWriter(config.getFile());
writer.write(contentPrettyPrint);
writer.close();
} catch (IOException e) {
logger.log(Level.WARNING, "File not found!", e);
} catch (NullPointerException e) {
logger.log(Level.WARNING, "Fatal Error in Config!", e);
}
}
public Config findConfig(String configName) {
if (configName == null) return null;
File configFile = new File(CONFIG_DIR, configName + ".cfg");
if (configFile.exists()) {
return new Config(configName);
}
return null;
}
}