Started working on exclude file (#88) and made file-reloading/updating more organized with an abstract FileHandler

This commit is contained in:
Artemis-the-gr8 2022-10-02 15:19:51 +02:00
parent 6678778e8f
commit 3417233dec
10 changed files with 210 additions and 166 deletions

View File

@ -32,7 +32,7 @@ import org.jetbrains.annotations.NotNull;
*/
public final class Main extends JavaPlugin {
private static Main instance;
private static JavaPlugin pluginInstance;
private static BukkitAudiences adventure;
private static ConfigHandler config;
@ -81,6 +81,18 @@ public final class Main extends JavaPlugin {
this.getLogger().info("Disabled PlayerStats!");
}
/**
*
* @return the JavaPlugin instance associated with PlayerStats
* @throws IllegalStateException if PlayerStats is not enabled
*/
public static @NotNull JavaPlugin getPluginInstance() throws IllegalStateException {
if (pluginInstance == null) {
throw new IllegalStateException("PlayerStats is not loaded!");
}
return pluginInstance;
}
/**
* @return Adventure's BukkitAudiences object
* @throws IllegalStateException if PlayerStats is not enabled
@ -112,7 +124,7 @@ public final class Main extends JavaPlugin {
public static @NotNull LanguageKeyHandler getLanguageKeyHandler() {
if (languageKeyHandler == null) {
languageKeyHandler = new LanguageKeyHandler(instance);
languageKeyHandler = new LanguageKeyHandler();
}
return languageKeyHandler;
}
@ -150,12 +162,12 @@ public final class Main extends JavaPlugin {
}
private void initializeMainClasses() {
instance = this;
pluginInstance = this;
adventure = BukkitAudiences.create(this);
config = new ConfigHandler(this);
config = new ConfigHandler();
enumHandler = new EnumHandler();
languageKeyHandler = new LanguageKeyHandler(instance);
languageKeyHandler = new LanguageKeyHandler();
offlinePlayerHandler = new OfflinePlayerHandler();
shareManager = new ShareManager(config);
@ -171,7 +183,7 @@ public final class Main extends JavaPlugin {
new BukkitRunnable() {
@Override
public void run() {
final Metrics metrics = new Metrics(instance, 15923);
final Metrics metrics = new Metrics(pluginInstance, 15923);
final boolean placeholderExpansionActive;
if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) {
PlaceholderExpansion expansion = PlaceholderAPIPlugin

View File

@ -1,39 +1,39 @@
package com.artemis.the.gr8.playerstats.config;
import com.artemis.the.gr8.playerstats.Main;
import com.artemis.the.gr8.playerstats.enums.Target;
import com.artemis.the.gr8.playerstats.enums.Unit;
import com.artemis.the.gr8.playerstats.utils.FileHandler;
import com.artemis.the.gr8.playerstats.utils.MyLogger;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Map;
/** Handles all PlayerStats' config-settings. */
public final class ConfigHandler {
public final class ConfigHandler extends FileHandler {
private static Main plugin;
private static int configVersion;
private File configFile;
private final int configVersion;
private FileConfiguration config;
public ConfigHandler(Main plugin) {
ConfigHandler.plugin = plugin;
public ConfigHandler() {
super("config.yml");
config = super.getFileConfiguration();
configVersion = 6;
saveDefaultConfig();
config = YamlConfiguration.loadConfiguration(configFile);
checkConfigVersion();
checkAndUpdateConfigVersion();
MyLogger.setDebugLevel(getDebugLevel());
}
@Override
public void reload() {
super.reload();
config = super.getFileConfiguration();
}
/**
* Checks the number that "config-version" returns to see if the
* config needs updating, and if so, send it to the {@link ConfigUpdateHandler}.
* config needs updating, and if so, updates it.
* <br>
* <br>PlayerStats 1.1: "config-version" doesn't exist.
* <br>PlayerStats 1.2: "config-version" is 2.
@ -42,41 +42,18 @@ public final class ConfigHandler {
* <br>PlayerStats 1.5: "config-version" is 5.
* <br>PlayerStats 1.6 and up: "config-version" is 6.
*/
private void checkConfigVersion() {
private void checkAndUpdateConfigVersion() {
if (!config.contains("config-version") || config.getInt("config-version") != configVersion) {
new ConfigUpdateHandler(plugin, configFile, configVersion);
reloadConfig();
}
}
DefaultValueGetter defaultValueGetter = new DefaultValueGetter(config);
Map<String, Object> defaultValues = defaultValueGetter.getValuesToAdjust();
defaultValues.put("config-version", configVersion);
/**
* Create a config file if none exists yet
* (from the config.yml in the plugin's resources).
*/
private void saveDefaultConfig() {
config = plugin.getConfig();
plugin.saveDefaultConfig();
configFile = new File(plugin.getDataFolder(), "config.yml");
}
super.addValues(defaultValues);
super.updateFile();
reload();
/**
* Reloads the config from file, or creates a new file with default values
* if there is none. Also reads the value for debug-level and passes it
* on to {@link MyLogger}.
*
* @return true if the config has been reloaded from disk, false if it failed
*/
public boolean reloadConfig() {
if (!configFile.exists()) {
saveDefaultConfig();
}
try {
config = YamlConfiguration.loadConfiguration(configFile);
return true;
}
catch (IllegalArgumentException e) {
MyLogger.logException(e, "ConfigHandler", "reloadConfig");
return false;
MyLogger.logLowLevelMsg("Your config has been updated to version " + configVersion +
", but all of your custom settings should still be there!");
}
}

View File

@ -1,69 +0,0 @@
package com.artemis.the.gr8.playerstats.config;
import com.artemis.the.gr8.playerstats.Main;
import com.artemis.the.gr8.playerstats.utils.MyLogger;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import com.tchristofferson.configupdater.ConfigUpdater;
public final class ConfigUpdateHandler {
/**
* Add new key-value pairs to the config without losing comments,
* using <a href="https://github.com/tchristofferson/Config-Updater">tchristofferson's Config-Updater</a>
*/
public ConfigUpdateHandler(Main plugin, File configFile, int configVersion) {
YamlConfiguration configuration = YamlConfiguration.loadConfiguration(configFile);
updateTopListDefault(configuration);
updateDefaultColors(configuration);
configuration.set("config-version", configVersion);
try {
configuration.save(configFile);
ConfigUpdater.update(plugin, configFile.getName(), configFile);
MyLogger.logLowLevelMsg("Your config has been updated to version " + configVersion +
", but all of your custom settings should still be there!");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Adjusts the value for "top-list" to migrate the config file from
* versions 1 or 2 to version 3 and above.
*/
private void updateTopListDefault(YamlConfiguration configuration) {
String oldTitle = configuration.getString("top-list-title");
if (oldTitle != null && oldTitle.equalsIgnoreCase("Top [x]")) {
configuration.set("top-list-title", "Top");
}
}
/**
* Adjusts some of the default colors to migrate from versions 2
* or 3 to version 4 and above.
*/
private void updateDefaultColors(YamlConfiguration configuration) {
updateColor(configuration, "top-list.title", "yellow", "#FFD52B");
updateColor(configuration, "top-list.title", "#FFEA40", "#FFD52B");
updateColor(configuration, "top-list.stat-names", "yellow", "#FFD52B");
updateColor(configuration, "top-list.stat-names", "#FFEA40", "#FFD52B");
updateColor(configuration, "top-list.sub-stat-names", "#FFD52B", "yellow");
updateColor(configuration, "individual-statistics.stat-names", "yellow", "#FFD52B");
updateColor(configuration, "individual-statistics.sub-stat-names", "#FFD52B", "yellow");
updateColor(configuration, "total-server.title", "gold", "#55AAFF");
updateColor(configuration, "total-server.server-name", "gold", "#55AAFF");
updateColor(configuration, "total-server.stat-names", "yellow", "#FFD52B");
updateColor(configuration, "total-server.sub-stat-names", "#FFD52B", "yellow");
}
private void updateColor(YamlConfiguration configuration, String path, String oldValue, String newValue) {
String configString = configuration.getString(path);
if (configString != null && configString.equalsIgnoreCase(oldValue)) {
configuration.set(path, newValue);
}
}
}

View File

@ -0,0 +1,56 @@
package com.artemis.the.gr8.playerstats.config;
import org.bukkit.configuration.file.FileConfiguration;
import java.util.HashMap;
import java.util.Map;
public class DefaultValueGetter {
private final FileConfiguration config;
private final Map<String, Object> defaultValuesToAdjust;
public DefaultValueGetter(FileConfiguration configuration) {
config = configuration;
defaultValuesToAdjust = new HashMap<>();
}
public Map<String, Object> getValuesToAdjust() {
checkTopListDefault();
checkDefaultColors();
return defaultValuesToAdjust;
}
private void checkTopListDefault() {
String oldTitle = config.getString("top-list-title");
if (oldTitle != null && oldTitle.equalsIgnoreCase("Top [x]")) {
defaultValuesToAdjust.put("top-list-title", "Top");
}
}
/**
* Adjusts some of the default colors to migrate from versions 2
* or 3 to version 4 and above.
*/
private void checkDefaultColors() {
addValueIfNeeded("top-list.title", "yellow", "#FFD52B");
addValueIfNeeded("top-list.title", "#FFEA40", "#FFD52B");
addValueIfNeeded("top-list.stat-names", "yellow", "#FFD52B");
addValueIfNeeded("top-list.stat-names", "#FFEA40", "#FFD52B");
addValueIfNeeded("top-list.sub-stat-names", "#FFD52B", "yellow");
addValueIfNeeded("individual-statistics.stat-names", "yellow", "#FFD52B");
addValueIfNeeded("individual-statistics.sub-stat-names", "#FFD52B", "yellow");
addValueIfNeeded("total-server.title", "gold", "#55AAFF");
addValueIfNeeded("total-server.server-name", "gold", "#55AAFF");
addValueIfNeeded("total-server.stat-names", "yellow", "#FFD52B");
addValueIfNeeded("total-server.sub-stat-names", "#FFD52B", "yellow");
}
private void addValueIfNeeded(String path, String oldValue, String newValue) {
String configString = config.getString(path);
if (configString != null && configString.equalsIgnoreCase(oldValue)) {
defaultValuesToAdjust.put(path, newValue);
}
}
}

View File

@ -1,5 +1,6 @@
package com.artemis.the.gr8.playerstats.msg.components;
import com.artemis.the.gr8.playerstats.Main;
import com.artemis.the.gr8.playerstats.msg.msgutils.LanguageKeyHandler;
import com.artemis.the.gr8.playerstats.msg.msgutils.StringUtils;
import net.kyori.adventure.text.*;
@ -61,14 +62,14 @@ public final class ComponentUtils {
}
else if (!LanguageKeyHandler.isKeyForEntityKilledByArg(translatable.key())) {
totalPrettyName.append(
LanguageKeyHandler.getStatKeyTranslation(
Main.getLanguageKeyHandler().getStatKeyTranslation(
translatable.key()));
}
}
});
}
else if (trans.key().startsWith("stat")) {
return LanguageKeyHandler.getStatKeyTranslation(trans.key());
return Main.getLanguageKeyHandler().getStatKeyTranslation(trans.key());
}
else {
return StringUtils.prettify(LanguageKeyHandler.convertToName(trans.key()));

View File

@ -1,19 +1,14 @@
package com.artemis.the.gr8.playerstats.msg.msgutils;
import com.artemis.the.gr8.playerstats.Main;
import com.artemis.the.gr8.playerstats.utils.EnumHandler;
import com.artemis.the.gr8.playerstats.utils.MyLogger;
import com.artemis.the.gr8.playerstats.utils.FileHandler;
import com.artemis.the.gr8.playerstats.enums.Unit;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.ApiStatus.Internal;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
@ -22,42 +17,18 @@ import java.util.HashMap;
* A utility class that provides language keys to be
* put in a TranslatableComponent.
*/
public final class LanguageKeyHandler {
public final class LanguageKeyHandler extends FileHandler {
private static Main plugin;
private static HashMap<Statistic, String> statNameKeys;
private static File languageKeyFile;
private static FileConfiguration languageKeys;
/**
* Since this class uses a file to get the English translations
* of languageKeys, it needs an instance of the PlayerStats
* This class uses a file to get the English translations
* of languageKeys, and uses an instance of the PlayerStats
* plugin to get access to this file.
*
* @param plugin an instance of PlayerStats' Main class
*/
public LanguageKeyHandler(Main plugin) {
LanguageKeyHandler.plugin = plugin;
public LanguageKeyHandler() {
super("language.yml");
statNameKeys = generateStatNameKeys();
loadFile();
}
private static void loadFile() {
languageKeyFile = new File(plugin.getDataFolder(), "language.yml");
if (!languageKeyFile.exists()) {
plugin.saveResource("language.yml", false);
}
languageKeys = YamlConfiguration.loadConfiguration(languageKeyFile);
}
@Internal
public static void reloadFile() {
if (!languageKeyFile.exists()) {
loadFile();
} else {
languageKeys = YamlConfiguration.loadConfiguration(languageKeyFile);
MyLogger.logLowLevelMsg("Language file reloaded!");
}
}
/**
@ -183,12 +154,12 @@ public final class LanguageKeyHandler {
}
}
public static String getStatKeyTranslation(String statKey) {
public String getStatKeyTranslation(String statKey) {
String realKey = convertToNormalStatKey(statKey);
if (realKey == null) {
return "";
}
return languageKeys.getString(realKey);
return super.getFileConfiguration().getString(statKey);
}
/**

View File

@ -1,10 +1,10 @@
package com.artemis.the.gr8.playerstats.reload;
import com.artemis.the.gr8.playerstats.Main;
import com.artemis.the.gr8.playerstats.ShareManager;
import com.artemis.the.gr8.playerstats.ThreadManager;
import com.artemis.the.gr8.playerstats.enums.StandardMessage;
import com.artemis.the.gr8.playerstats.msg.OutputManager;
import com.artemis.the.gr8.playerstats.msg.msgutils.LanguageKeyHandler;
import com.artemis.the.gr8.playerstats.statistic.StatCalculator;
import com.artemis.the.gr8.playerstats.statistic.StatThread;
import com.artemis.the.gr8.playerstats.utils.MyLogger;
@ -69,7 +69,7 @@ public final class ReloadThread extends Thread {
}
}
if (reloadThreadID != 1 && config.reloadConfig()) { //during a reload
if (reloadThreadID != 1) { //during a reload
MyLogger.logLowLevelMsg("Reloading!");
reloadEverything();
@ -85,8 +85,10 @@ public final class ReloadThread extends Thread {
}
private void reloadEverything() {
config.reload();
MyLogger.setDebugLevel(config.getDebugLevel());
LanguageKeyHandler.reloadFile();
Main.getLanguageKeyHandler().reload();
Main.getOfflinePlayerHandler().reload();
OutputManager.updateMessageBuilders();
OfflinePlayerHandler.updateOfflinePlayerList(loadOfflinePlayers());
ShareManager.updateSettings(config);

View File

@ -0,0 +1,77 @@
package com.artemis.the.gr8.playerstats.utils;
import com.artemis.the.gr8.playerstats.Main;
import com.tchristofferson.configupdater.ConfigUpdater;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public abstract class FileHandler {
private final String fileName;
private File file;
private FileConfiguration fileConfiguration;
public FileHandler(String fileName) {
this.fileName = fileName;
loadFile();
}
public void loadFile() {
JavaPlugin plugin = Main.getPluginInstance();
file = new File(plugin.getDataFolder(), fileName);
if (!file.exists()) {
plugin.saveResource(fileName, false);
}
fileConfiguration = YamlConfiguration.loadConfiguration(file);
}
public void reload() {
if (!file.exists()) {
loadFile();
} else {
fileConfiguration = YamlConfiguration.loadConfiguration(file);
MyLogger.logLowLevelMsg(fileName + " reloaded!");
}
}
public FileConfiguration getFileConfiguration() {
return fileConfiguration;
}
/**
* Add new key-value pairs to the config without losing comments,
* using <a href="https://github.com/tchristofferson/Config-Updater">tchristofferson's Config-Updater</a>
*/
public void updateFile() {
JavaPlugin plugin = Main.getPluginInstance();
try {
ConfigUpdater.update(plugin, fileName, file);
} catch (IOException e) {
e.printStackTrace();
}
}
public void addValues(@NotNull Map<String, Object> keyValuePairs) {
keyValuePairs.forEach(this::addValue);
save();
}
private void addValue(String key, Object value) {
fileConfiguration.set(key, value);
}
private void save() {
try {
fileConfiguration.save(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -12,16 +12,23 @@ import java.util.concurrent.ConcurrentHashMap;
* calculations, and can retrieve the corresponding OfflinePlayer
* object for a given player-name.
*/
public final class OfflinePlayerHandler {
public final class OfflinePlayerHandler extends FileHandler {
private static ConcurrentHashMap<String, UUID> offlinePlayerUUIDs;
private static ArrayList<String> playerNames;
public OfflinePlayerHandler() {
super("excluded_players.yml");
offlinePlayerUUIDs = new ConcurrentHashMap<>();
playerNames = new ArrayList<>();
}
@Override
public void reload() {
super.reload();
}
/**
* Get a new HashMap that stores the players to include in stat calculations.
* This HashMap is stored as a private variable in OfflinePlayerHandler.

View File

@ -0,0 +1,10 @@
# ------------------------------------------------------------------------------------------------------ #
# PlayerStats Excluded Players #
# ------------------------------------------------------------------------------------------------------ #
# Players whose UUIDs are stored in this file, will not be included in /statistic results.
# This can be used for more fine-grained filtering, for example to exclude alt accounts.
# For more general filtering settings, see the config.yml
excluded:
-