Refactor config loading

This commit is contained in:
filoghost 2020-06-27 11:08:38 +02:00
parent 4453e5f560
commit fef2ef952d
11 changed files with 244 additions and 188 deletions

View File

@ -19,7 +19,8 @@ import me.filoghost.chestcommands.command.framework.CommandFramework;
import me.filoghost.chestcommands.config.CustomPlaceholders;
import me.filoghost.chestcommands.config.Lang;
import me.filoghost.chestcommands.config.Settings;
import me.filoghost.chestcommands.config.yaml.PluginConfig;
import me.filoghost.chestcommands.config.yaml.Config;
import me.filoghost.chestcommands.config.yaml.ConfigLoader;
import me.filoghost.chestcommands.hook.BarAPIHook;
import me.filoghost.chestcommands.hook.BungeeCordHook;
import me.filoghost.chestcommands.hook.PlaceholderAPIHook;
@ -64,6 +65,12 @@ public class ChestCommands extends JavaPlugin {
private static ChestCommands instance;
private ConfigLoader settingsConfigLoader;
private ConfigLoader placeholdersConfigLoader;
private ConfigLoader langConfigLoader;
private MenuManager menuManager;
private static Settings settings;
private static Lang lang;
@ -83,6 +90,11 @@ public class ChestCommands extends JavaPlugin {
instance = this;
Log.setLogger(getLogger());
settingsConfigLoader = new ConfigLoader(getDataPath("config.yml"));
placeholdersConfigLoader = new ConfigLoader(getDataPath("custom-placeholders.yml"));
langConfigLoader = new ConfigLoader(getDataPath("lang.yml"));
menuManager = new MenuManager();
settings = new Settings();
lang = new Lang();
@ -168,31 +180,26 @@ public class ChestCommands extends JavaPlugin {
Log.severe("Encountered errors while running run automatic configuration upgrades. Some configuration files or menus may require manual updates.", e);
}
PluginConfig settingsYaml = getSettingsConfig();
try {
settingsYaml.createDefault(this);
settingsYaml.load();
settings.load(settingsYaml);
settingsConfigLoader.createDefault(this);
settings.load(settingsConfigLoader);
} catch (Throwable t) {
logConfigLoadException(settingsYaml, t);
logConfigLoadException(settingsConfigLoader, t);
}
PluginConfig langYaml = getLangConfig();
try {
langYaml.createDefault(this);
langYaml.load();
lang.load(langYaml);
langConfigLoader.createDefault(this);
lang.load(langConfigLoader);
} catch (Throwable t) {
logConfigLoadException(langYaml, t);
logConfigLoadException(langConfigLoader, t);
}
PluginConfig placeholdersYaml = getPlaceholdersConfig();
try {
placeholdersYaml.createDefault(this);
placeholdersYaml.load();
placeholders.load(placeholdersYaml, errors);
placeholdersConfigLoader.createDefault(this);
Config placeholdersConfig = placeholdersConfigLoader.load();
placeholders.load(placeholdersConfig, errors);
} catch (Throwable t) {
logConfigLoadException(placeholdersYaml, t);
logConfigLoadException(placeholdersConfigLoader, t);
}
// Load the menus
@ -206,11 +213,11 @@ public class ChestCommands extends JavaPlugin {
Log.severe("Couldn't create \"" + menusPath.getFileName() + "\" folder");
}
PluginConfig exampleMenu = new PluginConfig(getDataPath(Paths.get("menu", "example.yml")));
ConfigLoader exampleMenuLoader = new ConfigLoader(getDataPath(Paths.get("menu", "example.yml")));
try {
exampleMenu.createDefault(this);
exampleMenuLoader.createDefault(this);
} catch (Throwable t) {
logConfigLoadException(exampleMenu, t);
logConfigLoadException(exampleMenuLoader, t);
}
}
@ -224,11 +231,13 @@ public class ChestCommands extends JavaPlugin {
}
for (Path menuFile : menuPaths) {
PluginConfig menuConfig = new PluginConfig(menuFile);
ConfigLoader menuConfigLoader = new ConfigLoader(menuFile);
Config menuConfig;
try {
menuConfig.load();
menuConfig = menuConfigLoader.load();
} catch (Throwable t) {
logConfigLoadException(menuConfig, t);
logConfigLoadException(menuConfigLoader, t);
continue;
}
@ -252,28 +261,28 @@ public class ChestCommands extends JavaPlugin {
return errors;
}
private void logConfigLoadException(PluginConfig config, Throwable t) {
private void logConfigLoadException(ConfigLoader configLoader, Throwable t) {
t.printStackTrace();
if (t instanceof IOException) {
Log.warning("Error while reading the file \"" + config.getFileName() + "\". Default values will be used.");
Log.warning("Error while reading the file \"" + configLoader.getFileName() + "\". Default values will be used.");
} else if (t instanceof InvalidConfigurationException) {
Log.warning("Invalid YAML syntax in the file \"" + config.getFileName() + "\", please look at the error above. Default values will be used.");
Log.warning("Invalid YAML syntax in the file \"" + configLoader.getFileName() + "\", please look at the error above. Default values will be used.");
} else {
Log.warning("Unhandled error while parsing the file \"" + config.getFileName() + "\". Please inform the developer.");
Log.warning("Unhandled error while parsing the file \"" + configLoader.getFileName() + "\". Please inform the developer.");
}
}
public PluginConfig getLangConfig() {
return new PluginConfig(getDataPath("lang.yml"));
public ConfigLoader getLangConfigLoader() {
return langConfigLoader;
}
public PluginConfig getSettingsConfig() {
return new PluginConfig(getDataPath("config.yml"));
public ConfigLoader getSettingsConfigLoader() {
return settingsConfigLoader;
}
public PluginConfig getPlaceholdersConfig() {
return new PluginConfig(getDataPath("custom-placeholders.yml"));
public ConfigLoader getPlaceholdersConfigLoader() {
return placeholdersConfigLoader;
}
public Path getMenusPath() {

View File

@ -14,35 +14,34 @@
*/
package me.filoghost.chestcommands.config;
import me.filoghost.chestcommands.config.yaml.Config;
import me.filoghost.chestcommands.util.ErrorCollector;
import me.filoghost.chestcommands.util.FormatUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import me.filoghost.chestcommands.config.yaml.PluginConfig;
import me.filoghost.chestcommands.util.ErrorCollector;
import me.filoghost.chestcommands.util.FormatUtils;
public class CustomPlaceholders {
private final Map<String, String> placeholders = new HashMap<>();
public void load(PluginConfig pluginConfig, ErrorCollector errorCollector) {
public void load(Config config, ErrorCollector errorCollector) {
placeholders.clear();
for (String key : pluginConfig.getKeys(false)) {
for (String key : config.getKeys(false)) {
String placeholder = key;
String replacement = FormatUtils.addColors(pluginConfig.getString(key));
String replacement = FormatUtils.addColors(config.getString(key));
if (placeholder.length() == 0) {
errorCollector.addError("Error in " + pluginConfig.getFileName() + ": placeholder cannot be empty (skipped).");
errorCollector.addError("Error in " + config.getFileName() + ": placeholder cannot be empty (skipped).");
continue;
}
if (placeholder.length() > 100) {
errorCollector.addError("Error in " + pluginConfig.getFileName() + ": placeholder cannot be longer than 100 character (" + placeholder + ").");
errorCollector.addError("Error in " + config.getFileName() + ": placeholder cannot be longer than 100 character (" + placeholder + ").");
continue;
}

View File

@ -0,0 +1,33 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package me.filoghost.chestcommands.config.yaml;
import org.bukkit.configuration.file.YamlConfiguration;
import java.nio.file.Path;
public class Config extends YamlConfiguration {
private final Path path;
public Config(Path path) {
this.path = path;
}
public String getFileName() {
return path.getFileName().toString();
}
}

View File

@ -16,7 +16,6 @@ package me.filoghost.chestcommands.config.yaml;
import me.filoghost.chestcommands.ChestCommands;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.BufferedReader;
import java.io.BufferedWriter;
@ -27,14 +26,11 @@ import java.nio.file.Path;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
/**
* A simple utility class to manage configurations with a file associated to them.
*/
public class PluginConfig extends YamlConfiguration {
public class ConfigLoader {
private final Path path;
public PluginConfig(Path path) {
public ConfigLoader(Path path) {
this.path = path;
}
@ -75,23 +71,26 @@ public class PluginConfig extends YamlConfiguration {
Files.createFile(path);
}
public void load() throws IOException, InvalidConfigurationException {
// To reset all the values when loading
for (String section : this.getKeys(false)) {
set(section, null);
}
public Config load() throws IOException, InvalidConfigurationException {
Config config = new Config(path);
try (BufferedReader reader = Files.newBufferedReader(path)) {
load(reader);
}
config.load(reader);
}
public void save() throws IOException {
return config;
}
public Config loadEmpty() {
return new Config(path);
}
public void save(Config config) throws IOException {
if (path.getParent() != null) {
Files.createDirectories(path.getParent());
}
String data = saveToString();
String data = config.saveToString();
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write(data);

View File

@ -16,6 +16,7 @@ package me.filoghost.chestcommands.config.yaml;
import me.filoghost.chestcommands.util.FormatUtils;
import me.filoghost.chestcommands.util.Log;
import org.bukkit.configuration.InvalidConfigurationException;
import java.io.IOException;
import java.lang.reflect.Field;
@ -28,7 +29,7 @@ import java.util.Map.Entry;
* A special configuration wrapper that reads the values using reflection.
* It will also save default values if not set.
*/
public class SpecialConfig {
public abstract class SpecialConfig {
private transient String header;
private transient Map<String, Object> defaultValuesMap;
@ -37,7 +38,8 @@ public class SpecialConfig {
this.header = header;
}
public void load(PluginConfig config) throws IOException, IllegalAccessException {
public void load(ConfigLoader loader) throws IOException, IllegalAccessException, InvalidConfigurationException {
Config config = loader.load();
// Check if the configuration was initialized
if (defaultValuesMap == null) {
@ -76,7 +78,7 @@ public class SpecialConfig {
if (needsSave) {
config.options().header(header);
config.save();
loader.save(config);
}
// Now read change the fields

View File

@ -14,7 +14,8 @@
*/
package me.filoghost.chestcommands.legacy;
import me.filoghost.chestcommands.config.yaml.PluginConfig;
import me.filoghost.chestcommands.config.yaml.Config;
import me.filoghost.chestcommands.config.yaml.ConfigLoader;
import me.filoghost.chestcommands.util.Preconditions;
import org.bukkit.configuration.InvalidConfigurationException;
@ -58,13 +59,13 @@ public abstract class Upgrade {
return modified;
}
protected void loadConfig(PluginConfig config) throws UpgradeException {
protected Config loadConfig(ConfigLoader configLoader) throws UpgradeException {
try {
config.load();
return configLoader.load();
} catch (IOException e) {
throw new UpgradeException("couldn't read configuration file \"" + config.getFileName() + "\"", e);
throw new UpgradeException("couldn't read configuration file \"" + configLoader.getFileName() + "\"", e);
} catch (InvalidConfigurationException e) {
throw new UpgradeException("couldn't parse YAML syntax of file \"" + config.getFileName() + "\"", e);
throw new UpgradeException("couldn't parse YAML syntax of file \"" + configLoader.getFileName() + "\"", e);
}
}

View File

@ -15,7 +15,7 @@
package me.filoghost.chestcommands.legacy;
import me.filoghost.chestcommands.ChestCommands;
import me.filoghost.chestcommands.config.yaml.PluginConfig;
import me.filoghost.chestcommands.config.yaml.ConfigLoader;
import me.filoghost.chestcommands.legacy.UpgradesDoneRegistry.UpgradeID;
import me.filoghost.chestcommands.legacy.upgrades.MenuUpgrade;
import me.filoghost.chestcommands.legacy.upgrades.PlaceholdersUpgrade;
@ -65,7 +65,7 @@ public class UpgradesExecutor {
try {
List<MenuUpgrade> menuUpgrades = plugin.getMenusPathList().stream()
.map(menuPath -> new MenuUpgrade(new PluginConfig(menuPath), legacyCommandSeparator))
.map(menuPath -> new MenuUpgrade(new ConfigLoader(menuPath), legacyCommandSeparator))
.collect(Collectors.toList());
runIfNecessary(UpgradeID.V4_MENUS, menuUpgrades);
} catch (IOException e) {
@ -91,10 +91,10 @@ public class UpgradesExecutor {
private String readLegacyCommandSeparator() {
String legacyCommandSeparator;
PluginConfig settingsConfig = plugin.getSettingsConfig();
ConfigLoader settingsConfig = plugin.getSettingsConfigLoader();
try {
legacyCommandSeparator = settingsConfig.getString("multiple-commands-separator", ";");
legacyCommandSeparator = settingsConfig.load().getString("multiple-commands-separator", ";");
} catch (Exception e) {
legacyCommandSeparator = ";";
Log.severe("Failed to load " + settingsConfig.getFileName()

View File

@ -14,7 +14,8 @@
*/
package me.filoghost.chestcommands.legacy.upgrades;
import me.filoghost.chestcommands.config.yaml.PluginConfig;
import me.filoghost.chestcommands.config.yaml.Config;
import me.filoghost.chestcommands.config.yaml.ConfigLoader;
import me.filoghost.chestcommands.legacy.Upgrade;
import me.filoghost.chestcommands.legacy.UpgradeException;
import me.filoghost.chestcommands.util.Strings;
@ -29,27 +30,28 @@ import java.util.regex.Pattern;
public class MenuUpgrade extends Upgrade {
private final PluginConfig menuConfig;
private final ConfigLoader menuConfigLoader;
private final String legacyCommandSeparator;
private Config updatedConfig;
public MenuUpgrade(PluginConfig menuConfig, String legacyCommandSeparator) {
this.menuConfig = menuConfig;
public MenuUpgrade(ConfigLoader menuConfigLoader, String legacyCommandSeparator) {
this.menuConfigLoader = menuConfigLoader;
this.legacyCommandSeparator = legacyCommandSeparator;
}
@Override
public Path getOriginalFile() {
return menuConfig.getPath();
return menuConfigLoader.getPath();
}
@Override
public Path getUpgradedFile() {
return menuConfig.getPath();
return menuConfigLoader.getPath();
}
@Override
protected void computeChanges() throws UpgradeException {
loadConfig(menuConfig);
Config menuConfig = loadConfig(menuConfigLoader);
menuConfig.options().header(null);
for (String key : menuConfig.getKeys(true)) {
@ -65,11 +67,13 @@ public class MenuUpgrade extends Upgrade {
upgradeIcon(section);
}
}
this.updatedConfig = menuConfig;
}
@Override
protected void saveChanges() throws IOException {
menuConfig.save();
menuConfigLoader.save(updatedConfig);
}

View File

@ -15,7 +15,8 @@
package me.filoghost.chestcommands.legacy.upgrades;
import me.filoghost.chestcommands.ChestCommands;
import me.filoghost.chestcommands.config.yaml.PluginConfig;
import me.filoghost.chestcommands.config.yaml.Config;
import me.filoghost.chestcommands.config.yaml.ConfigLoader;
import me.filoghost.chestcommands.legacy.Upgrade;
import me.filoghost.chestcommands.legacy.UpgradeException;
import me.filoghost.chestcommands.util.Strings;
@ -28,11 +29,12 @@ import java.util.List;
public class PlaceholdersUpgrade extends Upgrade {
private final PluginConfig newPlaceholdersConfig;
private final ConfigLoader newPlaceholdersConfigLoader;
private final Path oldPlaceholdersFile;
private Config updatedConfig;
public PlaceholdersUpgrade(ChestCommands plugin) {
this.newPlaceholdersConfig = plugin.getPlaceholdersConfig();
this.newPlaceholdersConfigLoader = plugin.getPlaceholdersConfigLoader();
this.oldPlaceholdersFile = plugin.getDataPath("placeholders.yml");
}
@ -43,7 +45,7 @@ public class PlaceholdersUpgrade extends Upgrade {
@Override
public Path getUpgradedFile() {
return newPlaceholdersConfig.getPath();
return newPlaceholdersConfigLoader.getPath();
}
@Override
@ -53,6 +55,7 @@ public class PlaceholdersUpgrade extends Upgrade {
}
// Do NOT load the new placeholder configuration from disk, as it should only contain placeholders imported from the old file
Config newPlaceholdersConfig = newPlaceholdersConfigLoader.loadEmpty();
List<String> lines;
try {
lines = Files.readAllLines(oldPlaceholdersFile);
@ -78,6 +81,8 @@ public class PlaceholdersUpgrade extends Upgrade {
newPlaceholdersConfig.set(placeholder, replacement);
setModified();
}
this.updatedConfig = newPlaceholdersConfig;
}
@Override
@ -85,7 +90,7 @@ public class PlaceholdersUpgrade extends Upgrade {
try {
Files.deleteIfExists(oldPlaceholdersFile);
} catch (IOException ignored) {}
newPlaceholdersConfig.save();
newPlaceholdersConfigLoader.save(updatedConfig);
}
private static String unquote(String input) {

View File

@ -16,7 +16,8 @@ package me.filoghost.chestcommands.legacy.upgrades;
import com.google.common.collect.ImmutableSet;
import me.filoghost.chestcommands.ChestCommands;
import me.filoghost.chestcommands.config.yaml.PluginConfig;
import me.filoghost.chestcommands.config.yaml.Config;
import me.filoghost.chestcommands.config.yaml.ConfigLoader;
import me.filoghost.chestcommands.legacy.Upgrade;
import me.filoghost.chestcommands.legacy.UpgradeException;
@ -32,35 +33,39 @@ public class SettingsUpgrade extends Upgrade {
"multiple-commands-separator"
);
private final PluginConfig settingsConfig;
private final ConfigLoader settingsConfigLoader;
private Config updatedConfig;
public SettingsUpgrade(ChestCommands plugin) {
this.settingsConfig = plugin.getSettingsConfig();
this.settingsConfigLoader = plugin.getSettingsConfigLoader();
}
@Override
public Path getOriginalFile() {
return settingsConfig.getPath();
return settingsConfigLoader.getPath();
}
@Override
public Path getUpgradedFile() {
return settingsConfig.getPath();
return settingsConfigLoader.getPath();
}
@Override
protected void computeChanges() throws UpgradeException {
loadConfig(settingsConfig);
Config settingsConfig = loadConfig(settingsConfigLoader);
for (String removedConfigNode : removedConfigNodes) {
if (settingsConfig.isSet(removedConfigNode)) {
settingsConfig.set(removedConfigNode, null);
setModified();
}
}
this.updatedConfig = settingsConfig;
}
@Override
protected void saveChanges() throws IOException {
settingsConfig.save();
settingsConfigLoader.save(updatedConfig);
}
}

View File

@ -14,14 +14,8 @@
*/
package me.filoghost.chestcommands.parser;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import me.filoghost.chestcommands.action.Action;
import me.filoghost.chestcommands.config.yaml.PluginConfig;
import me.filoghost.chestcommands.config.yaml.Config;
import me.filoghost.chestcommands.menu.AdvancedIconMenu;
import me.filoghost.chestcommands.menu.icon.AdvancedIcon;
import me.filoghost.chestcommands.menu.settings.ClickType;
@ -30,6 +24,11 @@ import me.filoghost.chestcommands.menu.settings.OpenTrigger;
import me.filoghost.chestcommands.parser.IconParser.Coords;
import me.filoghost.chestcommands.util.ErrorCollector;
import me.filoghost.chestcommands.util.FormatUtils;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import java.util.ArrayList;
import java.util.List;
public class MenuParser {
@ -49,7 +48,7 @@ public class MenuParser {
}
public static AdvancedIconMenu loadMenu(PluginConfig config, String title, int rows, ErrorCollector errorCollector) {
public static AdvancedIconMenu loadMenu(Config config, String title, int rows, ErrorCollector errorCollector) {
AdvancedIconMenu iconMenu = new AdvancedIconMenu(title, rows, config.getFileName());
for (String subSectionName : config.getKeys(false)) {
@ -91,7 +90,7 @@ public class MenuParser {
/**
* Reads all the settings of a menu. It will never return a null title, even if not set.
*/
public static MenuSettings loadMenuSettings(PluginConfig config, ErrorCollector errorCollector) {
public static MenuSettings loadMenuSettings(Config config, ErrorCollector errorCollector) {
String title = FormatUtils.addColors(config.getString(Nodes.MENU_NAME));
int rows;