71 lines
2.5 KiB
Java
71 lines
2.5 KiB
Java
package tech.techyjessy.Configuration;
|
|
|
|
import java.io.File;
|
|
import java.io.FileNotFoundException;
|
|
import java.io.FileWriter;
|
|
import java.io.IOException;
|
|
|
|
import org.apache.commons.io.FileUtils;
|
|
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.GsonBuilder;
|
|
import com.google.gson.JsonIOException;
|
|
import com.google.gson.JsonSyntaxException;
|
|
|
|
public class ConfigMgr {
|
|
private static ConfigMgr static_inst;
|
|
private File config;
|
|
|
|
public static ConfigMgr getInstance() {
|
|
if (static_inst == null) {
|
|
static_inst = new ConfigMgr();
|
|
}
|
|
|
|
return static_inst;
|
|
}
|
|
|
|
public void SetConfDir(File file) {
|
|
config = new File(file, "keeblarcraft.json");
|
|
if (!config.exists()) {
|
|
config.getParentFile().mkdirs();
|
|
}
|
|
}
|
|
|
|
public <T> T GetJsonObjectFromFile(Class<T> classToConvertTo) {
|
|
Gson gson = new Gson();
|
|
String ret = "";
|
|
|
|
// hot fix: Not sure how to return "false" for invalid conversion when I'm forced to convert or just catch... Look into a better
|
|
// return value in the future - but for now throw JsonSyntaxException no matter what exception is caught
|
|
try {
|
|
ret = FileUtils.readFileToString(config, "UTF-8");
|
|
} catch (Exception e) {
|
|
System.out.println("Getting json object from file had errors. This is unsupported in this version of Keeblarcraft");
|
|
e.printStackTrace();
|
|
}
|
|
|
|
return gson.fromJson(ret, classToConvertTo);
|
|
}
|
|
|
|
// WriteToJsonFile
|
|
//
|
|
// Will write to or append to a json file. It will search if the key exists first & update the field;
|
|
// or add a new entry. It should be noted that json objects *can* be buried inside each other. It is
|
|
// considered best (and only) practice to call the "GetJsonStringFromFile" function first from this
|
|
// class and simply iterate to what you would need and then update the entire entry alongside the
|
|
// top-level key.
|
|
//
|
|
// NOTE: THIS DOES NOT SAFE UPDATE THE KEY OBJECT. PRE-EXISTING DATA WILL BE DELETED FOREVER
|
|
public void WriteToJsonFile(Object data) {
|
|
Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
|
try {
|
|
FileWriter writer = new FileWriter(config);
|
|
gson.toJson(data, writer);
|
|
writer.flush();
|
|
writer.close();
|
|
} catch (JsonIOException | IOException e) {
|
|
System.out.println("Writing to json had errors. This is unhandled in this version of Keeblarcraft");
|
|
}
|
|
}
|
|
}
|