Skip to content

Instantly share code, notes, and snippets.

@jamezrin
Created November 27, 2016 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamezrin/9d6278dff013776c7b2ddb1f68abc769 to your computer and use it in GitHub Desktop.
Save jamezrin/9d6278dff013776c7b2ddb1f68abc769 to your computer and use it in GitHub Desktop.
//Setting up gson
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
builder.enableComplexMapKeySerialization();
//fix for map key that is null
//gson does UUID.fromString even if the object is null, and it does not accept nulls
builder.registerTypeAdapter(UUID.class, (JsonDeserializer<UUID>) (element, type, context) -> {
if (element.isJsonNull() || element.getAsString().equals("null")) {
return null;
}
return UUID.fromString(element.getAsString());
});
gson = builder.create();
//Loading database
File file = new File(getDataFolder(), "data.json");
if (file.exists()) {
getLogger().info("Database exists, reading data...");
try (JsonReader reader = new JsonReader(new FileReader(file))) {
database = gson.fromJson(reader, JsonDataPool.class);
} catch (IOException e) {
e.printStackTrace();
}
} else {
getLogger().fine("Database does not exist, it will be created on server shutdown");
database = new JsonDataPool();
}
//Database save task
getLogger().info(String.format("The database will be saved every %s minutes", SAVE_INTERVAL));
new BukkitRunnable() {
@Override
public void run() {
getLogger().info("Periodically saving database...");
saveDatabase();
}
}.runTaskTimerAsynchronously(this, SAVE_INTERVAL * 60 * 20, SAVE_INTERVAL * 60 * 20);
@Override
public void onDisable() {
getServer().getScheduler().cancelTasks(this);
if (database != null) {
getLogger().info("Saving database...");
saveDatabase();
} else {
getLogger().info("Database is null, not saving database...");
}
}
private void saveDatabase() {
try (Writer writer = new FileWriter(new File(getDataFolder(), "data.json"))) {
String output = gson.toJson(database, JsonDataPool.class);
writer.write(output);
} catch (IOException e) {
getLogger().severe("Something went terribly wrong, couldn't save the database");
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment