use of me.shadorc.shadbot.data.annotation.DataSave in project Shadbot by Shadorc.
the class StatsManager method save.
@DataSave(filePath = FILE_NAME, initialDelay = 10, period = 10, unit = TimeUnit.MINUTES)
public static void save() throws JSONException, IOException {
JSONObject mainObj = new JSONObject();
Reflections reflections = new Reflections(StatsManager.class.getPackage().getName(), new MethodAnnotationsScanner());
for (Method jsonMethod : reflections.getMethodsAnnotatedWith(StatsJSON.class)) {
StatsJSON annotation = jsonMethod.getAnnotation(StatsJSON.class);
try {
mainObj.put(annotation.name(), jsonMethod.invoke(null));
} catch (Exception err) {
LogUtils.error(err, String.format("An error occurred while saving statistics %s.", jsonMethod.getDeclaringClass().getSimpleName()));
}
}
try (FileWriter writer = new FileWriter(FILE)) {
writer.write(mainObj.toString(Config.JSON_INDENT_FACTOR));
}
}
use of me.shadorc.shadbot.data.annotation.DataSave in project Shadbot by Shadorc.
the class DataManager method init.
public static boolean init() {
LogUtils.infof("Initializing data files...");
if (!SAVE_DIR.exists() && !SAVE_DIR.mkdir()) {
LogUtils.error("The save folder could not be created.");
return false;
}
Reflections reflections = new Reflections(DataManager.class.getPackage().getName(), new MethodAnnotationsScanner());
for (Method initMethod : reflections.getMethodsAnnotatedWith(DataInit.class)) {
try {
initMethod.invoke(null);
} catch (Exception err) {
LogUtils.error(err, String.format("An error occurred while initializing data %s.", initMethod.getDeclaringClass().getSimpleName()));
return false;
}
// Search for save() method and if found, schedule it
for (Method method : initMethod.getDeclaringClass().getMethods()) {
if (method.isAnnotationPresent(DataSave.class)) {
DataSave annotation = method.getAnnotation(DataSave.class);
Runnable saveTask = () -> {
try {
LogUtils.infof("Saving %s...", initMethod.getDeclaringClass().getSimpleName());
method.invoke(null);
LogUtils.infof("%s saved.", initMethod.getDeclaringClass().getSimpleName());
} catch (Exception err) {
LogUtils.error(err, String.format("An error occurred while saving %s.", annotation.filePath()));
}
};
SAVE_TASKS.add(saveTask);
SCHEDULED_EXECUTOR.scheduleAtFixedRate(saveTask, annotation.initialDelay(), annotation.period(), annotation.unit());
}
}
LogUtils.infof("%s initialized.", initMethod.getDeclaringClass().getSimpleName());
}
LogUtils.infof("Data files initialized.");
return true;
}
Aggregations