| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package me.lethunderhawk.profile.config;
- import me.lethunderhawk.profile.config.abstraction.ConfigFactory;
- import me.lethunderhawk.profile.config.abstraction.PersistentConfig;
- import org.bukkit.configuration.file.YamlConfiguration;
- import org.bukkit.plugin.java.JavaPlugin;
- import java.io.File;
- import java.io.IOException;
- import java.util.function.Supplier;
- public class ConfigLoader {
- private final File folder;
- private final JavaPlugin main;
- public ConfigLoader(JavaPlugin plugin) {
- this.main = plugin;
- this.folder = main.getDataFolder();
- if (!folder.exists()) {
- folder.mkdirs();
- }
- }
- public <T extends PersistentConfig> T loadConfig(
- Class<T> type,
- String fileName,
- ConfigFactory<T> factory,
- Supplier<T> defaultSupplier
- ) {
- File file = getFile(fileName);
- // If file does not exist → create default config
- if (!file.exists()) {
- try {
- file.getParentFile().mkdirs();
- file.createNewFile();
- } catch (IOException e) {
- throw new RuntimeException("Could not create config file: " + fileName, e);
- }
- T defaultConfig = defaultSupplier.get();
- save(defaultConfig);
- main.getLogger().info("[ProfileConfig] Created new profile " + fileName + ".yml");
- return defaultConfig;
- }
- YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file);
- // If file exists but is empty → also create default
- if (cfg.getKeys(false).isEmpty()) {
- T defaultConfig = defaultSupplier.get();
- save(defaultConfig);
- main.getLogger().info("[ProfileConfig] Initialized empty profile " + fileName + ".yml");
- return defaultConfig;
- }
- return factory.deserialize(cfg);
- }
- public void save(PersistentConfig persistentConfig) {
- File file = getFile(persistentConfig.getFileName());
- YamlConfiguration cfg = new YamlConfiguration();
- persistentConfig.serialize(cfg);
- try {
- cfg.save(file);
- } catch (IOException e) {
- throw new RuntimeException("Could not save config file: " + file.getName(), e);
- }
- }
- private File getFile(String name) {
- return new File(folder, name + ".yml");
- }
- }
|