Implement persistent data

This commit is contained in:
Gabriel Tofvesson 2021-05-02 21:55:28 +02:00
parent 80c77797bd
commit c47b5c4376
2 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,62 @@
package dev.w1zzrd.invtweaks;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DataStore {
private static final Logger logger = Bukkit.getLogger();
private final File storeFile;
private final FileConfiguration config;
public DataStore(final String storeName, final Plugin plugin) {
storeFile = new File(plugin.getDataFolder(), storeName + ".yml");
config = YamlConfiguration.loadConfiguration(storeFile);
// Save config in case it doesn't exist
saveData();
}
public <T extends ConfigurationSerializable> T loadData(final String path, final DefaultGetter<T> defaultValue) {
final T value = (T) config.get(path);
return value == null ? defaultValue.get() : value;
}
public <T extends ConfigurationSerializable> void storeData(final String path, final T value) {
config.set(path, value);
}
public void saveData() {
try {
config.save(storeFile);
} catch (IOException e) {
logger.log(Level.SEVERE, Logger.GLOBAL_LOGGER_NAME + " Could not save data due to an I/O error", e);
}
}
public void loadData() {
try {
config.load(storeFile);
} catch (IOException | InvalidConfigurationException e) {
logger.log(Level.SEVERE, Logger.GLOBAL_LOGGER_NAME + " Could not load data due to an I/O error", e);
}
}
/**
* Functional interface for constructing default values
* @param <T> Type to construct
*/
public interface DefaultGetter<T> {
T get();
}
}

View File

@ -0,0 +1,30 @@
package dev.w1zzrd.invtweaks.serialization;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import java.util.*;
import java.util.stream.Collectors;
public class UUIDList implements ConfigurationSerializable {
public final List<UUID> uuids;
public UUIDList(final List<UUID> backingList) {
uuids = backingList;
}
public UUIDList() {
this(new ArrayList<>());
}
public UUIDList(final Map<String, Object> values) {
this();
if (values.containsKey("values"))
uuids.addAll(((Collection<String>)values.get("values")).stream().map(UUID::fromString).collect(Collectors.toSet()));
}
@Override
public Map<String, Object> serialize() {
return Collections.singletonMap("values", uuids.stream().map(UUID::toString).collect(Collectors.toList()));
}
}