From a72109667a9fbefbf68415d0b37bf0bca547bb5f Mon Sep 17 00:00:00 2001 From: William Date: Sun, 12 Mar 2023 12:49:46 +0000 Subject: [PATCH] More work on commands --- .../william278/huskhomes/BukkitHuskHomes.java | 62 +++--- .../huskhomes/command/BrigadierUtil.java | 4 +- .../huskhomes/util/BukkitLogger.java | 40 ---- .../net/william278/huskhomes/HuskHomes.java | 20 +- .../huskhomes/command/DelHomeCommand.java | 2 +- .../huskhomes/command/DelWarpCommand.java | 2 +- .../huskhomes/command/EditHomeCommand.java | 210 ++++++++++-------- .../huskhomes/command/HomeCommand.java | 8 +- .../huskhomes/command/HomeListCommand.java | 10 +- .../huskhomes/command/HuskHomesCommand.java | 16 +- .../huskhomes/command/PublicHomeCommand.java | 8 +- .../command/PublicHomeListCommand.java | 6 +- .../huskhomes/command/RtpCommand.java | 12 +- .../command/SavedPositionCommand.java | 2 +- .../huskhomes/command/TpCommand.java | 10 +- .../huskhomes/command/WarpCommand.java | 8 +- .../huskhomes/command/WarpListCommand.java | 6 +- .../william278/huskhomes/config/Settings.java | 8 - .../huskhomes/database/Database.java | 15 -- .../huskhomes/database/MySqlDatabase.java | 64 +++--- .../huskhomes/database/SqLiteDatabase.java | 76 +++---- .../huskhomes/hook/BlueMapHook.java | 2 +- .../william278/huskhomes/hook/PlanHook.java | 17 +- .../huskhomes/listener/EventListener.java | 2 +- .../huskhomes/manager/HomesManager.java | 66 +++++- .../huskhomes/manager/WarpsManager.java | 10 +- .../network/PluginMessageBroker.java | 4 +- .../huskhomes/network/RedisBroker.java | 2 +- .../huskhomes/position/Location.java | 14 ++ .../huskhomes/position/Position.java | 13 +- .../william278/huskhomes/user/SavedUser.java | 45 +++- .../net/william278/huskhomes/util/Logger.java | 34 --- .../huskhomes/util/ValidationException.java | 29 ++- 33 files changed, 445 insertions(+), 382 deletions(-) delete mode 100644 bukkit/src/main/java/net/william278/huskhomes/util/BukkitLogger.java delete mode 100644 common/src/main/java/net/william278/huskhomes/util/Logger.java diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index 9bd50632..b968b449 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -65,7 +65,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess private static final int METRICS_ID = 8430; private Settings settings; private Locales locales; - private BukkitLogger logger; private Database database; private Cache cache; private Validator validator; @@ -103,24 +102,20 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess // Initialize HuskHomes final AtomicBoolean initialized = new AtomicBoolean(true); try { - // Set the logging and resource reading adapter - this.logger = new BukkitLogger(getLogger()); - // Create adventure audience this.audiences = BukkitAudiences.create(this); // Load settings and locales - getLoggingAdapter().log(Level.INFO, "Loading plugin configuration settings & locales..."); + log(Level.INFO, "Loading plugin configuration settings & locales..."); initialized.set(reload()); if (initialized.get()) { - logger.showDebugLogs(settings.doDebugLogging()); - getLoggingAdapter().log(Level.INFO, "Successfully loaded plugin configuration settings & locales"); + log(Level.INFO, "Successfully loaded plugin configuration settings & locales"); } else { throw new IllegalStateException("Failed to load plugin configuration settings and/or locales"); } // Initialize the database - getLoggingAdapter().log(Level.INFO, "Attempting to establish connection to the database..."); + log(Level.INFO, "Attempting to establish connection to the database..."); final Database.DatabaseType databaseType = settings.getDatabaseType(); this.database = switch (databaseType == null ? Database.DatabaseType.MYSQL : databaseType) { case MYSQL -> new MySqlDatabase(this); @@ -128,20 +123,20 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess }; initialized.set(this.database.initialize()); if (initialized.get()) { - getLoggingAdapter().log(Level.INFO, "Successfully established a connection to the database"); + log(Level.INFO, "Successfully established a connection to the database"); } else { throw new IllegalStateException("Failed to establish a connection to the database. " + "Please check the supplied database credentials in the config file"); } // Initialize the network messenger if proxy mode is enabled if (getSettings().isCrossServer()) { - getLoggingAdapter().log(Level.INFO, "Initializing the network messenger..."); + log(Level.INFO, "Initializing the network messenger..."); broker = switch (settings.getBrokerType()) { case PLUGIN_MESSAGE -> new PluginMessageBroker(this); case REDIS -> new RedisBroker(this); }; broker.initialize(); - getLoggingAdapter().log(Level.INFO, "Successfully initialized the network messenger."); + log(Level.INFO, "Successfully initialized the network messenger."); } // Prepare the validator @@ -189,16 +184,16 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess if (pluginHooks.size() > 0) { pluginHooks.forEach(PluginHook::initialize); - getLoggingAdapter().log(Level.INFO, "Registered " + pluginHooks.size() + " plugin hooks: " + pluginHooks.stream().map(PluginHook::getHookName).collect(Collectors.joining(", "))); + log(Level.INFO, "Registered " + pluginHooks.size() + " plugin hooks: " + pluginHooks.stream().map(PluginHook::getHookName).collect(Collectors.joining(", "))); } // Register events - getLoggingAdapter().log(Level.INFO, "Registering events..."); + log(Level.INFO, "Registering events..."); this.eventListener = new BukkitEventListener(this); - getLoggingAdapter().log(Level.INFO, "Successfully registered events listener"); + log(Level.INFO, "Successfully registered events listener"); // Register permissions - getLoggingAdapter().log(Level.INFO, "Registering permissions & commands..."); + log(Level.INFO, "Registering permissions & commands..."); Arrays.stream(Permission.values()).forEach(permission -> getServer().getPluginManager().addPermission(new org.bukkit.permissions.Permission(permission.node, switch (permission.defaultAccess) { case EVERYONE -> PermissionDefault.TRUE; case NOBODY -> PermissionDefault.FALSE; @@ -227,28 +222,28 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess this.registeredCommands.add(command); new BukkitCommand(command, this).register(pluginCommand); }); - getLoggingAdapter().log(Level.INFO, "Successfully registered permissions & commands."); + log(Level.INFO, "Successfully registered permissions & commands."); // Hook into bStats metrics registerMetrics(METRICS_ID); // Check for updates if (settings.doCheckForUpdates()) { - getLoggingAdapter().log(Level.INFO, "Checking for updates..."); - getLatestVersionIfOutdated().thenAccept(newestVersion -> newestVersion.ifPresent(newVersion -> getLoggingAdapter().log(Level.WARNING, "An update is available for HuskHomes, v" + newVersion + " (Currently running v" + getVersion() + ")"))); + log(Level.INFO, "Checking for updates..."); + getLatestVersionIfOutdated().thenAccept(newestVersion -> newestVersion.ifPresent(newVersion -> log(Level.WARNING, "An update is available for HuskHomes, v" + newVersion + " (Currently running v" + getVersion() + ")"))); } } catch (IllegalStateException exception) { - getLoggingAdapter().log(Level.SEVERE, exception.getMessage()); + log(Level.SEVERE, exception.getMessage()); initialized.set(false); } catch (Exception exception) { - getLoggingAdapter().log(Level.SEVERE, "An unhandled exception occurred initializing HuskHomes!", exception); + log(Level.SEVERE, "An unhandled exception occurred initializing HuskHomes!", exception); initialized.set(false); } finally { // Validate initialization if (initialized.get()) { - getLoggingAdapter().log(Level.INFO, "Successfully enabled HuskHomes v" + getVersion()); + log(Level.INFO, "Successfully enabled HuskHomes v" + getVersion()); } else { - getLoggingAdapter().log(Level.SEVERE, "Failed to initialize HuskHomes. The plugin will now be disabled"); + log(Level.SEVERE, "Failed to initialize HuskHomes. The plugin will now be disabled"); getServer().getPluginManager().disablePlugin(this); } } @@ -280,12 +275,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess return audiences; } - @NotNull - @Override - public Logger getLoggingAdapter() { - return logger; - } - @Override @NotNull public ConsoleUser getConsole() { @@ -372,7 +361,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess try { Annotaml.create(new File(getDataFolder(), "spawn.yml"), newSpawn); } catch (IOException e) { - getLoggingAdapter().log(Level.WARNING, "Failed to save server spawn to disk", e); + log(Level.WARNING, "Failed to save server spawn to disk", e); } // Update the world spawn location, too @@ -476,7 +465,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess return true; } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { - getLoggingAdapter().log(Level.SEVERE, "Failed to reload HuskHomes config or messages file", e); + log(Level.SEVERE, "Failed to reload HuskHomes config or messages file", e); } return false; } @@ -502,7 +491,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess metrics.addCustomChart(new SimplePie("map_type", () -> getSettings().getMappingPlugin().displayName)); } } catch (Exception e) { - getLoggingAdapter().log(Level.WARNING, "Failed to register metrics", e); + log(Level.WARNING, "Failed to register metrics", e); } } @@ -512,10 +501,19 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess Bukkit.getMessenger().registerOutgoingPluginChannel(this, PluginMessageBroker.BUNGEE_CHANNEL_ID); } + @Override + public void log(@NotNull Level level, @NotNull String message, @NotNull Throwable... exceptions) { + if (exceptions.length > 0) { + getLogger().log(level, message, exceptions[0]); + return; + } + getLogger().log(level, message); + } + @Override public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) { if (broker != null && broker instanceof PluginMessageBroker pluginMessenger - && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { + && getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { pluginMessenger.onReceive(channel, BukkitUser.adapt(player), message); } } diff --git a/bukkit/src/main/java/net/william278/huskhomes/command/BrigadierUtil.java b/bukkit/src/main/java/net/william278/huskhomes/command/BrigadierUtil.java index 182ad659..11f7d5c7 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/command/BrigadierUtil.java +++ b/bukkit/src/main/java/net/william278/huskhomes/command/BrigadierUtil.java @@ -28,9 +28,9 @@ public class BrigadierUtil { try { CommodoreProvider.getCommodore(plugin).register(pluginCommand, CommodoreFileReader.INSTANCE.parse(commandCommodore), - player -> player.hasPermission(command.permission)); + player -> player.hasPermission(command.getPermission())); } catch (IOException e) { - plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to read command commodore completions for " + plugin.log(Level.SEVERE, "Failed to read command commodore completions for " + pluginCommand.getName(), e); } } diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitLogger.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitLogger.java deleted file mode 100644 index 95132099..00000000 --- a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitLogger.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.william278.huskhomes.util; - -import org.jetbrains.annotations.NotNull; - -import java.util.logging.Level; - -public class BukkitLogger extends Logger { - - private final java.util.logging.Logger logger; - - public BukkitLogger(@NotNull java.util.logging.Logger logger) { - this.logger = logger; - } - - @Override - public void log(@NotNull Level level, @NotNull String message, @NotNull Throwable e) { - logger.log(level, message, e); - } - - @Override - public void log(@NotNull Level level, @NotNull String message) { - logger.log(level, message); - } - - @Override - public void info(@NotNull String message) { - logger.info(message); - } - - @Override - public void severe(@NotNull String message) { - logger.severe(message); - } - - @Override - public void config(@NotNull String message) { - logger.config(message); - } - -} diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 6203b2ee..c3fd7ff2 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -21,7 +21,6 @@ import net.william278.huskhomes.user.ConsoleUser; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.position.*; import net.william278.huskhomes.random.RandomTeleportEngine; -import net.william278.huskhomes.util.Logger; import net.william278.huskhomes.util.Permission; import net.william278.huskhomes.util.TaskRunner; import net.william278.huskhomes.util.Validator; @@ -35,6 +34,7 @@ import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; +import java.util.logging.Level; /** * Represents a cross-platform instance of the plugin @@ -43,14 +43,6 @@ public interface HuskHomes extends TaskRunner { int SPIGOT_RESOURCE_ID = 83767; - /** - * The platform plugin console logger - * - * @return the {@link Logger} implementation to use - */ - @NotNull - Logger getLoggingAdapter(); - @NotNull ConsoleUser getConsole(); @@ -367,6 +359,15 @@ public interface HuskHomes extends TaskRunner { */ void initializePluginChannels(); + /** + * Log a message to the console + * + * @param level the level to log at + * @param message the message to log + * @param exceptions any exceptions to log + */ + void log(@NotNull Level level, @NotNull String message, @NotNull Throwable... exceptions); + /** * Create a resource key namespaced with the plugin id * @@ -387,4 +388,5 @@ public interface HuskHomes extends TaskRunner { return Converters.registerOffsetDateTime(new GsonBuilder().excludeFieldsWithoutExposeAnnotation()).create(); } + } diff --git a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java index 01e0ff27..14574531 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java @@ -8,7 +8,7 @@ import org.jetbrains.annotations.NotNull; import java.util.List; -public class DelHomeCommand extends SavedPositionCommand implements TabProvider { +public class DelHomeCommand extends SavedPositionCommand { public DelHomeCommand(@NotNull HuskHomes implementor) { super("delhome", List.of(), Home.class, List.of(), implementor); diff --git a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java index 4d0ff3da..59aa6322 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java @@ -8,7 +8,7 @@ import org.jetbrains.annotations.NotNull; import java.util.List; -public class DelWarpCommand extends SavedPositionCommand implements TabProvider { +public class DelWarpCommand extends SavedPositionCommand { public DelWarpCommand(@NotNull HuskHomes implementor) { super("delwarp", List.of(), Warp.class, List.of(), implementor); diff --git a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java index 6ec357e7..71c5b0ca 100644 --- a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java @@ -4,72 +4,130 @@ import de.themoep.minedown.adventure.MineDown; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.hook.EconomyHook; -import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.PositionMeta; +import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.util.Permission; +import net.william278.huskhomes.util.ValidationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.time.ZoneId; import java.time.format.DateTimeFormatter; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.StringJoiner; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; -import java.util.stream.Collectors; -public class EditHomeCommand extends Command implements TabProvider { +public class EditHomeCommand extends SavedPositionCommand { - private final String[] EDIT_HOME_COMPLETIONS = {"rename", "description", "relocate", "privacy"}; - - public EditHomeCommand(@NotNull HuskHomes implementor) { - super("edithome", Permission.COMMAND_EDIT_HOME, implementor); + public EditHomeCommand(@NotNull HuskHomes plugin) { + super("edithome", List.of(), Home.class, List.of("rename", "description", "relocate", "privacy"), plugin); } @Override - public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { - if (args.length >= 1) { - final String homeName = args[0]; - final String editOperation = args.length >= 2 ? args[1] : null; - final String editArgs = getEditArguments(args); + public void execute(@NotNull CommandUser executor, @NotNull Home home, @NotNull String[] args) { + final boolean ownerEditing = home.getOwner().equals(executor); + if (!ownerEditing && !executor.hasPermission(getOtherPermission())) { + plugin.getLocales().getLocale("error_no_permission") + .ifPresent(executor::sendMessage); + return; + } - RegexUtil.matchDisambiguatedHomeIdentifier(homeName).ifPresentOrElse( - homeIdentifier -> plugin.getDatabase().getUserDataByName(homeIdentifier.ownerName()) - .thenAcceptAsync(optionalUserData -> optionalUserData.ifPresentOrElse(userData -> { - if (!userData.getUserUuid().equals(onlineUser.getUuid())) { - if (!onlineUser.hasPermission(Permission.COMMAND_EDIT_HOME_OTHER.node)) { - plugin.getLocales().getLocale("error_no_permission") - .ifPresent(onlineUser::sendMessage); - return; - } - } - plugin.getDatabase().getHome(userData.user(), homeIdentifier.homeName()).thenAcceptAsync(optionalHome -> { - if (optionalHome.isEmpty()) { - plugin.getLocales().getLocale("error_home_invalid_other", - homeIdentifier.ownerName(), homeIdentifier.homeName()) - .ifPresent(onlineUser::sendMessage); - return; - } - editHome(optionalHome.get(), onlineUser, editOperation, editArgs); - }); + final Optional operation = parseStringArg(args, 0); + if (operation.isEmpty()) { + getHomeEditorWindow(home, true, !ownerEditing, + !ownerEditing || executor.hasPermission(Permission.COMMAND_HOME_OTHER.node), + executor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) + .forEach(executor::sendMessage); + return; + } - }, - () -> plugin.getLocales().getLocale("error_home_invalid_other", - homeIdentifier.ownerName(), homeIdentifier.homeName()) - .ifPresent(onlineUser::sendMessage))), - () -> plugin.getDatabase().getHome(onlineUser, homeName).thenAcceptAsync(optionalHome -> { - if (optionalHome.isEmpty()) { - plugin.getLocales().getLocale("error_home_invalid", homeName) - .ifPresent(onlineUser::sendMessage); - return; - } - editHome(optionalHome.get(), onlineUser, editOperation, editArgs); - }) - ); - } else { + if (!arguments.contains(operation.get().toLowerCase())) { plugin.getLocales().getLocale("error_invalid_syntax", - "/edithome [" + String.join("|", EDIT_HOME_COMPLETIONS) + "] [args]") - .ifPresent(onlineUser::sendMessage); + "/edithome " + home.getName() + " <" + String.join("|", arguments) + ">") + .ifPresent(executor::sendMessage); + return; + } + + switch (operation.get().toLowerCase()) { + case "rename" -> { + final Optional newName = parseStringArg(args, 1); + if (newName.isEmpty()) { + plugin.getLocales().getLocale("error_invalid_syntax", + "/edithome " + home.getName() + " rename ") + .ifPresent(executor::sendMessage); + return; + } + + try { + plugin.getManager().homes().renameHome(home.getOwner(), home.getName(), newName.get()); + } catch (ValidationException e) { + e.dispatchHomeError(executor, false, plugin, newName.get()); + return; + } + + if (ownerEditing) { + plugin.getLocales().getLocale("edit_home_update_name", home.getName(), newName.get()) + .ifPresent(executor::sendMessage); + } else { + plugin.getLocales().getLocale("edit_home_update_name_other", home.getOwner().getUsername(), + home.getName(), newName.get()) + .ifPresent(executor::sendMessage); + } + } + case "description" -> { + final Optional newDescription = parseGreedyString(args, 1); + if (newDescription.isEmpty()) { + plugin.getLocales().getLocale("error_invalid_syntax", + "/edithome " + home.getName() + " description ") + .ifPresent(executor::sendMessage); + return; + } + + try { + plugin.getManager().homes().updateHomeDescription(home.getOwner(), home.getName(), newDescription.get()); + } catch (ValidationException e) { + e.dispatchHomeError(executor, false, plugin, newDescription.get()); + return; + } + + if (ownerEditing) { + plugin.getLocales().getLocale("edit_home_update_description", home.getName(), newDescription.get()) + .ifPresent(executor::sendMessage); + } else { + plugin.getLocales().getLocale("edit_home_update_description_other", home.getOwner().getUsername(), + home.getName(), newDescription.get()) + .ifPresent(executor::sendMessage); + } + } + case "relocate" -> { + if (!(executor instanceof OnlineUser user)) { + plugin.getLocales().getLocale("error_in_game_only") + .ifPresent(executor::sendMessage); + return; + } + + try { + plugin.getManager().homes().relocateHome(user, home.getName(), user.getPosition()); + } catch (ValidationException e) { + e.dispatchHomeError(executor, false, plugin, home.getName()); + } + + if (ownerEditing) { + plugin.getLocales().getLocale("edit_home_update_location", home.getName()) + .ifPresent(executor::sendMessage); + } else { + plugin.getLocales().getLocale("edit_home_update_location_other", home.getOwner().getUsername(), home.getName()) + .ifPresent(executor::sendMessage); + } + } + case "privacy" -> { + + } } } @@ -87,10 +145,6 @@ public class EditHomeCommand extends Command implements TabProvider { final boolean otherOwner = !editor.equals(home.getOwner()); if (editOperation == null) { - getHomeEditorWindow(home, true, otherOwner, - !otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node), - editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) - .forEach(editor::sendMessage); return; } if (editArgs != null) { @@ -163,24 +217,23 @@ public class EditHomeCommand extends Command implements TabProvider { default -> plugin.getLocales().getLocale("error_home_name_characters"); }).ifPresent(editor::sendMessage)); } - case "relocate" -> - plugin.getManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> { - if (home.getOwner().equals(editor)) { - editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location", - home.getMeta().getName()).orElse(new MineDown(""))); - } else { - editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location_other", - home.getOwner().getUsername(), home.getMeta().getName()).orElse(new MineDown(""))); - } + case "relocate" -> plugin.getManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> { + if (home.getOwner().equals(editor)) { + editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location", + home.getMeta().getName()).orElse(new MineDown(""))); + } else { + editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location_other", + home.getOwner().getUsername(), home.getMeta().getName()).orElse(new MineDown(""))); + } - // Show the menu if the menu flag is set - if (showMenuFlag.get()) { - getHomeEditorWindow(home, false, otherOwner, - !otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node), - editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) - .forEach(editor::sendMessage); - } - }); + // Show the menu if the menu flag is set + if (showMenuFlag.get()) { + getHomeEditorWindow(home, false, otherOwner, + !otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node), + editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) + .forEach(editor::sendMessage); + } + }); case "privacy" -> { if (!editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) { plugin.getLocales().getLocale("error_no_permission") @@ -344,23 +397,4 @@ public class EditHomeCommand extends Command implements TabProvider { }}; } - @Override - @NotNull - public final List suggest(@NotNull CommandUser user, @NotNull String[] args) { - if (user == null) { - return Collections.emptyList(); - } - return switch (args.length) { - case 0, 1 -> plugin.getCache().getHomes().getOrDefault(user.getUuid(), new ArrayList<>()) - .stream() - .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) - .sorted() - .collect(Collectors.toList()); - case 2 -> Arrays.stream(EDIT_HOME_COMPLETIONS) - .filter(s -> s.toLowerCase().startsWith(args[1].toLowerCase())) - .sorted() - .collect(Collectors.toList()); - default -> Collections.emptyList(); - }; - } } diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java index 4f8e56d3..f058ab2d 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java @@ -85,13 +85,13 @@ public class HomeCommand extends Command implements TabProvider, ConsoleExecutab @Override public void onConsoleExecute(@NotNull String[] args) { if (args.length != 2) { - plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: home "); + plugin.log(Level.WARNING, "Invalid syntax. Usage: home "); return; } CompletableFuture.runAsync(() -> { final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); if (playerToTeleport == null) { - plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); + plugin.log(Level.WARNING, "Player not found: " + args[0]); return; } final AtomicReference matchedHome = new AtomicReference<>(null); @@ -105,11 +105,11 @@ public class HomeCommand extends Command implements TabProvider, ConsoleExecutab final Home home = matchedHome.get(); if (home == null) { - plugin.getLoggingAdapter().log(Level.WARNING, "Could not find home '" + args[1] + "'"); + plugin.log(Level.WARNING, "Could not find home '" + args[1] + "'"); return; } - plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to " + plugin.log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to " + home.getOwner().getUsername() + "." + home.getMeta().getName()); Teleport.builder(plugin, playerToTeleport) .setTarget(home) diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java index b274b9d2..a19a52a9 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java @@ -86,29 +86,29 @@ public class HomeListCommand extends Command implements ConsoleExecutable { @Override public void onConsoleExecute(@NotNull String[] args) { if (args.length != 1) { - plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: homelist "); + plugin.log(Level.WARNING, "Invalid syntax. Usage: homelist "); return; } CompletableFuture.runAsync(() -> { final Optional userData = plugin.getDatabase().getUserDataByName(args[0]).join(); if (userData.isEmpty()) { - plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); + plugin.log(Level.WARNING, "Player not found: " + args[0]); return; } final List homes = plugin.getDatabase().getHomes(userData.get().user()).join(); StringJoiner rowJoiner = new StringJoiner("\t"); - plugin.getLoggingAdapter().log(Level.INFO, "List of " + userData.get().user().getUsername() + "'s " + plugin.log(Level.INFO, "List of " + userData.get().user().getUsername() + "'s " + homes.size() + " homes:"); for (int i = 0; i < homes.size(); i++) { final String home = homes.get(i).getMeta().getName(); rowJoiner.add(home.length() < 16 ? home + " ".repeat(16 - home.length()) : home); if ((i + 1) % 3 == 0) { - plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); + plugin.log(Level.INFO, rowJoiner.toString()); rowJoiner = new StringJoiner("\t"); } } - plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); + plugin.log(Level.INFO, rowJoiner.toString()); }); } } diff --git a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java index f68fb5e0..7edbac1f 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java @@ -116,33 +116,33 @@ public class HuskHomesCommand extends Command implements ConsoleExecutable, TabP public void onConsoleExecute(@NotNull String[] args) { if (args.length == 0) { Arrays.stream(aboutMenu.toString().split("\n")).forEach(message -> - plugin.getLoggingAdapter().log(Level.INFO, message)); + plugin.log(Level.INFO, message)); return; } switch (args[0].toLowerCase()) { case "about" -> Arrays.stream(aboutMenu.toString().split("\n")).forEach(message -> - plugin.getLoggingAdapter().log(Level.INFO, message)); + plugin.log(Level.INFO, message)); case "help" -> { - plugin.getLoggingAdapter().log(Level.INFO, "List of enabled console-executable commands:"); + plugin.log(Level.INFO, "List of enabled console-executable commands:"); plugin.getCommands() .stream().filter(command -> command instanceof ConsoleExecutable) - .forEach(command -> plugin.getLoggingAdapter().log(Level.INFO, + .forEach(command -> plugin.log(Level.INFO, command.command + (command.command.length() < 16 ? " ".repeat(16 - command.command.length()) : "") + " - " + command.getDescription())); } case "reload" -> { if (!plugin.reload()) { - plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to reload the plugin."); + plugin.log(Level.SEVERE, "Failed to reload the plugin."); return; } - plugin.getLoggingAdapter().log(Level.INFO, "Reloaded config & message files."); + plugin.log(Level.INFO, "Reloaded config & message files."); } case "update" -> plugin.getLatestVersionIfOutdated().thenAccept(newestVersion -> - newestVersion.ifPresentOrElse(newVersion -> plugin.getLoggingAdapter().log(Level.WARNING, + newestVersion.ifPresentOrElse(newVersion -> plugin.log(Level.WARNING, "An update is available for HuskHomes, v" + newVersion + " (Running v" + plugin.getVersion() + ")"), - () -> plugin.getLoggingAdapter().log(Level.INFO, + () -> plugin.log(Level.INFO, "HuskHomes is up to date" + " (Running v" + plugin.getVersion() + ")"))); } diff --git a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java index adff119d..797b312e 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java @@ -97,13 +97,13 @@ public class PublicHomeCommand extends Command implements TabProvider, ConsoleEx @Override public void onConsoleExecute(@NotNull String[] args) { if (args.length != 2) { - plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: publichome <[owner_name].[home_name]>"); + plugin.log(Level.WARNING, "Invalid syntax. Usage: publichome <[owner_name].[home_name]>"); return; } CompletableFuture.runAsync(() -> { final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); if (playerToTeleport == null) { - plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); + plugin.log(Level.WARNING, "Player not found: " + args[0]); return; } final AtomicReference matchedHome = new AtomicReference<>(null); @@ -119,11 +119,11 @@ public class PublicHomeCommand extends Command implements TabProvider, ConsoleEx final Home home = matchedHome.get(); if (home == null) { - plugin.getLoggingAdapter().log(Level.WARNING, "Could not find public home '" + args[1] + "'"); + plugin.log(Level.WARNING, "Could not find public home '" + args[1] + "'"); return; } - plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to " + plugin.log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to " + home.getOwner().getUsername() + "." + home.getMeta().getName()); Teleport.builder(plugin, playerToTeleport) .setTarget(home) diff --git a/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java b/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java index c143db85..4f431a8d 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java @@ -66,7 +66,7 @@ public class PublicHomeListCommand extends Command implements ConsoleExecutable final List homes = plugin.getDatabase().getPublicHomes().join(); StringJoiner rowJoiner = new StringJoiner("\t"); - plugin.getLoggingAdapter().log(Level.INFO, "List of " + homes.size() + " public homes:"); + plugin.log(Level.INFO, "List of " + homes.size() + " public homes:"); for (int i = 0; i < homes.size(); i++) { final String ownerUsername = homes.get(i).getOwner().getUsername(); final String homeName = homes.get(i).getMeta().getName(); @@ -74,11 +74,11 @@ public class PublicHomeListCommand extends Command implements ConsoleExecutable int spacingSize = (16 - ownerUsername.length()) + 17; rowJoiner.add(home.length() < spacingSize ? home + " ".repeat(spacingSize - home.length()) : home); if ((i + 1) % 3 == 0) { - plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); + plugin.log(Level.INFO, rowJoiner.toString()); rowJoiner = new StringJoiner("\t"); } } - plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); + plugin.log(Level.INFO, rowJoiner.toString()); }); } } diff --git a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java index 5fb4a13f..675b7f58 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -100,19 +100,19 @@ public class RtpCommand extends Command implements ConsoleExecutable { @Override public void onConsoleExecute(@NotNull String[] args) { if (args.length == 0) { - plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: rtp [player]"); + plugin.log(Level.WARNING, "Invalid syntax. Usage: rtp [player]"); return; } final Optional foundUser = plugin.findOnlinePlayer(args[0]); if (foundUser.isEmpty()) { - plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); + plugin.log(Level.WARNING, "Player not found: " + args[0]); return; } - plugin.getLoggingAdapter().log(Level.INFO, "Finding a random position for " + foundUser.get().getUsername() + "..."); + plugin.log(Level.INFO, "Finding a random position for " + foundUser.get().getUsername() + "..."); plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get().getPosition().getWorld(), ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> { if (position.isEmpty()) { - plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + foundUser.get().getUsername() + " to a random position; randomization timed out!"); + plugin.log(Level.WARNING, "Failed to teleport " + foundUser.get().getUsername() + " to a random position; randomization timed out!"); return; } Teleport.builder(plugin, foundUser.get()) @@ -120,9 +120,9 @@ public class RtpCommand extends Command implements ConsoleExecutable { .toTeleport() .thenAccept(teleport -> teleport.execute().thenAccept(result -> { if (result.successful()) { - plugin.getLoggingAdapter().log(Level.INFO, "Teleported " + foundUser.get().getUsername() + " to a random position."); + plugin.log(Level.INFO, "Teleported " + foundUser.get().getUsername() + " to a random position."); } else { - plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport" + foundUser.get().getUsername() + " to a random position."); + plugin.log(Level.WARNING, "Failed to teleport" + foundUser.get().getUsername() + " to a random position."); } })); }); diff --git a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java index d4584b4c..49806fe4 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java @@ -16,7 +16,7 @@ import java.util.Optional; public abstract class SavedPositionCommand extends Command { private final Class positionType; - private final List arguments; + protected final List arguments; protected SavedPositionCommand(@NotNull String name, @NotNull List aliases, @NotNull Class positionType, @NotNull List arguments, @NotNull HuskHomes plugin) { diff --git a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java index b803b598..c202f97b 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java @@ -159,12 +159,12 @@ public class TpCommand extends Command implements TabProvider, ConsoleExecutable @Override public void onConsoleExecute(@NotNull String[] args) { if (args.length < 2 || args.length > 6) { - plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: tp "); + plugin.log(Level.WARNING, "Invalid syntax. Usage: tp "); return; } final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); if (playerToTeleport == null) { - plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); + plugin.log(Level.WARNING, "Player not found: " + args[0]); return; } final TeleportTarget teleportTarget; @@ -180,7 +180,7 @@ public class TpCommand extends Command implements TabProvider, ConsoleExecutable args.length >= 5 ? new World(args[4], UUID.randomUUID()) : plugin.getWorlds().get(0), args.length == 6 ? new Server(args[5]) : plugin.getServerName())); } catch (NumberFormatException e) { - plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: tp [world] [server]"); + plugin.log(Level.WARNING, "Invalid syntax. Usage: tp [world] [server]"); return; } } @@ -195,9 +195,9 @@ public class TpCommand extends Command implements TabProvider, ConsoleExecutable } builder.toTeleport().thenAccept(teleport -> teleport.execute().thenAccept(result -> { if (result.successful()) { - plugin.getLoggingAdapter().log(Level.INFO, "Successfully teleported " + playerToTeleport.getUsername()); + plugin.log(Level.INFO, "Successfully teleported " + playerToTeleport.getUsername()); } else { - plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + playerToTeleport.getUsername() + " to " + teleportTarget); + plugin.log(Level.WARNING, "Failed to teleport " + playerToTeleport.getUsername() + " to " + teleportTarget); } })); } diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java index 504c699d..0e99833a 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java @@ -74,23 +74,23 @@ public class WarpCommand extends Command implements TabProvider, ConsoleExecutab @Override public void onConsoleExecute(@NotNull String[] args) { if (args.length != 2) { - plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: warp "); + plugin.log(Level.WARNING, "Invalid syntax. Usage: warp "); return; } final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); if (playerToTeleport == null) { - plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); + plugin.log(Level.WARNING, "Player not found: " + args[0]); return; } plugin.getDatabase().getWarp(args[1]).thenAccept(optionalWarp -> { if (optionalWarp.isEmpty()) { - plugin.getLoggingAdapter().log(Level.WARNING, "Could not find warp '" + args[1] + "'"); + plugin.log(Level.WARNING, "Could not find warp '" + args[1] + "'"); return; } final Warp warp = optionalWarp.get(); - plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to " + warp.getMeta().getName()); + plugin.log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to " + warp.getMeta().getName()); Teleport.builder(plugin, playerToTeleport) .setTarget(warp) .toTimedTeleport() diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java index bca0fecd..c7708ef1 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java @@ -64,18 +64,18 @@ public class WarpListCommand extends Command implements ConsoleExecutable { @Override public void onConsoleExecute(@NotNull String[] args) { plugin.getDatabase().getWarps().thenAccept(warps -> { - plugin.getLoggingAdapter().log(Level.INFO, "List of " + warps.size() + " warps:"); + plugin.log(Level.INFO, "List of " + warps.size() + " warps:"); StringJoiner rowJoiner = new StringJoiner("\t"); for (int i = 0; i < warps.size(); i++) { final String warp = warps.get(i).meta.name; rowJoiner.add(warp.length() < 16 ? warp + " ".repeat(16 - warp.length()) : warp); if ((i + 1) % 3 == 0) { - plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); + plugin.log(Level.INFO, rowJoiner.toString()); rowJoiner = new StringJoiner("\t"); } } - plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); + plugin.log(Level.INFO, rowJoiner.toString()); }); } } diff --git a/common/src/main/java/net/william278/huskhomes/config/Settings.java b/common/src/main/java/net/william278/huskhomes/config/Settings.java index aeb6af8e..4792ecae 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Settings.java +++ b/common/src/main/java/net/william278/huskhomes/config/Settings.java @@ -35,10 +35,6 @@ public class Settings { @YamlKey("check_for_updates") private boolean checkForUpdates = true; - @YamlKey("debug_logging") - private boolean debugLogging = false; - - // Database settings @YamlComment("Database connection settings") @YamlKey("database.type") @@ -278,10 +274,6 @@ public class Settings { return checkForUpdates; } - public boolean doDebugLogging() { - return debugLogging; - } - public Database.DatabaseType getDatabaseType() { return databaseType; } diff --git a/common/src/main/java/net/william278/huskhomes/database/Database.java b/common/src/main/java/net/william278/huskhomes/database/Database.java index fdebe344..6e1eaead 100644 --- a/common/src/main/java/net/william278/huskhomes/database/Database.java +++ b/common/src/main/java/net/william278/huskhomes/database/Database.java @@ -6,7 +6,6 @@ import net.william278.huskhomes.user.User; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.position.*; import net.william278.huskhomes.teleport.Teleport; -import net.william278.huskhomes.util.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -102,19 +101,6 @@ public abstract class Database { */ protected final HuskHomes plugin; - /** - * Logger instance used for database error logging - */ - private final Logger logger; - - /** - * Returns the {@link Logger} used to log database errors - * - * @return the {@link Logger} instance - */ - protected Logger getLogger() { - return logger; - } /** * Loads SQL table creation schema statements from a resource file as a string array @@ -159,7 +145,6 @@ public abstract class Database { this.homesTableName = implementor.getSettings().getTableName(TableName.HOME_DATA); this.warpsTableName = implementor.getSettings().getTableName(TableName.WARP_DATA); this.teleportsTableName = implementor.getSettings().getTableName(TableName.TELEPORT_DATA); - this.logger = implementor.getLoggingAdapter(); } /** diff --git a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java index bb7d583a..faaa6d98 100644 --- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -110,10 +110,10 @@ public class MySqlDatabase extends Database { } return true; } catch (SQLException | IOException e) { - getLogger().log(Level.SEVERE, "An error occurred creating tables on the MySQL database: ", e); + plugin.log(Level.SEVERE, "An error occurred creating tables on the MySQL database: ", e); } } catch (Exception e) { - getLogger().log(Level.SEVERE, "An unhandled exception occurred during database setup!", e); + plugin.log(Level.SEVERE, "An unhandled exception occurred during database setup!", e); } return false; } @@ -132,7 +132,7 @@ public class MySqlDatabase extends Database { statement.executeBatch(); } } catch (IOException | SQLException e) { - getLogger().log(Level.SEVERE, "An error occurred running a script on the MySQL database: ", e); + plugin.log(Level.SEVERE, "An error occurred running a script on the MySQL database: ", e); throw new RuntimeException(e); } } @@ -254,9 +254,9 @@ public class MySqlDatabase extends Database { statement.setString(2, existingUserData.getUserUuid().toString()); statement.executeUpdate(); } - getLogger().log(Level.INFO, "Updated " + onlineUser.getUsername() + "'s name in the database (" + existingUserData.getUsername() + " -> " + onlineUser.getUsername() + ")"); + plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() + "'s name in the database (" + existingUserData.getUsername() + " -> " + onlineUser.getUsername() + ")"); } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e); + plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e); } } }, @@ -272,7 +272,7 @@ public class MySqlDatabase extends Database { statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e); + plugin.log(Level.SEVERE, "Failed to insert a player into the database", e); } }); } @@ -297,7 +297,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e); + plugin.log(Level.SEVERE, "Failed to fetch a player by name from the database", e); } return Optional.empty(); } @@ -323,7 +323,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); + plugin.log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); } return Optional.empty(); } @@ -363,7 +363,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername()); + plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername()); } return userHomes; } @@ -397,7 +397,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for warp data."); + plugin.log(Level.SEVERE, "Failed to query the database for warp data."); } return warps; } @@ -436,7 +436,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for public home data"); + plugin.log(Level.SEVERE, "Failed to query the database for public home data"); } return userHomes; } @@ -476,7 +476,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a player's home", e); + plugin.log(Level.SEVERE, "Failed to query a player's home", e); } return Optional.empty(); } @@ -514,7 +514,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a player's home by uuid", e); + plugin.log(Level.SEVERE, "Failed to query a player's home by uuid", e); } return Optional.empty(); } @@ -548,7 +548,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a server warp", e); + plugin.log(Level.SEVERE, "Failed to query a server warp", e); } return Optional.empty(); } @@ -582,7 +582,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a server warp", e); + plugin.log(Level.SEVERE, "Failed to query a server warp", e); } return Optional.empty(); } @@ -616,7 +616,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e); } return Optional.empty(); } @@ -636,7 +636,7 @@ public class MySqlDatabase extends Database { statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername() + " on the database", e); + plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername() + " on the database", e); } } @@ -668,7 +668,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e); } } @@ -695,7 +695,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e); } return Optional.empty(); } @@ -727,7 +727,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e); } } @@ -754,7 +754,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e); } return Optional.empty(); } @@ -785,7 +785,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e); } } @@ -812,7 +812,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e); } return Optional.empty(); } @@ -859,7 +859,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e); } } @@ -889,7 +889,7 @@ public class MySqlDatabase extends Database { statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, + plugin.log(Level.SEVERE, "Failed to update a home in the database for " + home.getOwner().getUsername(), e); } }, () -> { @@ -905,7 +905,7 @@ public class MySqlDatabase extends Database { statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, + plugin.log(Level.SEVERE, "Failed to set a home to the database for " + home.getOwner().getUsername(), e); } }); @@ -926,7 +926,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to update a warp in the database", e); + plugin.log(Level.SEVERE, "Failed to update a warp in the database", e); } }, () -> { try (Connection connection = getConnection()) { @@ -939,7 +939,7 @@ public class MySqlDatabase extends Database { statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e); + plugin.log(Level.SEVERE, "Failed to add a warp to the database", e); } }); } @@ -963,7 +963,7 @@ public class MySqlDatabase extends Database { statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e); + plugin.log(Level.SEVERE, "Failed to delete a home from the database", e); } } @@ -986,7 +986,7 @@ public class MySqlDatabase extends Database { return statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e); + plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e); } return 0; } @@ -1010,7 +1010,7 @@ public class MySqlDatabase extends Database { statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e); + plugin.log(Level.SEVERE, "Failed to delete a warp from the database", e); } } @@ -1031,7 +1031,7 @@ public class MySqlDatabase extends Database { return statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete all warps from the database", e); + plugin.log(Level.SEVERE, "Failed to delete all warps from the database", e); } return 0; } diff --git a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java index 799cf515..70c2ad0f 100644 --- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -58,7 +58,7 @@ public class SqLiteDatabase extends Database { try { // Ensure that the database file exists if (databaseFile.createNewFile()) { - getLogger().log(Level.INFO, "Created the SQLite database file"); + plugin.log(Level.INFO, "Created the SQLite database file"); } // Specify use of the JDBC SQLite driver @@ -73,11 +73,11 @@ public class SqLiteDatabase extends Database { // Establish the connection connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath(), config.toProperties()); } catch (IOException e) { - getLogger().log(Level.SEVERE, "An exception occurred creating the database file", e); + plugin.log(Level.SEVERE, "An exception occurred creating the database file", e); } catch (SQLException e) { - getLogger().log(Level.SEVERE, "An SQL exception occurred initializing the SQLite database", e); + plugin.log(Level.SEVERE, "An SQL exception occurred initializing the SQLite database", e); } catch (ClassNotFoundException e) { - getLogger().log(Level.SEVERE, "Failed to load the necessary SQLite driver", e); + plugin.log(Level.SEVERE, "Failed to load the necessary SQLite driver", e); } } @@ -98,10 +98,10 @@ public class SqLiteDatabase extends Database { } return true; } catch (SQLException | IOException e) { - getLogger().log(Level.SEVERE, "An error occurred creating tables on the SQLite database: ", e); + plugin.log(Level.SEVERE, "An error occurred creating tables on the SQLite database: ", e); } } catch (Exception e) { - getLogger().log(Level.SEVERE, "An unhandled exception occurred during database setup!", e); + plugin.log(Level.SEVERE, "An unhandled exception occurred during database setup!", e); } return false; } @@ -124,7 +124,7 @@ public class SqLiteDatabase extends Database { } getConnection().setAutoCommit(autoCommit); } catch (IOException | SQLException e) { - getLogger().log(Level.SEVERE, "An exception occurred running script on the SQLite database", e); + plugin.log(Level.SEVERE, "An exception occurred running script on the SQLite database", e); throw new RuntimeException(e); } } @@ -250,9 +250,9 @@ public class SqLiteDatabase extends Database { statement.setString(2, existingUser.getUserUuid().toString()); statement.executeUpdate(); } - getLogger().log(Level.INFO, "Updated " + onlineUser.getUsername() + "'s name in the database (" + existingUser.getUsername() + " -> " + onlineUser.getUsername() + ")"); + plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() + "'s name in the database (" + existingUser.getUsername() + " -> " + onlineUser.getUsername() + ")"); } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e); + plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e); } } }, @@ -268,7 +268,7 @@ public class SqLiteDatabase extends Database { statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e); + plugin.log(Level.SEVERE, "Failed to insert a player into the database", e); } }); } @@ -293,7 +293,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e); + plugin.log(Level.SEVERE, "Failed to fetch a player by name from the database", e); } return Optional.empty(); } @@ -319,7 +319,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); + plugin.log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); } return Optional.empty(); } @@ -359,7 +359,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername()); + plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername()); } return userHomes; } @@ -393,7 +393,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for warp data."); + plugin.log(Level.SEVERE, "Failed to query the database for warp data."); } return warps; } @@ -432,7 +432,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the database for public home data"); + plugin.log(Level.SEVERE, "Failed to query the database for public home data"); } return userHomes; } @@ -472,7 +472,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a player's home", e); + plugin.log(Level.SEVERE, "Failed to query a player's home", e); } return Optional.empty(); } @@ -510,7 +510,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a player's home by uuid", e); + plugin.log(Level.SEVERE, "Failed to query a player's home by uuid", e); } return Optional.empty(); } @@ -544,7 +544,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a server warp", e); + plugin.log(Level.SEVERE, "Failed to query a server warp", e); } return Optional.empty(); } @@ -578,7 +578,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query a server warp", e); + plugin.log(Level.SEVERE, "Failed to query a server warp", e); } return Optional.empty(); } @@ -612,7 +612,7 @@ public class SqLiteDatabase extends Database { } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e); } return Optional.empty(); } @@ -630,7 +630,7 @@ public class SqLiteDatabase extends Database { statement.setString(4, savedUser.getUserUuid().toString()); statement.executeUpdate(); } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername() + " on the database", e); + plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername() + " on the database", e); } } @@ -649,7 +649,7 @@ public class SqLiteDatabase extends Database { deleteStatement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e); } // Set the user's teleport into the database (if it's not null) @@ -664,7 +664,7 @@ public class SqLiteDatabase extends Database { statement.executeUpdate(); } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the current teleport of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the current teleport of " + user.getUsername(), e); } } } @@ -690,7 +690,7 @@ public class SqLiteDatabase extends Database { resultSet.getString("server_name"))); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e); } return Optional.empty(); } @@ -721,7 +721,7 @@ public class SqLiteDatabase extends Database { } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e); } } @@ -748,7 +748,7 @@ public class SqLiteDatabase extends Database { } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e); } return Optional.empty(); } @@ -777,7 +777,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e); } } @@ -802,7 +802,7 @@ public class SqLiteDatabase extends Database { resultSet.getString("server_name"))); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e); } return Optional.empty(); } @@ -848,7 +848,7 @@ public class SqLiteDatabase extends Database { } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e); } } @@ -878,7 +878,7 @@ public class SqLiteDatabase extends Database { statement.executeUpdate(); } } catch (SQLException e) { - getLogger().log(Level.SEVERE, + plugin.log(Level.SEVERE, "Failed to update a home in the database for " + home.getOwner().getUsername(), e); } }, () -> { @@ -893,7 +893,7 @@ public class SqLiteDatabase extends Database { statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); - getLogger().log(Level.SEVERE, + plugin.log(Level.SEVERE, "Failed to set a home to the database for " + home.getOwner().getUsername(), e); } }); @@ -915,7 +915,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to update a warp in the database", e); + plugin.log(Level.SEVERE, "Failed to update a warp in the database", e); } }, () -> { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" @@ -926,7 +926,7 @@ public class SqLiteDatabase extends Database { statement.executeUpdate(); } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e); + plugin.log(Level.SEVERE, "Failed to add a warp to the database", e); } }); } @@ -949,7 +949,7 @@ public class SqLiteDatabase extends Database { statement.executeUpdate(); } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e); + plugin.log(Level.SEVERE, "Failed to delete a home from the database", e); } } @@ -970,7 +970,7 @@ public class SqLiteDatabase extends Database { statement.setString(1, user.getUuid().toString()); return statement.executeUpdate(); } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e); + plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e); } return 0; } @@ -991,7 +991,7 @@ public class SqLiteDatabase extends Database { statement.setString(1, uuid.toString()); statement.executeUpdate(); } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e); + plugin.log(Level.SEVERE, "Failed to delete a warp from the database", e); } } @@ -1009,7 +1009,7 @@ public class SqLiteDatabase extends Database { );"""))) { return statement.executeUpdate(); } catch (SQLException e) { - getLogger().log(Level.SEVERE, "Failed to delete all warps from the database", e); + plugin.log(Level.SEVERE, "Failed to delete all warps from the database", e); } return 0; } @@ -1023,7 +1023,7 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - getLogger().log(Level.WARNING, "Failed to properly close the SQLite connection"); + plugin.log(Level.WARNING, "Failed to properly close the SQLite connection"); } } diff --git a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java index 63be1aa9..075463da 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java @@ -58,7 +58,7 @@ public class BlueMapHook extends MapHook { ImageIO.read(Objects.requireNonNull(plugin.getResource("markers/50x/" + WARP_MARKER_IMAGE_NAME + ".png"))), "huskhomes/" + WARP_MARKER_IMAGE_NAME + ".png"); } catch (IOException e) { - plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to create warp marker image", e); + plugin.log(Level.SEVERE, "Failed to create warp marker image", e); } initializedFuture.complete(null); diff --git a/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java b/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java index ab63d9ec..b3945cf0 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java @@ -3,7 +3,6 @@ package net.william278.huskhomes.hook; import com.djrapitops.plan.capability.CapabilityService; import com.djrapitops.plan.extension.ExtensionService; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.database.Database; import net.william278.huskhomes.util.Logger; import org.jetbrains.annotations.NotNull; @@ -14,13 +13,11 @@ import java.util.logging.Level; */ public class PlanHook extends PluginHook { - private final Database database; - private final Logger logger; + private final HuskHomes plugin; - public PlanHook(@NotNull HuskHomes implementor) { - super(implementor, "Plan"); - this.database = implementor.getDatabase(); - this.logger = implementor.getLoggingAdapter(); + public PlanHook(@NotNull HuskHomes plugin) { + super(plugin, "Plan"); + this.plugin = plugin; } @Override @@ -41,12 +38,12 @@ public class PlanHook extends PluginHook { private void registerDataExtension() { try { - ExtensionService.getInstance().register(new PlanDataExtension(database, plugin.getSettings().isCrossServer())); + ExtensionService.getInstance().register(new PlanDataExtension(plugin.getDatabase(), plugin.getSettings().isCrossServer())); } catch (IllegalStateException planIsNotEnabled) { - logger.log(Level.SEVERE, "Plan extension hook failed to register. Plan is not enabled.", planIsNotEnabled); + plugin.log(Level.SEVERE, "Plan extension hook failed to register. Plan is not enabled.", planIsNotEnabled); // Plan is not enabled, handle exception } catch (IllegalArgumentException dataExtensionImplementationIsInvalid) { - logger.log(Level.SEVERE, "Plan extension hook failed to register. Data hook implementation is invalid.", dataExtensionImplementationIsInvalid); + plugin.log(Level.SEVERE, "Plan extension hook failed to register. Data hook implementation is invalid.", dataExtensionImplementationIsInvalid); // The DataExtension implementation has an implementation error, handle exception } } diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java index 470dfaad..8b45b14b 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java @@ -183,7 +183,7 @@ public class EventListener { * Handle when the plugin is disabling (server is shutting down) */ public final void handlePluginDisable() { - plugin.getLoggingAdapter().log(Level.INFO, "Successfully disabled HuskHomes v" + plugin.getVersion()); + plugin.log(Level.INFO, "Successfully disabled HuskHomes v" + plugin.getVersion()); } } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java index 792b4dfd..0e0e4c95 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java @@ -1,6 +1,9 @@ package net.william278.huskhomes.manager; import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.hook.EconomyHook; +import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.util.ValidationException; import net.william278.huskhomes.user.User; import net.william278.huskhomes.position.Home; @@ -17,31 +20,52 @@ public class HomesManager { this.plugin = plugin; } - public void createHome(@NotNull User owner, @NotNull String name, @NotNull Position position, boolean overwrite) throws ValidationException { + public void createHome(@NotNull User owner, @NotNull String name, @NotNull Position position, + boolean overwrite, boolean buyAdditionalSlots) throws ValidationException { final Optional existingHome = plugin.getDatabase().getHome(owner, name); if (existingHome.isPresent() && !overwrite) { throw new ValidationException(ValidationException.Type.NAME_TAKEN); } - if (!plugin.getValidator().isValidName(name)) { throw new ValidationException(ValidationException.Type.NAME_INVALID); } + // Validate against user max homes + final int homeCount = plugin.getDatabase().getHomes(owner).size(); + int maxHomes = plugin.getSettings().getMaxHomes(); + if (owner instanceof OnlineUser online) { + maxHomes = online.getMaxHomes(maxHomes, plugin.getSettings().doStackPermissionLimits()); + } + if (homeCount >= maxHomes) { + throw new ValidationException(ValidationException.Type.REACHED_MAX_HOMES); + } + + // Validate against user home slots + final SavedUser savedOwner = plugin.getDatabase().getUserData(owner.getUuid()) + .orElseThrow(() -> new IllegalStateException("User data not found for " + owner.getUuid())); + if (plugin.getSettings().doEconomy() && homeCount >= savedOwner.getHomeSlots()) { + if (!buyAdditionalSlots || plugin.getEconomyHook().isEmpty() || !(owner instanceof OnlineUser online)) { + throw new ValidationException(ValidationException.Type.NOT_ENOUGH_HOME_SLOTS); + } + + plugin.performEconomyTransaction(online, EconomyHook.Action.ADDITIONAL_HOME_SLOT); + savedOwner.setHomeSlots(savedOwner.getHomeSlots() + 1); + plugin.getDatabase().updateUserData(savedOwner); + } + final Home home = existingHome .map(existing -> { - existing.setX(position.getX()); - existing.setY(position.getY()); - existing.setZ(position.getZ()); - existing.setWorld(position.getWorld()); - existing.setServer(position.getServer()); - existing.setYaw(position.getYaw()); - existing.setPitch(position.getPitch()); + existing.update(position); return existing; }) .orElse(new Home(position, new PositionMeta(name, ""), owner)); plugin.getDatabase().saveHome(home); } + public void createHome(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) throws ValidationException { + createHome(owner, name, position, plugin.getSettings().doOverwriteExistingHomesWarps(), true); + } + public void deleteHome(@NotNull User owner, @NotNull String name) throws ValidationException { final Optional home = plugin.getDatabase().getHome(owner, name); if (home.isEmpty()) { @@ -55,7 +79,14 @@ public class HomesManager { } public void relocateHome(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException { - createHome(owner, name, position, true); + final Optional optionalHome = plugin.getDatabase().getHome(owner, name); + if (optionalHome.isEmpty()) { + throw new ValidationException(ValidationException.Type.NOT_FOUND); + } + + final Home home = optionalHome.get(); + home.update(position); + plugin.getDatabase().saveHome(home); } public void renameHome(@NotNull User owner, @NotNull String name, @NotNull String newName) throws ValidationException { @@ -95,6 +126,21 @@ public class HomesManager { } final Home home = optionalHome.get(); + if (isPublic == home.isPublic()) { + return; + } + + if (isPublic && owner instanceof OnlineUser online) { + final int publicHomes = plugin.getDatabase().getHomes(owner).stream() + .filter(Home::isPublic) + .toList().size(); + final int publicSlots = online.getMaxPublicHomes(plugin.getSettings().getMaxPublicHomes(), + plugin.getSettings().doStackPermissionLimits()); + if (publicHomes >= publicSlots) { + throw new ValidationException(ValidationException.Type.REACHED_MAX_PUBLIC_HOMES); + } + } + home.setPublic(isPublic); plugin.getDatabase().saveHome(home); } diff --git a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java index 3eb53065..6742caa8 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java @@ -11,6 +11,7 @@ import java.util.Optional; public class WarpsManager { private final HuskHomes plugin; + protected WarpsManager(@NotNull HuskHomes plugin) { this.plugin = plugin; } @@ -53,7 +54,14 @@ public class WarpsManager { } public void relocateWarp(@NotNull String name, @NotNull Position position) { - createWarp(name, position, true); + final Optional optionalWarp = plugin.getDatabase().getWarp(name); + if (optionalWarp.isEmpty()) { + throw new ValidationException(ValidationException.Type.NOT_FOUND); + } + + final Warp warp = optionalWarp.get(); + warp.update(position); + plugin.getDatabase().saveWarp(warp); } public void renameHome(@NotNull String name, @NotNull String newName) throws ValidationException { diff --git a/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java b/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java index d1babbba..8a3ae0cf 100644 --- a/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java +++ b/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java @@ -57,7 +57,7 @@ public class PluginMessageBroker extends Broker { try (final DataInputStream messageReader = new DataInputStream(new ByteArrayInputStream(messageBody))) { super.handle(user, plugin.getGson().fromJson(messageReader.readUTF(), Message.class)); } catch (IOException e) { - plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to fully read plugin message", e); + plugin.log(Level.SEVERE, "Failed to fully read plugin message", e); } } @@ -77,7 +77,7 @@ public class PluginMessageBroker extends Broker { messageWriter.write(messageByteStream.toByteArray()); } } catch (IOException e) { - plugin.getLoggingAdapter().log(Level.SEVERE, "Exception dispatching plugin message", e); + plugin.log(Level.SEVERE, "Exception dispatching plugin message", e); return; } diff --git a/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java b/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java index 735f4be6..b352ff6b 100644 --- a/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java +++ b/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java @@ -34,7 +34,7 @@ public class RedisBroker extends PluginMessageBroker { new Thread(getSubscriber(), plugin.getKey("redis_subscriber").toString()).start(); - plugin.getLoggingAdapter().log(Level.INFO, "Initialized Redis connection pool"); + plugin.log(Level.INFO, "Initialized Redis connection pool"); } @NotNull diff --git a/common/src/main/java/net/william278/huskhomes/position/Location.java b/common/src/main/java/net/william278/huskhomes/position/Location.java index ed6362f2..3837a190 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Location.java +++ b/common/src/main/java/net/william278/huskhomes/position/Location.java @@ -36,6 +36,20 @@ public class Location { public Location() { } + /** + * Update the position to match that of another position + * + * @param position The position to update to + */ + public void update(@NotNull Position position) { + this.setX(position.getX()); + this.setY(position.getY()); + this.setZ(position.getZ()); + this.setYaw(position.getYaw()); + this.setPitch(position.getPitch()); + this.setWorld(position.getWorld()); + } + /** * The double-precision defined x coordinate of the location */ diff --git a/common/src/main/java/net/william278/huskhomes/position/Position.java b/common/src/main/java/net/william278/huskhomes/position/Position.java index ff965e21..c8804e64 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Position.java +++ b/common/src/main/java/net/william278/huskhomes/position/Position.java @@ -28,18 +28,9 @@ public class Position extends Location implements Target { private Position() { } - /** - * Update the position to match that of another position - * - * @param newPosition The position to update to - */ + @Override public void update(@NotNull Position newPosition) { - this.setX(newPosition.getX()); - this.setY(newPosition.getY()); - this.setZ(newPosition.getZ()); - this.setYaw(newPosition.getYaw()); - this.setPitch(newPosition.getPitch()); - this.setWorld(newPosition.getWorld()); + super.update(newPosition); this.setServer(newPosition.getServer()); } diff --git a/common/src/main/java/net/william278/huskhomes/user/SavedUser.java b/common/src/main/java/net/william278/huskhomes/user/SavedUser.java index 976712c5..d02d8b78 100644 --- a/common/src/main/java/net/william278/huskhomes/user/SavedUser.java +++ b/common/src/main/java/net/william278/huskhomes/user/SavedUser.java @@ -8,7 +8,25 @@ import java.util.UUID; /** * Represents data about a player on the server */ -public record SavedUser(@NotNull User user, int homeSlots, boolean ignoringTeleports, @NotNull Instant rtpCooldown) { +public class SavedUser { + + private final User user; + + private int homeSlots; + private boolean ignoringTeleports; + private Instant rtpCooldown; + + public SavedUser(@NotNull User user, int homeSlots, boolean ignoringTeleports, @NotNull Instant rtpCooldown) { + this.user = user; + this.homeSlots = homeSlots; + this.ignoringTeleports = ignoringTeleports; + this.rtpCooldown = rtpCooldown; + } + + @NotNull + public User getUser() { + return user; + } @NotNull public UUID getUserUuid() { @@ -20,4 +38,29 @@ public record SavedUser(@NotNull User user, int homeSlots, boolean ignoringTelep return user.getUsername(); } + public int getHomeSlots() { + return homeSlots; + } + + public void setHomeSlots(int homeSlots) { + this.homeSlots = homeSlots; + } + + public boolean isIgnoringTeleports() { + return ignoringTeleports; + } + + public void setIgnoringTeleports(boolean ignoringTeleports) { + this.ignoringTeleports = ignoringTeleports; + } + + @NotNull + public Instant getRtpCooldown() { + return rtpCooldown; + } + + public void setRtpCooldown(@NotNull Instant rtpCooldown) { + this.rtpCooldown = rtpCooldown; + } + } diff --git a/common/src/main/java/net/william278/huskhomes/util/Logger.java b/common/src/main/java/net/william278/huskhomes/util/Logger.java deleted file mode 100644 index 7f3aeb78..00000000 --- a/common/src/main/java/net/william278/huskhomes/util/Logger.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.william278.huskhomes.util; - -import org.jetbrains.annotations.NotNull; - -import java.util.logging.Level; - -/** - * An abstract, cross-platform representation of a logger - */ -public abstract class Logger { - - private boolean debug; - - public abstract void log(@NotNull Level level, @NotNull String message, @NotNull Throwable e); - - public abstract void log(@NotNull Level level, @NotNull String message); - - public abstract void info(@NotNull String message); - - public abstract void severe(@NotNull String message); - - public final void debug(@NotNull String message) { - if (debug) { - log(Level.INFO, "[DEBUG] " + message); - } - } - - public abstract void config(@NotNull String message); - - public final void showDebugLogs(boolean debug) { - this.debug = debug; - } - -} diff --git a/common/src/main/java/net/william278/huskhomes/util/ValidationException.java b/common/src/main/java/net/william278/huskhomes/util/ValidationException.java index 611ee796..42c1bc2b 100644 --- a/common/src/main/java/net/william278/huskhomes/util/ValidationException.java +++ b/common/src/main/java/net/william278/huskhomes/util/ValidationException.java @@ -1,18 +1,45 @@ package net.william278.huskhomes.util; +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.user.CommandUser; import org.jetbrains.annotations.NotNull; public class ValidationException extends IllegalArgumentException { + private final Type error; + public ValidationException(@NotNull ValidationException.Type error) { super("Error validating position: " + error.name()); + this.error = error; + } + + public void dispatchHomeError(@NotNull CommandUser viewer, boolean other, @NotNull HuskHomes plugin, @NotNull String... args) { + plugin.getLocales() + .getLocale(switch (error) { + case NOT_FOUND -> other ? "error_home_invalid_other" : "error_home_invalid"; + case NAME_TAKEN -> "error_home_name_taken"; + case NAME_INVALID -> "error_home_name_characters"; + case DESCRIPTION_INVALID -> "error_home_description_characters"; + }, args) + .ifPresent(viewer::sendMessage); + } + + public void dispatchWarpError(@NotNull CommandUser viewer, @NotNull HuskHomes plugin) { + plugin.getLocales() + .getLocale(switch (error) { + case NOT_FOUND -> "error_warp_invalid"; + case NAME_TAKEN -> "error_warp_name_taken"; + case NAME_INVALID -> "error_warp_name_characters"; + case DESCRIPTION_INVALID -> "error_warp_description_characters"; + }) + .ifPresent(viewer::sendMessage); } public enum Type { NOT_FOUND, NAME_TAKEN, NAME_INVALID, - DESCRIPTION_INVALID + REACHED_MAX_HOMES, NOT_ENOUGH_HOME_SLOTS, REACHED_MAX_PUBLIC_HOMES, DESCRIPTION_INVALID } }