ConfigLoader.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package me.lethunderhawk.profile.config;
  2. import me.lethunderhawk.profile.config.abstraction.ConfigFactory;
  3. import me.lethunderhawk.profile.config.abstraction.PersistentConfig;
  4. import org.bukkit.configuration.file.YamlConfiguration;
  5. import org.bukkit.plugin.java.JavaPlugin;
  6. import java.io.File;
  7. import java.io.IOException;
  8. import java.util.function.Supplier;
  9. public class ConfigLoader {
  10. private final File folder;
  11. private final JavaPlugin main;
  12. public ConfigLoader(JavaPlugin plugin) {
  13. this.main = plugin;
  14. this.folder = main.getDataFolder();
  15. if (!folder.exists()) {
  16. folder.mkdirs();
  17. }
  18. }
  19. public <T extends PersistentConfig> T loadConfig(
  20. Class<T> type,
  21. String fileName,
  22. ConfigFactory<T> factory,
  23. Supplier<T> defaultSupplier
  24. ) {
  25. File file = getFile(fileName);
  26. // If file does not exist → create default config
  27. if (!file.exists()) {
  28. try {
  29. file.getParentFile().mkdirs();
  30. file.createNewFile();
  31. } catch (IOException e) {
  32. throw new RuntimeException("Could not create config file: " + fileName, e);
  33. }
  34. T defaultConfig = defaultSupplier.get();
  35. save(defaultConfig);
  36. main.getLogger().info("[ProfileConfig] Created new profile " + fileName + ".yml");
  37. return defaultConfig;
  38. }
  39. YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file);
  40. // If file exists but is empty → also create default
  41. if (cfg.getKeys(false).isEmpty()) {
  42. T defaultConfig = defaultSupplier.get();
  43. save(defaultConfig);
  44. main.getLogger().info("[ProfileConfig] Initialized empty profile " + fileName + ".yml");
  45. return defaultConfig;
  46. }
  47. return factory.deserialize(cfg);
  48. }
  49. public void save(PersistentConfig persistentConfig) {
  50. File file = getFile(persistentConfig.getFileName());
  51. YamlConfiguration cfg = new YamlConfiguration();
  52. persistentConfig.serialize(cfg);
  53. try {
  54. cfg.save(file);
  55. } catch (IOException e) {
  56. throw new RuntimeException("Could not save config file: " + file.getName(), e);
  57. }
  58. }
  59. private File getFile(String name) {
  60. return new File(folder, name + ".yml");
  61. }
  62. }