More work on commands

This commit is contained in:
William committed 2023-03-12 12:49:46 +00:00
1 parent 0bd63a9f01
commit a72109667a
33 files changed
+445 -382

No files matched your search

@@ -65,7 +65,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
private static final int METRICS_ID = 8430; private static final int METRICS_ID = 8430;
private Settings settings; private Settings settings;
private Locales locales; private Locales locales;
private BukkitLogger logger;
private Database database; private Database database;
private Cache cache; private Cache cache;
private Validator validator; private Validator validator;
@@ -103,24 +102,20 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
// Initialize HuskHomes // Initialize HuskHomes
final AtomicBoolean initialized = new AtomicBoolean(true); final AtomicBoolean initialized = new AtomicBoolean(true);
try { try {
// Set the logging and resource reading adapter
this.logger = new BukkitLogger(getLogger());
// Create adventure audience // Create adventure audience
this.audiences = BukkitAudiences.create(this); this.audiences = BukkitAudiences.create(this);
// Load settings and locales // Load settings and locales
getLoggingAdapter().log(Level.INFO, "Loading plugin configuration settings & locales..."); log(Level.INFO, "Loading plugin configuration settings & locales...");
initialized.set(reload()); initialized.set(reload());
if (initialized.get()) { if (initialized.get()) {
logger.showDebugLogs(settings.doDebugLogging()); log(Level.INFO, "Successfully loaded plugin configuration settings & locales");
getLoggingAdapter().log(Level.INFO, "Successfully loaded plugin configuration settings & locales");
} else { } else {
throw new IllegalStateException("Failed to load plugin configuration settings and/or locales"); throw new IllegalStateException("Failed to load plugin configuration settings and/or locales");
} }
// Initialize the database // 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(); final Database.DatabaseType databaseType = settings.getDatabaseType();
this.database = switch (databaseType == null ? Database.DatabaseType.MYSQL : databaseType) { this.database = switch (databaseType == null ? Database.DatabaseType.MYSQL : databaseType) {
case MYSQL -> new MySqlDatabase(this); case MYSQL -> new MySqlDatabase(this);
@@ -128,20 +123,20 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
}; };
initialized.set(this.database.initialize()); initialized.set(this.database.initialize());
if (initialized.get()) { 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 { } else {
throw new IllegalStateException("Failed to establish a connection to the database. " + "Please check the supplied database credentials in the config file"); 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 // Initialize the network messenger if proxy mode is enabled
if (getSettings().isCrossServer()) { if (getSettings().isCrossServer()) {
getLoggingAdapter().log(Level.INFO, "Initializing the network messenger..."); log(Level.INFO, "Initializing the network messenger...");
broker = switch (settings.getBrokerType()) { broker = switch (settings.getBrokerType()) {
case PLUGIN_MESSAGE -> new PluginMessageBroker(this); case PLUGIN_MESSAGE -> new PluginMessageBroker(this);
case REDIS -> new RedisBroker(this); case REDIS -> new RedisBroker(this);
}; };
broker.initialize(); broker.initialize();
getLoggingAdapter().log(Level.INFO, "Successfully initialized the network messenger."); log(Level.INFO, "Successfully initialized the network messenger.");
} }
// Prepare the validator // Prepare the validator
@@ -189,16 +184,16 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
if (pluginHooks.size() > 0) { if (pluginHooks.size() > 0) {
pluginHooks.forEach(PluginHook::initialize); 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 // Register events
getLoggingAdapter().log(Level.INFO, "Registering events..."); log(Level.INFO, "Registering events...");
this.eventListener = new BukkitEventListener(this); this.eventListener = new BukkitEventListener(this);
getLoggingAdapter().log(Level.INFO, "Successfully registered events listener"); log(Level.INFO, "Successfully registered events listener");
// Register permissions // 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) { Arrays.stream(Permission.values()).forEach(permission -> getServer().getPluginManager().addPermission(new org.bukkit.permissions.Permission(permission.node, switch (permission.defaultAccess) {
case EVERYONE -> PermissionDefault.TRUE; case EVERYONE -> PermissionDefault.TRUE;
case NOBODY -> PermissionDefault.FALSE; case NOBODY -> PermissionDefault.FALSE;
@@ -227,28 +222,28 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
this.registeredCommands.add(command); this.registeredCommands.add(command);
new BukkitCommand(command, this).register(pluginCommand); 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 // Hook into bStats metrics
registerMetrics(METRICS_ID); registerMetrics(METRICS_ID);
// Check for updates // Check for updates
if (settings.doCheckForUpdates()) { if (settings.doCheckForUpdates()) {
getLoggingAdapter().log(Level.INFO, "Checking for updates..."); 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() + ")"))); getLatestVersionIfOutdated().thenAccept(newestVersion -> newestVersion.ifPresent(newVersion -> log(Level.WARNING, "An update is available for HuskHomes, v" + newVersion + " (Currently running v" + getVersion() + ")")));
} }
} catch (IllegalStateException exception) { } catch (IllegalStateException exception) {
getLoggingAdapter().log(Level.SEVERE, exception.getMessage()); log(Level.SEVERE, exception.getMessage());
initialized.set(false); initialized.set(false);
} catch (Exception exception) { } 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); initialized.set(false);
} finally { } finally {
// Validate initialization // Validate initialization
if (initialized.get()) { if (initialized.get()) {
getLoggingAdapter().log(Level.INFO, "Successfully enabled HuskHomes v" + getVersion()); log(Level.INFO, "Successfully enabled HuskHomes v" + getVersion());
} else { } 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); getServer().getPluginManager().disablePlugin(this);
} }
} }
@@ -280,12 +275,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
return audiences; return audiences;
} }
@NotNull
@Override
public Logger getLoggingAdapter() {
return logger;
}
@Override @Override
@NotNull @NotNull
public ConsoleUser getConsole() { public ConsoleUser getConsole() {
@@ -372,7 +361,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
try { try {
Annotaml.create(new File(getDataFolder(), "spawn.yml"), newSpawn); Annotaml.create(new File(getDataFolder(), "spawn.yml"), newSpawn);
} catch (IOException e) { } 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 // Update the world spawn location, too
@@ -476,7 +465,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
return true; return true;
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { } 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; return false;
} }
@@ -502,7 +491,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
metrics.addCustomChart(new SimplePie("map_type", () -> getSettings().getMappingPlugin().displayName)); metrics.addCustomChart(new SimplePie("map_type", () -> getSettings().getMappingPlugin().displayName));
} }
} catch (Exception e) { } 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); 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 @Override
public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) { public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) {
if (broker != null && broker instanceof PluginMessageBroker pluginMessenger 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); pluginMessenger.onReceive(channel, BukkitUser.adapt(player), message);
} }
} }
@@ -28,9 +28,9 @@ public class BrigadierUtil {
try { try {
CommodoreProvider.getCommodore(plugin).register(pluginCommand, CommodoreProvider.getCommodore(plugin).register(pluginCommand,
CommodoreFileReader.INSTANCE.parse(commandCommodore), CommodoreFileReader.INSTANCE.parse(commandCommodore),
player -> player.hasPermission(command.permission)); player -> player.hasPermission(command.getPermission()));
} catch (IOException e) { } 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); + pluginCommand.getName(), e);
} }
} }
@@ -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);
}
}
@@ -21,7 +21,6 @@ import net.william278.huskhomes.user.ConsoleUser;
import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.*; import net.william278.huskhomes.position.*;
import net.william278.huskhomes.random.RandomTeleportEngine; import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.Permission; import net.william278.huskhomes.util.Permission;
import net.william278.huskhomes.util.TaskRunner; import net.william278.huskhomes.util.TaskRunner;
import net.william278.huskhomes.util.Validator; import net.william278.huskhomes.util.Validator;
@@ -35,6 +34,7 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
/** /**
* Represents a cross-platform instance of the plugin * Represents a cross-platform instance of the plugin
@@ -43,14 +43,6 @@ public interface HuskHomes extends TaskRunner {
int SPIGOT_RESOURCE_ID = 83767; int SPIGOT_RESOURCE_ID = 83767;
/**
* The platform plugin console logger
*
* @return the {@link Logger} implementation to use
*/
@NotNull
Logger getLoggingAdapter();
@NotNull @NotNull
ConsoleUser getConsole(); ConsoleUser getConsole();
@@ -367,6 +359,15 @@ public interface HuskHomes extends TaskRunner {
*/ */
void initializePluginChannels(); 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 * 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(); return Converters.registerOffsetDateTime(new GsonBuilder().excludeFieldsWithoutExposeAnnotation()).create();
} }
} }
@@ -8,7 +8,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
public class DelHomeCommand extends SavedPositionCommand<Home> implements TabProvider { public class DelHomeCommand extends SavedPositionCommand<Home> {
public DelHomeCommand(@NotNull HuskHomes implementor) { public DelHomeCommand(@NotNull HuskHomes implementor) {
super("delhome", List.of(), Home.class, List.of(), implementor); super("delhome", List.of(), Home.class, List.of(), implementor);
@@ -8,7 +8,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
public class DelWarpCommand extends SavedPositionCommand<Warp> implements TabProvider { public class DelWarpCommand extends SavedPositionCommand<Warp> {
public DelWarpCommand(@NotNull HuskHomes implementor) { public DelWarpCommand(@NotNull HuskHomes implementor) {
super("delwarp", List.of(), Warp.class, List.of(), implementor); super("delwarp", List.of(), Warp.class, List.of(), implementor);
@@ -4,72 +4,130 @@ import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.PositionMeta; 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.Permission;
import net.william278.huskhomes.util.ValidationException;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.format.DateTimeFormatter; 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.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class EditHomeCommand extends Command implements TabProvider { public class EditHomeCommand extends SavedPositionCommand<Home> {
private final String[] EDIT_HOME_COMPLETIONS = {"rename", "description", "relocate", "privacy"}; public EditHomeCommand(@NotNull HuskHomes plugin) {
super("edithome", List.of(), Home.class, List.of("rename", "description", "relocate", "privacy"), plugin);
public EditHomeCommand(@NotNull HuskHomes implementor) {
super("edithome", Permission.COMMAND_EDIT_HOME, implementor);
} }
@Override @Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { public void execute(@NotNull CommandUser executor, @NotNull Home home, @NotNull String[] args) {
if (args.length >= 1) { final boolean ownerEditing = home.getOwner().equals(executor);
final String homeName = args[0]; if (!ownerEditing && !executor.hasPermission(getOtherPermission())) {
final String editOperation = args.length >= 2 ? args[1] : null; plugin.getLocales().getLocale("error_no_permission")
final String editArgs = getEditArguments(args); .ifPresent(executor::sendMessage);
return;
}
RegexUtil.matchDisambiguatedHomeIdentifier(homeName).ifPresentOrElse( final Optional<String> operation = parseStringArg(args, 0);
homeIdentifier -> plugin.getDatabase().getUserDataByName(homeIdentifier.ownerName()) if (operation.isEmpty()) {
.thenAcceptAsync(optionalUserData -> optionalUserData.ifPresentOrElse(userData -> { getHomeEditorWindow(home, true, !ownerEditing,
if (!userData.getUserUuid().equals(onlineUser.getUuid())) { !ownerEditing || executor.hasPermission(Permission.COMMAND_HOME_OTHER.node),
if (!onlineUser.hasPermission(Permission.COMMAND_EDIT_HOME_OTHER.node)) { executor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node))
plugin.getLocales().getLocale("error_no_permission") .forEach(executor::sendMessage);
.ifPresent(onlineUser::sendMessage); return;
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);
});
}, if (!arguments.contains(operation.get().toLowerCase())) {
() -> 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 {
plugin.getLocales().getLocale("error_invalid_syntax", plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome <name> [" + String.join("|", EDIT_HOME_COMPLETIONS) + "] [args]") "/edithome " + home.getName() + " <" + String.join("|", arguments) + ">")
.ifPresent(onlineUser::sendMessage); .ifPresent(executor::sendMessage);
return;
}
switch (operation.get().toLowerCase()) {
case "rename" -> {
final Optional<String> newName = parseStringArg(args, 1);
if (newName.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome " + home.getName() + " rename <name>")
.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<String> newDescription = parseGreedyString(args, 1);
if (newDescription.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome " + home.getName() + " description <text>")
.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()); final boolean otherOwner = !editor.equals(home.getOwner());
if (editOperation == null) { 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; return;
} }
if (editArgs != null) { if (editArgs != null) {
@@ -163,24 +217,23 @@ public class EditHomeCommand extends Command implements TabProvider {
default -> plugin.getLocales().getLocale("error_home_name_characters"); default -> plugin.getLocales().getLocale("error_home_name_characters");
}).ifPresent(editor::sendMessage)); }).ifPresent(editor::sendMessage));
} }
case "relocate" -> case "relocate" -> plugin.getManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> {
plugin.getManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> { if (home.getOwner().equals(editor)) {
if (home.getOwner().equals(editor)) { editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location",
editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location", home.getMeta().getName()).orElse(new MineDown("")));
home.getMeta().getName()).orElse(new MineDown(""))); } else {
} else { editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location_other",
editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location_other", home.getOwner().getUsername(), home.getMeta().getName()).orElse(new MineDown("")));
home.getOwner().getUsername(), home.getMeta().getName()).orElse(new MineDown(""))); }
}
// Show the menu if the menu flag is set // Show the menu if the menu flag is set
if (showMenuFlag.get()) { if (showMenuFlag.get()) {
getHomeEditorWindow(home, false, otherOwner, getHomeEditorWindow(home, false, otherOwner,
!otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node), !otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node),
editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node))
.forEach(editor::sendMessage); .forEach(editor::sendMessage);
} }
}); });
case "privacy" -> { case "privacy" -> {
if (!editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) { if (!editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node)) {
plugin.getLocales().getLocale("error_no_permission") plugin.getLocales().getLocale("error_no_permission")
@@ -344,23 +397,4 @@ public class EditHomeCommand extends Command implements TabProvider {
}}; }};
} }
@Override
@NotNull
public final List<String> 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();
};
}
} }
@@ -85,13 +85,13 @@ public class HomeCommand extends Command implements TabProvider, ConsoleExecutab
@Override @Override
public void onConsoleExecute(@NotNull String[] args) { public void onConsoleExecute(@NotNull String[] args) {
if (args.length != 2) { if (args.length != 2) {
plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: home <player> <home>"); plugin.log(Level.WARNING, "Invalid syntax. Usage: home <player> <home>");
return; return;
} }
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null);
if (playerToTeleport == null) { if (playerToTeleport == null) {
plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); plugin.log(Level.WARNING, "Player not found: " + args[0]);
return; return;
} }
final AtomicReference<Home> matchedHome = new AtomicReference<>(null); final AtomicReference<Home> matchedHome = new AtomicReference<>(null);
@@ -105,11 +105,11 @@ public class HomeCommand extends Command implements TabProvider, ConsoleExecutab
final Home home = matchedHome.get(); final Home home = matchedHome.get();
if (home == null) { 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; return;
} }
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to " plugin.log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to "
+ home.getOwner().getUsername() + "." + home.getMeta().getName()); + home.getOwner().getUsername() + "." + home.getMeta().getName());
Teleport.builder(plugin, playerToTeleport) Teleport.builder(plugin, playerToTeleport)
.setTarget(home) .setTarget(home)
@@ -86,29 +86,29 @@ public class HomeListCommand extends Command implements ConsoleExecutable {
@Override @Override
public void onConsoleExecute(@NotNull String[] args) { public void onConsoleExecute(@NotNull String[] args) {
if (args.length != 1) { if (args.length != 1) {
plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: homelist <player>"); plugin.log(Level.WARNING, "Invalid syntax. Usage: homelist <player>");
return; return;
} }
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
final Optional<SavedUser> userData = plugin.getDatabase().getUserDataByName(args[0]).join(); final Optional<SavedUser> userData = plugin.getDatabase().getUserDataByName(args[0]).join();
if (userData.isEmpty()) { if (userData.isEmpty()) {
plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); plugin.log(Level.WARNING, "Player not found: " + args[0]);
return; return;
} }
final List<Home> homes = plugin.getDatabase().getHomes(userData.get().user()).join(); final List<Home> homes = plugin.getDatabase().getHomes(userData.get().user()).join();
StringJoiner rowJoiner = new StringJoiner("\t"); 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:"); + homes.size() + " homes:");
for (int i = 0; i < homes.size(); i++) { for (int i = 0; i < homes.size(); i++) {
final String home = homes.get(i).getMeta().getName(); final String home = homes.get(i).getMeta().getName();
rowJoiner.add(home.length() < 16 ? home + " ".repeat(16 - home.length()) : home); rowJoiner.add(home.length() < 16 ? home + " ".repeat(16 - home.length()) : home);
if ((i + 1) % 3 == 0) { if ((i + 1) % 3 == 0) {
plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); plugin.log(Level.INFO, rowJoiner.toString());
rowJoiner = new StringJoiner("\t"); rowJoiner = new StringJoiner("\t");
} }
} }
plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); plugin.log(Level.INFO, rowJoiner.toString());
}); });
} }
} }
@@ -116,33 +116,33 @@ public class HuskHomesCommand extends Command implements ConsoleExecutable, TabP
public void onConsoleExecute(@NotNull String[] args) { public void onConsoleExecute(@NotNull String[] args) {
if (args.length == 0) { if (args.length == 0) {
Arrays.stream(aboutMenu.toString().split("\n")).forEach(message -> Arrays.stream(aboutMenu.toString().split("\n")).forEach(message ->
plugin.getLoggingAdapter().log(Level.INFO, message)); plugin.log(Level.INFO, message));
return; return;
} }
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) {
case "about" -> Arrays.stream(aboutMenu.toString().split("\n")).forEach(message -> case "about" -> Arrays.stream(aboutMenu.toString().split("\n")).forEach(message ->
plugin.getLoggingAdapter().log(Level.INFO, message)); plugin.log(Level.INFO, message));
case "help" -> { 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() plugin.getCommands()
.stream().filter(command -> command instanceof ConsoleExecutable) .stream().filter(command -> command instanceof ConsoleExecutable)
.forEach(command -> plugin.getLoggingAdapter().log(Level.INFO, .forEach(command -> plugin.log(Level.INFO,
command.command + command.command +
(command.command.length() < 16 ? " ".repeat(16 - command.command.length()) : "") (command.command.length() < 16 ? " ".repeat(16 - command.command.length()) : "")
+ " - " + command.getDescription())); + " - " + command.getDescription()));
} }
case "reload" -> { case "reload" -> {
if (!plugin.reload()) { if (!plugin.reload()) {
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to reload the plugin."); plugin.log(Level.SEVERE, "Failed to reload the plugin.");
return; return;
} }
plugin.getLoggingAdapter().log(Level.INFO, "Reloaded config & message files."); plugin.log(Level.INFO, "Reloaded config & message files.");
} }
case "update" -> plugin.getLatestVersionIfOutdated().thenAccept(newestVersion -> 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 "An update is available for HuskHomes, v" + newVersion
+ " (Running v" + plugin.getVersion() + ")"), + " (Running v" + plugin.getVersion() + ")"),
() -> plugin.getLoggingAdapter().log(Level.INFO, () -> plugin.log(Level.INFO,
"HuskHomes is up to date" + "HuskHomes is up to date" +
" (Running v" + plugin.getVersion() + ")"))); " (Running v" + plugin.getVersion() + ")")));
} }
@@ -97,13 +97,13 @@ public class PublicHomeCommand extends Command implements TabProvider, ConsoleEx
@Override @Override
public void onConsoleExecute(@NotNull String[] args) { public void onConsoleExecute(@NotNull String[] args) {
if (args.length != 2) { if (args.length != 2) {
plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: publichome <player> <[owner_name].[home_name]>"); plugin.log(Level.WARNING, "Invalid syntax. Usage: publichome <player> <[owner_name].[home_name]>");
return; return;
} }
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null);
if (playerToTeleport == null) { if (playerToTeleport == null) {
plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); plugin.log(Level.WARNING, "Player not found: " + args[0]);
return; return;
} }
final AtomicReference<Home> matchedHome = new AtomicReference<>(null); final AtomicReference<Home> matchedHome = new AtomicReference<>(null);
@@ -119,11 +119,11 @@ public class PublicHomeCommand extends Command implements TabProvider, ConsoleEx
final Home home = matchedHome.get(); final Home home = matchedHome.get();
if (home == null) { 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; return;
} }
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to " plugin.log(Level.INFO, "Teleporting " + playerToTeleport.getUsername() + " to "
+ home.getOwner().getUsername() + "." + home.getMeta().getName()); + home.getOwner().getUsername() + "." + home.getMeta().getName());
Teleport.builder(plugin, playerToTeleport) Teleport.builder(plugin, playerToTeleport)
.setTarget(home) .setTarget(home)
@@ -66,7 +66,7 @@ public class PublicHomeListCommand extends Command implements ConsoleExecutable
final List<Home> homes = plugin.getDatabase().getPublicHomes().join(); final List<Home> homes = plugin.getDatabase().getPublicHomes().join();
StringJoiner rowJoiner = new StringJoiner("\t"); 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++) { for (int i = 0; i < homes.size(); i++) {
final String ownerUsername = homes.get(i).getOwner().getUsername(); final String ownerUsername = homes.get(i).getOwner().getUsername();
final String homeName = homes.get(i).getMeta().getName(); 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; int spacingSize = (16 - ownerUsername.length()) + 17;
rowJoiner.add(home.length() < spacingSize ? home + " ".repeat(spacingSize - home.length()) : home); rowJoiner.add(home.length() < spacingSize ? home + " ".repeat(spacingSize - home.length()) : home);
if ((i + 1) % 3 == 0) { if ((i + 1) % 3 == 0) {
plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); plugin.log(Level.INFO, rowJoiner.toString());
rowJoiner = new StringJoiner("\t"); rowJoiner = new StringJoiner("\t");
} }
} }
plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); plugin.log(Level.INFO, rowJoiner.toString());
}); });
} }
} }
@@ -100,19 +100,19 @@ public class RtpCommand extends Command implements ConsoleExecutable {
@Override @Override
public void onConsoleExecute(@NotNull String[] args) { public void onConsoleExecute(@NotNull String[] args) {
if (args.length == 0) { if (args.length == 0) {
plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: rtp [player]"); plugin.log(Level.WARNING, "Invalid syntax. Usage: rtp [player]");
return; return;
} }
final Optional<OnlineUser> foundUser = plugin.findOnlinePlayer(args[0]); final Optional<OnlineUser> foundUser = plugin.findOnlinePlayer(args[0]);
if (foundUser.isEmpty()) { if (foundUser.isEmpty()) {
plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); plugin.log(Level.WARNING, "Player not found: " + args[0]);
return; 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 -> { plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get().getPosition().getWorld(), ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> {
if (position.isEmpty()) { 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; return;
} }
Teleport.builder(plugin, foundUser.get()) Teleport.builder(plugin, foundUser.get())
@@ -120,9 +120,9 @@ public class RtpCommand extends Command implements ConsoleExecutable {
.toTeleport() .toTeleport()
.thenAccept(teleport -> teleport.execute().thenAccept(result -> { .thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (result.successful()) { 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 { } 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.");
} }
})); }));
}); });
@@ -16,7 +16,7 @@ import java.util.Optional;
public abstract class SavedPositionCommand<T extends SavedPosition> extends Command { public abstract class SavedPositionCommand<T extends SavedPosition> extends Command {
private final Class<T> positionType; private final Class<T> positionType;
private final List<String> arguments; protected final List<String> arguments;
protected SavedPositionCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull Class<T> positionType, protected SavedPositionCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull Class<T> positionType,
@NotNull List<String> arguments, @NotNull HuskHomes plugin) { @NotNull List<String> arguments, @NotNull HuskHomes plugin) {
@@ -159,12 +159,12 @@ public class TpCommand extends Command implements TabProvider, ConsoleExecutable
@Override @Override
public void onConsoleExecute(@NotNull String[] args) { public void onConsoleExecute(@NotNull String[] args) {
if (args.length < 2 || args.length > 6) { if (args.length < 2 || args.length > 6) {
plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: tp <player> <destination>"); plugin.log(Level.WARNING, "Invalid syntax. Usage: tp <player> <destination>");
return; return;
} }
final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null);
if (playerToTeleport == null) { if (playerToTeleport == null) {
plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); plugin.log(Level.WARNING, "Player not found: " + args[0]);
return; return;
} }
final TeleportTarget teleportTarget; 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 >= 5 ? new World(args[4], UUID.randomUUID()) : plugin.getWorlds().get(0),
args.length == 6 ? new Server(args[5]) : plugin.getServerName())); args.length == 6 ? new Server(args[5]) : plugin.getServerName()));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: tp <player> <x> <y> <z> [world] [server]"); plugin.log(Level.WARNING, "Invalid syntax. Usage: tp <player> <x> <y> <z> [world] [server]");
return; return;
} }
} }
@@ -195,9 +195,9 @@ public class TpCommand extends Command implements TabProvider, ConsoleExecutable
} }
builder.toTeleport().thenAccept(teleport -> teleport.execute().thenAccept(result -> { builder.toTeleport().thenAccept(teleport -> teleport.execute().thenAccept(result -> {
if (result.successful()) { if (result.successful()) {
plugin.getLoggingAdapter().log(Level.INFO, "Successfully teleported " + playerToTeleport.getUsername()); plugin.log(Level.INFO, "Successfully teleported " + playerToTeleport.getUsername());
} else { } else {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + playerToTeleport.getUsername() + " to " + teleportTarget); plugin.log(Level.WARNING, "Failed to teleport " + playerToTeleport.getUsername() + " to " + teleportTarget);
} }
})); }));
} }
@@ -74,23 +74,23 @@ public class WarpCommand extends Command implements TabProvider, ConsoleExecutab
@Override @Override
public void onConsoleExecute(@NotNull String[] args) { public void onConsoleExecute(@NotNull String[] args) {
if (args.length != 2) { if (args.length != 2) {
plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: warp <player> <warp>"); plugin.log(Level.WARNING, "Invalid syntax. Usage: warp <player> <warp>");
return; return;
} }
final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null); final OnlineUser playerToTeleport = plugin.findOnlinePlayer(args[0]).orElse(null);
if (playerToTeleport == null) { if (playerToTeleport == null) {
plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]); plugin.log(Level.WARNING, "Player not found: " + args[0]);
return; return;
} }
plugin.getDatabase().getWarp(args[1]).thenAccept(optionalWarp -> { plugin.getDatabase().getWarp(args[1]).thenAccept(optionalWarp -> {
if (optionalWarp.isEmpty()) { 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; return;
} }
final Warp warp = optionalWarp.get(); 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) Teleport.builder(plugin, playerToTeleport)
.setTarget(warp) .setTarget(warp)
.toTimedTeleport() .toTimedTeleport()
@@ -64,18 +64,18 @@ public class WarpListCommand extends Command implements ConsoleExecutable {
@Override @Override
public void onConsoleExecute(@NotNull String[] args) { public void onConsoleExecute(@NotNull String[] args) {
plugin.getDatabase().getWarps().thenAccept(warps -> { 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"); StringJoiner rowJoiner = new StringJoiner("\t");
for (int i = 0; i < warps.size(); i++) { for (int i = 0; i < warps.size(); i++) {
final String warp = warps.get(i).meta.name; final String warp = warps.get(i).meta.name;
rowJoiner.add(warp.length() < 16 ? warp + " ".repeat(16 - warp.length()) : warp); rowJoiner.add(warp.length() < 16 ? warp + " ".repeat(16 - warp.length()) : warp);
if ((i + 1) % 3 == 0) { if ((i + 1) % 3 == 0) {
plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); plugin.log(Level.INFO, rowJoiner.toString());
rowJoiner = new StringJoiner("\t"); rowJoiner = new StringJoiner("\t");
} }
} }
plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString()); plugin.log(Level.INFO, rowJoiner.toString());
}); });
} }
} }
@@ -35,10 +35,6 @@ public class Settings {
@YamlKey("check_for_updates") @YamlKey("check_for_updates")
private boolean checkForUpdates = true; private boolean checkForUpdates = true;
@YamlKey("debug_logging")
private boolean debugLogging = false;
// Database settings // Database settings
@YamlComment("Database connection settings") @YamlComment("Database connection settings")
@YamlKey("database.type") @YamlKey("database.type")
@@ -278,10 +274,6 @@ public class Settings {
return checkForUpdates; return checkForUpdates;
} }
public boolean doDebugLogging() {
return debugLogging;
}
public Database.DatabaseType getDatabaseType() { public Database.DatabaseType getDatabaseType() {
return databaseType; return databaseType;
} }
@@ -6,7 +6,6 @@ import net.william278.huskhomes.user.User;
import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.position.*; import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Logger;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -102,19 +101,6 @@ public abstract class Database {
*/ */
protected final HuskHomes plugin; 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 * 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.homesTableName = implementor.getSettings().getTableName(TableName.HOME_DATA);
this.warpsTableName = implementor.getSettings().getTableName(TableName.WARP_DATA); this.warpsTableName = implementor.getSettings().getTableName(TableName.WARP_DATA);
this.teleportsTableName = implementor.getSettings().getTableName(TableName.TELEPORT_DATA); this.teleportsTableName = implementor.getSettings().getTableName(TableName.TELEPORT_DATA);
this.logger = implementor.getLoggingAdapter();
} }
/** /**
@@ -110,10 +110,10 @@ public class MySqlDatabase extends Database {
} }
return true; return true;
} catch (SQLException | IOException e) { } 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) { } 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; return false;
} }
@@ -132,7 +132,7 @@ public class MySqlDatabase extends Database {
statement.executeBatch(); statement.executeBatch();
} }
} catch (IOException | SQLException e) { } 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); throw new RuntimeException(e);
} }
} }
@@ -254,9 +254,9 @@ public class MySqlDatabase extends Database {
statement.setString(2, existingUserData.getUserUuid().toString()); statement.setString(2, existingUserData.getUserUuid().toString());
statement.executeUpdate(); 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) { } 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(); statement.executeUpdate();
} }
} catch (SQLException e) { } 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) { } 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(); return Optional.empty();
} }
@@ -323,7 +323,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -363,7 +363,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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; return userHomes;
} }
@@ -397,7 +397,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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; return warps;
} }
@@ -436,7 +436,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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; return userHomes;
} }
@@ -476,7 +476,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -514,7 +514,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -548,7 +548,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -582,7 +582,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -616,7 +616,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -636,7 +636,7 @@ public class MySqlDatabase extends Database {
statement.executeUpdate(); statement.executeUpdate();
} }
} catch (SQLException e) { } 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) { } 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) { } 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(); return Optional.empty();
} }
@@ -727,7 +727,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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) { } 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(); return Optional.empty();
} }
@@ -785,7 +785,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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) { } 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(); return Optional.empty();
} }
@@ -859,7 +859,7 @@ public class MySqlDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); statement.executeUpdate();
} }
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, plugin.log(Level.SEVERE,
"Failed to update a home in the database for " + home.getOwner().getUsername(), e); "Failed to update a home in the database for " + home.getOwner().getUsername(), e);
} }
}, () -> { }, () -> {
@@ -905,7 +905,7 @@ public class MySqlDatabase extends Database {
statement.executeUpdate(); statement.executeUpdate();
} }
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, plugin.log(Level.SEVERE,
"Failed to set a home to the database for " + home.getOwner().getUsername(), e); "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) { } 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()) { try (Connection connection = getConnection()) {
@@ -939,7 +939,7 @@ public class MySqlDatabase extends Database {
statement.executeUpdate(); statement.executeUpdate();
} }
} catch (SQLException e) { } 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(); statement.executeUpdate();
} }
} catch (SQLException e) { } 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(); return statement.executeUpdate();
} }
} catch (SQLException e) { } 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; return 0;
} }
@@ -1010,7 +1010,7 @@ public class MySqlDatabase extends Database {
statement.executeUpdate(); statement.executeUpdate();
} }
} catch (SQLException e) { } 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(); return statement.executeUpdate();
} }
} catch (SQLException e) { } 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; return 0;
} }
@@ -58,7 +58,7 @@ public class SqLiteDatabase extends Database {
try { try {
// Ensure that the database file exists // Ensure that the database file exists
if (databaseFile.createNewFile()) { 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 // Specify use of the JDBC SQLite driver
@@ -73,11 +73,11 @@ public class SqLiteDatabase extends Database {
// Establish the connection // Establish the connection
connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath(), config.toProperties()); connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath(), config.toProperties());
} catch (IOException e) { } 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) { } 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) { } 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; return true;
} catch (SQLException | IOException e) { } 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) { } 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; return false;
} }
@@ -124,7 +124,7 @@ public class SqLiteDatabase extends Database {
} }
getConnection().setAutoCommit(autoCommit); getConnection().setAutoCommit(autoCommit);
} catch (IOException | SQLException e) { } 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); throw new RuntimeException(e);
} }
} }
@@ -250,9 +250,9 @@ public class SqLiteDatabase extends Database {
statement.setString(2, existingUser.getUserUuid().toString()); statement.setString(2, existingUser.getUserUuid().toString());
statement.executeUpdate(); 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) { } 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(); statement.executeUpdate();
} }
} catch (SQLException e) { } 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) { } 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(); return Optional.empty();
} }
@@ -319,7 +319,7 @@ public class SqLiteDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -359,7 +359,7 @@ public class SqLiteDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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; return userHomes;
} }
@@ -393,7 +393,7 @@ public class SqLiteDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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; return warps;
} }
@@ -432,7 +432,7 @@ public class SqLiteDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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; return userHomes;
} }
@@ -472,7 +472,7 @@ public class SqLiteDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -510,7 +510,7 @@ public class SqLiteDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -544,7 +544,7 @@ public class SqLiteDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -578,7 +578,7 @@ public class SqLiteDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -612,7 +612,7 @@ public class SqLiteDatabase extends Database {
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -630,7 +630,7 @@ public class SqLiteDatabase extends Database {
statement.setString(4, savedUser.getUserUuid().toString()); statement.setString(4, savedUser.getUserUuid().toString());
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) { } 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(); deleteStatement.executeUpdate();
} }
} catch (SQLException e) { } 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) // Set the user's teleport into the database (if it's not null)
@@ -664,7 +664,7 @@ public class SqLiteDatabase extends Database {
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) { } 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"))); resultSet.getString("server_name")));
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -721,7 +721,7 @@ public class SqLiteDatabase extends Database {
} }
} catch (SQLException e) { } 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) { } 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(); return Optional.empty();
} }
@@ -777,7 +777,7 @@ public class SqLiteDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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"))); resultSet.getString("server_name")));
} }
} catch (SQLException e) { } 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(); return Optional.empty();
} }
@@ -848,7 +848,7 @@ public class SqLiteDatabase extends Database {
} }
} catch (SQLException e) { } 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(); statement.executeUpdate();
} }
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, plugin.log(Level.SEVERE,
"Failed to update a home in the database for " + home.getOwner().getUsername(), e); "Failed to update a home in the database for " + home.getOwner().getUsername(), e);
} }
}, () -> { }, () -> {
@@ -893,7 +893,7 @@ public class SqLiteDatabase extends Database {
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
getLogger().log(Level.SEVERE, plugin.log(Level.SEVERE,
"Failed to set a home to the database for " + home.getOwner().getUsername(), e); "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) { } 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(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -926,7 +926,7 @@ public class SqLiteDatabase extends Database {
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) { } 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(); statement.executeUpdate();
} catch (SQLException e) { } 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()); statement.setString(1, user.getUuid().toString());
return statement.executeUpdate(); return statement.executeUpdate();
} catch (SQLException e) { } 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; return 0;
} }
@@ -991,7 +991,7 @@ public class SqLiteDatabase extends Database {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) { } 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(); return statement.executeUpdate();
} catch (SQLException e) { } 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; return 0;
} }
@@ -1023,7 +1023,7 @@ public class SqLiteDatabase extends Database {
} }
} }
} catch (SQLException e) { } 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");
} }
} }
@@ -58,7 +58,7 @@ public class BlueMapHook extends MapHook {
ImageIO.read(Objects.requireNonNull(plugin.getResource("markers/50x/" + WARP_MARKER_IMAGE_NAME + ".png"))), ImageIO.read(Objects.requireNonNull(plugin.getResource("markers/50x/" + WARP_MARKER_IMAGE_NAME + ".png"))),
"huskhomes/" + WARP_MARKER_IMAGE_NAME + ".png"); "huskhomes/" + WARP_MARKER_IMAGE_NAME + ".png");
} catch (IOException e) { } 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); initializedFuture.complete(null);
@@ -3,7 +3,6 @@ package net.william278.huskhomes.hook;
import com.djrapitops.plan.capability.CapabilityService; import com.djrapitops.plan.capability.CapabilityService;
import com.djrapitops.plan.extension.ExtensionService; import com.djrapitops.plan.extension.ExtensionService;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.util.Logger; import net.william278.huskhomes.util.Logger;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -14,13 +13,11 @@ import java.util.logging.Level;
*/ */
public class PlanHook extends PluginHook { public class PlanHook extends PluginHook {
private final Database database; private final HuskHomes plugin;
private final Logger logger;
public PlanHook(@NotNull HuskHomes implementor) { public PlanHook(@NotNull HuskHomes plugin) {
super(implementor, "Plan"); super(plugin, "Plan");
this.database = implementor.getDatabase(); this.plugin = plugin;
this.logger = implementor.getLoggingAdapter();
} }
@Override @Override
@@ -41,12 +38,12 @@ public class PlanHook extends PluginHook {
private void registerDataExtension() { private void registerDataExtension() {
try { try {
ExtensionService.getInstance().register(new PlanDataExtension(database, plugin.getSettings().isCrossServer())); ExtensionService.getInstance().register(new PlanDataExtension(plugin.getDatabase(), plugin.getSettings().isCrossServer()));
} catch (IllegalStateException planIsNotEnabled) { } 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 // Plan is not enabled, handle exception
} catch (IllegalArgumentException dataExtensionImplementationIsInvalid) { } 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 // The DataExtension implementation has an implementation error, handle exception
} }
} }
@@ -183,7 +183,7 @@ public class EventListener {
* Handle when the plugin is disabling (server is shutting down) * Handle when the plugin is disabling (server is shutting down)
*/ */
public final void handlePluginDisable() { 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());
} }
} }
@@ -1,6 +1,9 @@
package net.william278.huskhomes.manager; package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes; 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.util.ValidationException;
import net.william278.huskhomes.user.User; import net.william278.huskhomes.user.User;
import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Home;
@@ -17,31 +20,52 @@ public class HomesManager {
this.plugin = plugin; 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<Home> existingHome = plugin.getDatabase().getHome(owner, name); final Optional<Home> existingHome = plugin.getDatabase().getHome(owner, name);
if (existingHome.isPresent() && !overwrite) { if (existingHome.isPresent() && !overwrite) {
throw new ValidationException(ValidationException.Type.NAME_TAKEN); throw new ValidationException(ValidationException.Type.NAME_TAKEN);
} }
if (!plugin.getValidator().isValidName(name)) { if (!plugin.getValidator().isValidName(name)) {
throw new ValidationException(ValidationException.Type.NAME_INVALID); 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 final Home home = existingHome
.map(existing -> { .map(existing -> {
existing.setX(position.getX()); existing.update(position);
existing.setY(position.getY());
existing.setZ(position.getZ());
existing.setWorld(position.getWorld());
existing.setServer(position.getServer());
existing.setYaw(position.getYaw());
existing.setPitch(position.getPitch());
return existing; return existing;
}) })
.orElse(new Home(position, new PositionMeta(name, ""), owner)); .orElse(new Home(position, new PositionMeta(name, ""), owner));
plugin.getDatabase().saveHome(home); 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 { public void deleteHome(@NotNull User owner, @NotNull String name) throws ValidationException {
final Optional<Home> home = plugin.getDatabase().getHome(owner, name); final Optional<Home> home = plugin.getDatabase().getHome(owner, name);
if (home.isEmpty()) { if (home.isEmpty()) {
@@ -55,7 +79,14 @@ public class HomesManager {
} }
public void relocateHome(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException { public void relocateHome(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException {
createHome(owner, name, position, true); final Optional<Home> 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 { 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(); 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); home.setPublic(isPublic);
plugin.getDatabase().saveHome(home); plugin.getDatabase().saveHome(home);
} }
@@ -11,6 +11,7 @@ import java.util.Optional;
public class WarpsManager { public class WarpsManager {
private final HuskHomes plugin; private final HuskHomes plugin;
protected WarpsManager(@NotNull HuskHomes plugin) { protected WarpsManager(@NotNull HuskHomes plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
@@ -53,7 +54,14 @@ public class WarpsManager {
} }
public void relocateWarp(@NotNull String name, @NotNull Position position) { public void relocateWarp(@NotNull String name, @NotNull Position position) {
createWarp(name, position, true); final Optional<Warp> 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 { public void renameHome(@NotNull String name, @NotNull String newName) throws ValidationException {
@@ -57,7 +57,7 @@ public class PluginMessageBroker extends Broker {
try (final DataInputStream messageReader = new DataInputStream(new ByteArrayInputStream(messageBody))) { try (final DataInputStream messageReader = new DataInputStream(new ByteArrayInputStream(messageBody))) {
super.handle(user, plugin.getGson().fromJson(messageReader.readUTF(), Message.class)); super.handle(user, plugin.getGson().fromJson(messageReader.readUTF(), Message.class));
} catch (IOException e) { } 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()); messageWriter.write(messageByteStream.toByteArray());
} }
} catch (IOException e) { } catch (IOException e) {
plugin.getLoggingAdapter().log(Level.SEVERE, "Exception dispatching plugin message", e); plugin.log(Level.SEVERE, "Exception dispatching plugin message", e);
return; return;
} }
@@ -34,7 +34,7 @@ public class RedisBroker extends PluginMessageBroker {
new Thread(getSubscriber(), plugin.getKey("redis_subscriber").toString()).start(); 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 @NotNull
@@ -36,6 +36,20 @@ public class Location {
public 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 * The double-precision defined x coordinate of the location
*/ */
@@ -28,18 +28,9 @@ public class Position extends Location implements Target {
private Position() { private Position() {
} }
/** @Override
* Update the position to match that of another position
*
* @param newPosition The position to update to
*/
public void update(@NotNull Position newPosition) { public void update(@NotNull Position newPosition) {
this.setX(newPosition.getX()); super.update(newPosition);
this.setY(newPosition.getY());
this.setZ(newPosition.getZ());
this.setYaw(newPosition.getYaw());
this.setPitch(newPosition.getPitch());
this.setWorld(newPosition.getWorld());
this.setServer(newPosition.getServer()); this.setServer(newPosition.getServer());
} }
@@ -8,7 +8,25 @@ import java.util.UUID;
/** /**
* Represents data about a player on the server * 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 @NotNull
public UUID getUserUuid() { public UUID getUserUuid() {
@@ -20,4 +38,29 @@ public record SavedUser(@NotNull User user, int homeSlots, boolean ignoringTelep
return user.getUsername(); 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;
}
} }
@@ -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;
}
}
@@ -1,18 +1,45 @@
package net.william278.huskhomes.util; package net.william278.huskhomes.util;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class ValidationException extends IllegalArgumentException { public class ValidationException extends IllegalArgumentException {
private final Type error;
public ValidationException(@NotNull ValidationException.Type error) { public ValidationException(@NotNull ValidationException.Type error) {
super("Error validating position: " + error.name()); 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 { public enum Type {
NOT_FOUND, NOT_FOUND,
NAME_TAKEN, NAME_TAKEN,
NAME_INVALID, NAME_INVALID,
DESCRIPTION_INVALID REACHED_MAX_HOMES, NOT_ENOUGH_HOME_SLOTS, REACHED_MAX_PUBLIC_HOMES, DESCRIPTION_INVALID
} }
} }