110 lines
2.8 KiB
Java
110 lines
2.8 KiB
Java
package eu.oskar3123.spigot2fa.config.yaml;
|
|
|
|
import com.google.common.base.Charsets;
|
|
import org.bukkit.Bukkit;
|
|
import org.bukkit.configuration.file.FileConfiguration;
|
|
import org.bukkit.configuration.file.YamlConfiguration;
|
|
import org.bukkit.plugin.java.JavaPlugin;
|
|
|
|
import java.io.File;
|
|
import java.io.IOException;
|
|
import java.io.InputStream;
|
|
import java.io.InputStreamReader;
|
|
import java.util.logging.Level;
|
|
|
|
public class ConfigHandler
|
|
{
|
|
|
|
private JavaPlugin plugin;
|
|
|
|
public ConfigHandler(JavaPlugin instance)
|
|
{
|
|
plugin = instance;
|
|
}
|
|
|
|
public Config addConfig(Config config)
|
|
{
|
|
saveDefaultConfig(config);
|
|
return config;
|
|
}
|
|
|
|
public FileConfiguration getConfig(Config config)
|
|
{
|
|
if (config.fileConfig == null)
|
|
{
|
|
reloadConfig(config);
|
|
}
|
|
return config.fileConfig;
|
|
}
|
|
|
|
public void reloadConfig(Config config)
|
|
{
|
|
if (config.fileConfig == null)
|
|
{
|
|
config.file = new File(plugin.getDataFolder(), config.name + ".yml");
|
|
}
|
|
config.fileConfig = YamlConfiguration.loadConfiguration(config.file);
|
|
config.fileConfig.options().copyDefaults(true);
|
|
|
|
InputStream defConfigStream = plugin.getResource(config.name + ".yml");
|
|
if (defConfigStream != null)
|
|
{
|
|
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream, Charsets.UTF_8));
|
|
config.fileConfig.setDefaults(defConfig);
|
|
saveConfig(config);
|
|
}
|
|
}
|
|
|
|
public void saveConfig(Config config)
|
|
{
|
|
saveConfig(config, false);
|
|
}
|
|
|
|
public void saveConfig(Config config, boolean async)
|
|
{
|
|
if (config.fileConfig == null || config.file == null)
|
|
{
|
|
return;
|
|
}
|
|
if (async)
|
|
{
|
|
Bukkit.getScheduler().runTaskAsynchronously(plugin, () ->
|
|
{
|
|
try
|
|
{
|
|
getConfig(config).save(config.file);
|
|
}
|
|
catch (IOException e)
|
|
{
|
|
plugin.getLogger().log(Level.SEVERE, "Could not save config to " + config.file, e);
|
|
}
|
|
});
|
|
}
|
|
else
|
|
{
|
|
try
|
|
{
|
|
getConfig(config).save(config.file);
|
|
}
|
|
catch (IOException e)
|
|
{
|
|
plugin.getLogger().log(Level.SEVERE, "Could not save config to " + config.file, e);
|
|
}
|
|
}
|
|
}
|
|
|
|
public void saveDefaultConfig(Config config)
|
|
{
|
|
if (config.file == null)
|
|
{
|
|
config.file = new File(plugin.getDataFolder(), config.name + ".yml");
|
|
}
|
|
if (!config.file.exists())
|
|
{
|
|
plugin.saveResource(config.name + ".yml", false);
|
|
}
|
|
reloadConfig(config);
|
|
}
|
|
|
|
}
|