Start refactor work

This commit is contained in:
William278 committed 2023-03-01 16:23:01 +00:00
1 parent 6a8851a446
commit 3e1ec09487
51 files changed
+962 -1039

No files matched your search

@@ -19,6 +19,7 @@ import net.william278.huskhomes.event.EventDispatcher;
import net.william278.huskhomes.hook.*; import net.william278.huskhomes.hook.*;
import net.william278.huskhomes.listener.BukkitEventListener; import net.william278.huskhomes.listener.BukkitEventListener;
import net.william278.huskhomes.listener.EventListener; import net.william278.huskhomes.listener.EventListener;
import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Messenger; import net.william278.huskhomes.network.Messenger;
import net.william278.huskhomes.network.PluginMessenger; import net.william278.huskhomes.network.PluginMessenger;
import net.william278.huskhomes.network.RedisMessenger; import net.william278.huskhomes.network.RedisMessenger;
@@ -27,7 +28,6 @@ import net.william278.huskhomes.migrator.Migrator;
import net.william278.huskhomes.player.BukkitPlayer; import net.william278.huskhomes.player.BukkitPlayer;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.SavedPositionManager;
import net.william278.huskhomes.position.Server; import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.position.World; import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.NormalDistributionEngine; import net.william278.huskhomes.random.NormalDistributionEngine;
@@ -58,7 +58,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTaskRunner {
/** /**
* Metrics ID for <a href="https://bstats.org/plugin/bukkit/HuskHomes/8430">HuskHomes on Bukkit</a>. * Metrics ID for <a href="https://bstats.org/plugin/bukkit/HuskHomes/8430">HuskHomes on Bukkit</a>.
@@ -70,7 +70,8 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
private Database database; private Database database;
private Cache cache; private Cache cache;
private RequestManager requestManager; private RequestManager requestManager;
private SavedPositionManager savedPositionManager; private Validator validator;
private Manager manager;
private EventListener eventListener; private EventListener eventListener;
private RandomTeleportEngine randomTeleportEngine; private RandomTeleportEngine randomTeleportEngine;
private CachedSpawn serverSpawn; private CachedSpawn serverSpawn;
@@ -118,7 +119,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
getLoggingAdapter().log(Level.INFO, "Loading plugin configuration settings & locales..."); getLoggingAdapter().log(Level.INFO, "Loading plugin configuration settings & locales...");
initialized.set(reload()); initialized.set(reload());
if (initialized.get()) { if (initialized.get()) {
logger.showDebugLogs(settings.debugLogging); logger.showDebugLogs(settings.doDebugLogging());
if (upgradeData != null) { if (upgradeData != null) {
upgradeData.upgradeSettings(settings); upgradeData.upgradeSettings(settings);
} }
@@ -129,7 +130,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
// Initialize the database // Initialize the database
getLoggingAdapter().log(Level.INFO, "Attempting to establish connection to the database..."); getLoggingAdapter().log(Level.INFO, "Attempting to establish connection to the database...");
final Settings.DatabaseType databaseType = settings.databaseType; final Settings.DatabaseType databaseType = settings.getDatabaseType();
this.database = switch (databaseType == null ? Settings.DatabaseType.MYSQL : databaseType) { this.database = switch (databaseType == null ? Settings.DatabaseType.MYSQL : databaseType) {
case MYSQL -> new MySqlDatabase(this); case MYSQL -> new MySqlDatabase(this);
case SQLITE -> new SqLiteDatabase(this); case SQLITE -> new SqLiteDatabase(this);
@@ -142,9 +143,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
} }
// Initialize the network messenger if proxy mode is enabled // Initialize the network messenger if proxy mode is enabled
if (getSettings().crossServer) { if (getSettings().isCrossServer()) {
getLoggingAdapter().log(Level.INFO, "Initializing the network messenger..."); getLoggingAdapter().log(Level.INFO, "Initializing the network messenger...");
messenger = switch (settings.messengerType) { messenger = switch (settings.getMessengerType()) {
case PLUGIN_MESSAGE -> new PluginMessenger(); case PLUGIN_MESSAGE -> new PluginMessenger();
case REDIS -> new RedisMessenger(); case REDIS -> new RedisMessenger();
}; };
@@ -152,6 +153,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
getLoggingAdapter().log(Level.INFO, "Successfully initialized the network messenger."); getLoggingAdapter().log(Level.INFO, "Successfully initialized the network messenger.");
} }
// Prepare the validator
this.validator = new Validator(this);
// Prepare the request manager // Prepare the request manager
this.requestManager = new RequestManager(this); this.requestManager = new RequestManager(this);
@@ -163,22 +167,22 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
cache.initialize(database); cache.initialize(database);
// Prepare the home and warp position manager // Prepare the home and warp position manager
this.savedPositionManager = new SavedPositionManager(this); this.manager = new Manager(this);
// Initialize the RTP engine with the default normal distribution engine // Initialize the RTP engine with the default normal distribution engine
setRandomTeleportEngine(new NormalDistributionEngine(this)); setRandomTeleportEngine(new NormalDistributionEngine(this));
// Register plugin hooks (Economy, Maps, Plan) // Register plugin hooks (Economy, Maps, Plan)
this.pluginHooks = new HashSet<>(); this.pluginHooks = new HashSet<>();
if (settings.economy) { if (settings.isEconomy()) {
if (Bukkit.getPluginManager().getPlugin("RedisEconomy") != null) { if (Bukkit.getPluginManager().getPlugin("RedisEconomy") != null) {
pluginHooks.add(new RedisEconomyHook(this)); pluginHooks.add(new RedisEconomyHook(this));
} else if (Bukkit.getPluginManager().getPlugin("Vault") != null) { } else if (Bukkit.getPluginManager().getPlugin("Vault") != null) {
pluginHooks.add(new VaultEconomyHook(this)); pluginHooks.add(new VaultEconomyHook(this));
} }
} }
if (settings.doMapHook) { if (settings.isDoMapHook()) {
switch (settings.mappingPlugin) { switch (settings.getMappingPlugin()) {
case DYNMAP -> { case DYNMAP -> {
final Plugin dynmapPlugin = Bukkit.getPluginManager().getPlugin("Dynmap"); final Plugin dynmapPlugin = Bukkit.getPluginManager().getPlugin("Dynmap");
if (dynmapPlugin != null) { if (dynmapPlugin != null) {
@@ -223,7 +227,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
} }
// If the command is disabled, use the disabled CommandBase // If the command is disabled, use the disabled CommandBase
if (settings.disabledCommands.stream().anyMatch(disabledCommand -> { if (settings.getDisabledCommands().stream().anyMatch(disabledCommand -> {
final String command = (disabledCommand.startsWith("/") ? disabledCommand.substring(1) : disabledCommand); final String command = (disabledCommand.startsWith("/") ? disabledCommand.substring(1) : disabledCommand);
return command.equalsIgnoreCase(commandType.commandBase.command) || Arrays.stream(commandType.commandBase.aliases).anyMatch(alias -> alias.equalsIgnoreCase(command)); return command.equalsIgnoreCase(commandType.commandBase.command) || Arrays.stream(commandType.commandBase.aliases).anyMatch(alias -> alias.equalsIgnoreCase(command));
})) { })) {
@@ -246,7 +250,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
registerMetrics(METRICS_ID); registerMetrics(METRICS_ID);
// Check for updates // Check for updates
if (settings.checkForUpdates) { if (settings.doCheckForUpdates()) {
getLoggingAdapter().log(Level.INFO, "Checking for updates..."); 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" + getPluginVersion() + ")"))); getLatestVersionIfOutdated().thenAccept(newestVersion -> newestVersion.ifPresent(newVersion -> getLoggingAdapter().log(Level.WARNING, "An update is available for HuskHomes, v" + newVersion + " (Currently running v" + getPluginVersion() + ")")));
} }
@@ -347,10 +351,16 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
return requestManager; return requestManager;
} }
@Override
@NotNull
public Validator getValidator() {
return validator;
}
@NotNull @NotNull
@Override @Override
public SavedPositionManager getSavedPositionManager() { public Manager getManager() {
return savedPositionManager; return manager;
} }
@NotNull @NotNull
@@ -478,11 +488,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
this.settings = Annotaml.create(new File(getDataFolder(), "config.yml"), Settings.class).get(); this.settings = Annotaml.create(new File(getDataFolder(), "config.yml"), Settings.class).get();
// Load locales from language preset default // Load locales from language preset default
final Locales languagePresets = Annotaml.create(Locales.class, Objects.requireNonNull(getResource("locales/" + settings.language + ".yml"))).get(); final Locales languagePresets = Annotaml.create(Locales.class, Objects.requireNonNull(getResource("locales/" + settings.getLanguage() + ".yml"))).get();
this.locales = Annotaml.create(new File(getDataFolder(), "messages_" + settings.language + ".yml"), languagePresets).get(); this.locales = Annotaml.create(new File(getDataFolder(), "messages_" + settings.getLanguage() + ".yml"), languagePresets).get();
// Load server from file // Load server from file
if (settings.crossServer) { if (settings.isCrossServer()) {
this.server = Annotaml.create(new File(getDataFolder(), "server.yml"), Server.class).get(); this.server = Annotaml.create(new File(getDataFolder(), "server.yml"), Server.class).get();
} else { } else {
this.server = Server.getDefault(); this.server = Server.getDefault();
@@ -514,22 +524,28 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
public void registerMetrics(int metricsId) { public void registerMetrics(int metricsId) {
try { try {
final Metrics metrics = new Metrics(this, metricsId); final Metrics metrics = new Metrics(this, metricsId);
metrics.addCustomChart(new SimplePie("bungee_mode", () -> Boolean.toString(getSettings().crossServer))); metrics.addCustomChart(new SimplePie("bungee_mode", () -> Boolean.toString(getSettings().isCrossServer())));
if (getSettings().crossServer) { if (getSettings().isCrossServer()) {
metrics.addCustomChart(new SimplePie("messenger_type", () -> getSettings().messengerType.displayName)); metrics.addCustomChart(new SimplePie("messenger_type", () -> getSettings().getMessengerType().displayName));
} }
metrics.addCustomChart(new SimplePie("language", () -> getSettings().language.toLowerCase())); metrics.addCustomChart(new SimplePie("language", () -> getSettings().getLanguage().toLowerCase()));
metrics.addCustomChart(new SimplePie("database_type", () -> getSettings().databaseType.displayName)); metrics.addCustomChart(new SimplePie("database_type", () -> getSettings().getDatabaseType().displayName));
metrics.addCustomChart(new SimplePie("using_economy", () -> Boolean.toString(getSettings().economy))); metrics.addCustomChart(new SimplePie("using_economy", () -> Boolean.toString(getSettings().isEconomy())));
metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().doMapHook))); metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().isDoMapHook())));
if (getSettings().doMapHook) { if (getSettings().isDoMapHook()) {
metrics.addCustomChart(new SimplePie("map_type", () -> getSettings().mappingPlugin.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); getLoggingAdapter().log(Level.WARNING, "Failed to register metrics", e);
} }
} }
@Override
@NotNull
public HuskHomes getPlugin() {
return this;
}
// Default constructor // Default constructor
@SuppressWarnings("unused") @SuppressWarnings("unused")
public BukkitHuskHomes() { public BukkitHuskHomes() {
@@ -541,5 +557,4 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, @NotNull File dataFolder, @NotNull File file) { protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, @NotNull File dataFolder, @NotNull File file) {
super(loader, description, dataFolder, file); super(loader, description, dataFolder, file);
} }
} }
@@ -37,7 +37,7 @@ public class DynMapHook extends MapHook {
protected CompletableFuture<Void> initializeMap() { protected CompletableFuture<Void> initializeMap() {
return CompletableFuture.runAsync(() -> { return CompletableFuture.runAsync(() -> {
final MarkerAPI markerAPI = dynmapAPI.getMarkerAPI(); final MarkerAPI markerAPI = dynmapAPI.getMarkerAPI();
if (plugin.getSettings().publicHomesOnMap) { if (plugin.getSettings().isPublicHomesOnMap()) {
markerAPI.getMarkerIcons().stream() markerAPI.getMarkerIcons().stream()
.filter(markerIcon -> markerIcon.getMarkerIconID().equals(PUBLIC_HOME_MARKER_IMAGE_NAME)) .filter(markerIcon -> markerIcon.getMarkerIconID().equals(PUBLIC_HOME_MARKER_IMAGE_NAME))
.findFirst() .findFirst()
@@ -47,7 +47,7 @@ public class DynMapHook extends MapHook {
markerAPI.createMarkerSet(PUBLIC_HOMES_MARKER_SET_ID, markerAPI.createMarkerSet(PUBLIC_HOMES_MARKER_SET_ID,
"Public Homes", dynmapAPI.getMarkerAPI().getMarkerIcons(), false); "Public Homes", dynmapAPI.getMarkerAPI().getMarkerIcons(), false);
} }
if (plugin.getSettings().warpsOnMap) { if (plugin.getSettings().isWarpsOnMap()) {
markerAPI.getMarkerIcons().stream() markerAPI.getMarkerIcons().stream()
.filter(markerIcon -> markerIcon.getMarkerIconID().equals(WARP_MARKER_IMAGE_NAME)) .filter(markerIcon -> markerIcon.getMarkerIconID().equals(WARP_MARKER_IMAGE_NAME))
.findFirst() .findFirst()
@@ -14,7 +14,7 @@ public class RedisEconomyHook extends VaultEconomyHook {
public boolean initialize() { public boolean initialize() {
RedisEconomyAPI api = RedisEconomyAPI.getAPI(); RedisEconomyAPI api = RedisEconomyAPI.getAPI();
if (api != null) { if (api != null) {
economy = api.getCurrencyByName(plugin.getSettings().redisEconomyName); economy = api.getCurrencyByName(plugin.getSettings().getRedisEconomyName());
if (economy != null) { if (economy != null) {
return true; return true;
} }
@@ -62,7 +62,7 @@ public class BukkitEventListener extends EventListener implements Listener {
// (https://jd.papermc.io/paper/1.19/com/destroystokyo/paper/event/player/PlayerSetSpawnEvent.html) // (https://jd.papermc.io/paper/1.19/com/destroystokyo/paper/event/player/PlayerSetSpawnEvent.html)
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onPlayerUpdateRespawnLocation(PlayerInteractEvent event) { public void onPlayerUpdateRespawnLocation(PlayerInteractEvent event) {
if (!(plugin.getSettings().crossServer && plugin.getSettings().globalRespawning)) return; if (!(plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning())) return;
if (event.getClickedBlock() == null) return; if (event.getClickedBlock() == null) return;
if (!(event.getClickedBlock().getBlockData() instanceof Bed if (!(event.getClickedBlock().getBlockData() instanceof Bed
|| event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) return; || event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) return;
@@ -25,12 +25,12 @@ public class LegacyMigrator extends Migrator {
public LegacyMigrator(@NotNull HuskHomes implementor) { public LegacyMigrator(@NotNull HuskHomes implementor) {
super(implementor); super(implementor);
this.sourceDatabaseType = implementor.getSettings().databaseType; this.sourceDatabaseType = implementor.getSettings().getDatabaseType();
this.sourceMySqlHost = implementor.getSettings().mySqlHost; this.sourceMySqlHost = implementor.getSettings().getMySqlHost();
this.sourceMySqlPort = implementor.getSettings().mySqlPort; this.sourceMySqlPort = implementor.getSettings().getMySqlPort();
this.sourceMySqlDatabase = implementor.getSettings().mySqlDatabase; this.sourceMySqlDatabase = implementor.getSettings().getMySqlDatabase();
this.sourceMySqlUsername = implementor.getSettings().mySqlUsername; this.sourceMySqlUsername = implementor.getSettings().getMySqlUsername();
this.sourceMySqlPassword = implementor.getSettings().mySqlPassword; this.sourceMySqlPassword = implementor.getSettings().getMySqlPassword();
} }
public LegacyMigrator(@NotNull HuskHomes implementor, @NotNull BukkitUpgradeUtil bukkitUpgradeUtil) { public LegacyMigrator(@NotNull HuskHomes implementor, @NotNull BukkitUpgradeUtil bukkitUpgradeUtil) {
@@ -57,9 +57,9 @@ public class LegacyMigrator extends Migrator {
return true; return true;
} }
if (sourceDatabaseType == plugin.getSettings().databaseType if (sourceDatabaseType == plugin.getSettings().getDatabaseType()
&& sourceMySqlHost.equals(plugin.getSettings().mySqlHost) && sourceMySqlHost.equals(plugin.getSettings().getMySqlHost())
&& sourceMySqlPort == plugin.getSettings().mySqlPort) { && sourceMySqlPort == plugin.getSettings().getMySqlPort()) {
migrateMySqlDatabase(); migrateMySqlDatabase();
return true; return true;
} }
@@ -0,0 +1,30 @@
package net.william278.huskhomes.util;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.HuskHomes;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public interface BukkitTaskRunner extends TaskRunner {
@Override
default void runAsync(@NotNull Runnable runnable) {
Bukkit.getScheduler().runTaskAsynchronously((BukkitHuskHomes) getPlugin(), runnable);
}
@Override
default <T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> supplier) {
final CompletableFuture<T> future = new CompletableFuture<>();
Bukkit.getScheduler().runTaskAsynchronously((BukkitHuskHomes) getPlugin(),
() -> future.complete(supplier.get()));
return future;
}
@Override
default void runSync(@NotNull Runnable runnable) {
Bukkit.getScheduler().runTask((BukkitHuskHomes) getPlugin(), runnable);
}
}
@@ -112,7 +112,7 @@ public class Cache {
.map(onlineUser -> onlineUser.username) .map(onlineUser -> onlineUser.username)
.toList()); .toList());
if (plugin.getSettings().crossServer) { if (plugin.getSettings().isCrossServer()) {
return plugin.getMessenger() return plugin.getMessenger()
.getOnlinePlayerNames(requester) .getOnlinePlayerNames(requester)
.thenApply(networkedPlayers -> { .thenApply(networkedPlayers -> {
@@ -11,6 +11,7 @@ import net.william278.huskhomes.event.EventDispatcher;
import net.william278.huskhomes.hook.EconomyHook; import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.hook.MapHook; import net.william278.huskhomes.hook.MapHook;
import net.william278.huskhomes.hook.PluginHook; import net.william278.huskhomes.hook.PluginHook;
import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Messenger; import net.william278.huskhomes.network.Messenger;
import net.william278.huskhomes.migrator.Migrator; import net.william278.huskhomes.migrator.Migrator;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
@@ -19,6 +20,8 @@ import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.request.RequestManager; import net.william278.huskhomes.request.RequestManager;
import net.william278.huskhomes.util.Logger; 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.Validator;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -32,7 +35,7 @@ import java.util.concurrent.CompletableFuture;
/** /**
* Represents a cross-platform instance of the plugin * Represents a cross-platform instance of the plugin
*/ */
public interface HuskHomes { public interface HuskHomes extends TaskRunner {
int SPIGOT_RESOURCE_ID = 83767; int SPIGOT_RESOURCE_ID = 83767;
@@ -85,7 +88,7 @@ public interface HuskHomes {
if (localPlayer.isPresent()) { if (localPlayer.isPresent()) {
return CompletableFuture.completedFuture(Optional.of(localPlayer.get().username)); return CompletableFuture.completedFuture(Optional.of(localPlayer.get().username));
} }
if (getSettings().crossServer) { if (getSettings().isCrossServer()) {
return getMessenger().findPlayer(requester, targetPlayerName); return getMessenger().findPlayer(requester, targetPlayerName);
} }
return CompletableFuture.completedFuture(Optional.empty()); return CompletableFuture.completedFuture(Optional.empty());
@@ -128,15 +131,24 @@ public interface HuskHomes {
* *
* @return the plugin {@link RequestManager} * @return the plugin {@link RequestManager}
*/ */
@NotNull RequestManager getRequestManager(); @NotNull
RequestManager getRequestManager();
/** /**
* The {@link SavedPositionManager} that manages setting homes and warps * The {@link Validator} for validating thome names and descriptions
* *
* @return the {@link SavedPositionManager} implementation * @return the {@link Validator} instance
*/ */
@NotNull @NotNull
SavedPositionManager getSavedPositionManager(); Validator getValidator();
/**
* The {@link Manager} that manages home, warp and user data
*
* @return the {@link Manager} implementation
*/
@NotNull
Manager getManager();
/** /**
* The {@link Messenger} that sends cross-network messages * The {@link Messenger} that sends cross-network messages
@@ -189,10 +201,10 @@ public interface HuskHomes {
* *
* @return the {@link Position} of the spawn, or an empty {@link Optional} if it has not been set * @return the {@link Position} of the spawn, or an empty {@link Optional} if it has not been set
*/ */
default CompletableFuture<Optional<? extends Position>> getSpawn() { default Optional<? extends Position> getSpawn() {
return CompletableFuture.supplyAsync(() -> getSettings().crossServer && getSettings().globalSpawn return getSettings().isCrossServer() && getSettings().isGlobalSpawn()
? getDatabase().getWarp(getSettings().globalSpawnName).join() ? getDatabase().getWarp(getSettings().getGlobalSpawnName())
: getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(getServerName()))); : getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(getServerName()));
} }
/** /**
@@ -246,7 +258,7 @@ public interface HuskHomes {
* @return the {@link MapHook} optionally being used * @return the {@link MapHook} optionally being used
*/ */
default Optional<MapHook> getMapHook() { default Optional<MapHook> getMapHook() {
return getSettings().doMapHook ? getHook(MapHook.class) : Optional.empty(); return getSettings().isDoMapHook() ? getHook(MapHook.class) : Optional.empty();
} }
/** /**
@@ -255,7 +267,7 @@ public interface HuskHomes {
* @return the {@link EconomyHook} optionally being used * @return the {@link EconomyHook} optionally being used
*/ */
default Optional<EconomyHook> getEconomyHook() { default Optional<EconomyHook> getEconomyHook() {
return getSettings().economy ? getHook(EconomyHook.class) : Optional.empty(); return getSettings().isEconomy() ? getHook(EconomyHook.class) : Optional.empty();
} }
/** /**
@@ -288,7 +300,7 @@ public interface HuskHomes {
* @param action the action to deduct the cost from if needed * @param action the action to deduct the cost from if needed
*/ */
default void performEconomyTransaction(@NotNull OnlineUser player, @NotNull Settings.EconomyAction action) { default void performEconomyTransaction(@NotNull OnlineUser player, @NotNull Settings.EconomyAction action) {
if (!getSettings().economy) return; if (!getSettings().isEconomy()) return;
final Optional<Double> cost = getSettings().getEconomyCost(action).map(Math::abs); final Optional<Double> cost = getSettings().getEconomyCost(action).map(Math::abs);
if (cost.isPresent() && !player.hasPermission(Permission.BYPASS_ECONOMY_CHECKS.node)) { if (cost.isPresent() && !player.hasPermission(Permission.BYPASS_ECONOMY_CHECKS.node)) {
@@ -9,11 +9,10 @@ public class ValidationException extends IllegalArgumentException {
} }
public enum ValidationError { public enum ValidationError {
NAME_LENGTH, NOT_FOUND,
NAME_TAKEN, NAME_TAKEN,
NAME_CHARACTERS, NAME_INVALID,
NAME_RESERVED, DESCRIPTION_INVALID
DESCRIPTION_LENGTH,
DESCRIPTION_CHARACTERS
} }
} }
@@ -47,7 +47,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public final CompletableFuture<Optional<UserData>> getUserData(@NotNull UUID uuid) { public final CompletableFuture<Optional<UserData>> getUserData(@NotNull UUID uuid) {
return plugin.getDatabase().getUserData(uuid); return plugin.supplyAsync(() -> plugin.getDatabase().getUserData(uuid));
} }
/** /**
@@ -58,7 +58,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public final CompletableFuture<Optional<UserData>> getUserData(@NotNull String username) { public final CompletableFuture<Optional<UserData>> getUserData(@NotNull String username) {
return plugin.getDatabase().getUserDataByName(username); return plugin.supplyAsync(() -> plugin.getDatabase().getUserDataByName(username));
} }
/** /**
@@ -69,7 +69,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public CompletableFuture<Optional<Position>> getUserLastPosition(@NotNull User user) { public CompletableFuture<Optional<Position>> getUserLastPosition(@NotNull User user) {
return plugin.getDatabase().getLastPosition(user); return plugin.supplyAsync(() -> plugin.getDatabase().getLastPosition(user));
} }
/** /**
@@ -80,7 +80,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public CompletableFuture<Optional<Position>> getUserOfflinePosition(@NotNull User user) { public CompletableFuture<Optional<Position>> getUserOfflinePosition(@NotNull User user) {
return plugin.getDatabase().getOfflinePosition(user); return plugin.supplyAsync(() -> plugin.getDatabase().getOfflinePosition(user));
} }
/** /**
@@ -94,10 +94,10 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public CompletableFuture<Optional<Position>> getUserRespawnPosition(@NotNull User user) { public CompletableFuture<Optional<Position>> getUserRespawnPosition(@NotNull User user) {
if (!plugin.getSettings().crossServer || plugin.getSettings().globalRespawning) { if (!plugin.getSettings().isCrossServer() || plugin.getSettings().isGlobalRespawning()) {
return CompletableFuture.completedFuture(Optional.empty()); return CompletableFuture.completedFuture(Optional.empty());
} }
return plugin.getDatabase().getRespawnPosition(user); return plugin.supplyAsync(() -> plugin.getDatabase().getRespawnPosition(user));
} }
/** /**
@@ -119,8 +119,8 @@ public abstract class BaseHuskHomesAPI {
* @return A {@link CompletableFuture} that will complete when the data has been saved * @return A {@link CompletableFuture} that will complete when the data has been saved
* @since 3.0 * @since 3.0
*/ */
public final CompletableFuture<Void> saveUserData(@NotNull UserData userData) { public final void saveUserData(@NotNull UserData userData) {
return plugin.getDatabase().updateUserData(userData); plugin.runAsync(() -> plugin.getDatabase().updateUserData(userData));
} }
/** /**
@@ -130,7 +130,7 @@ public abstract class BaseHuskHomesAPI {
* @return A {@link CompletableFuture} that will complete with a list of {@link Home}s set by the user * @return A {@link CompletableFuture} that will complete with a list of {@link Home}s set by the user
*/ */
public final CompletableFuture<List<Home>> getUserHomes(@NotNull User user) { public final CompletableFuture<List<Home>> getUserHomes(@NotNull User user) {
return plugin.getDatabase().getHomes(user); return plugin.supplyAsync(() -> plugin.getDatabase().getHomes(user));
} }
/** /**
@@ -154,7 +154,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public final CompletableFuture<List<Home>> getPublicHomes() { public final CompletableFuture<List<Home>> getPublicHomes() {
return plugin.getDatabase().getPublicHomes(); return plugin.supplyAsync(() -> plugin.getDatabase().getPublicHomes());
} }
/** /**
@@ -166,7 +166,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public final CompletableFuture<Optional<Home>> getHome(@NotNull User user, @NotNull String homeName) { public final CompletableFuture<Optional<Home>> getHome(@NotNull User user, @NotNull String homeName) {
return plugin.getDatabase().getHome(user, homeName); return plugin.supplyAsync(() -> plugin.getDatabase().getHome(user, homeName));
} }
/** /**
@@ -176,7 +176,7 @@ public abstract class BaseHuskHomesAPI {
* @return A {@link CompletableFuture} that will complete with the {@link Home} if it exists, otherwise an empty {@link Optional} * @return A {@link CompletableFuture} that will complete with the {@link Home} if it exists, otherwise an empty {@link Optional}
*/ */
public final CompletableFuture<Optional<Home>> getHome(@NotNull UUID homeUuid) { public final CompletableFuture<Optional<Home>> getHome(@NotNull UUID homeUuid) {
return plugin.getDatabase().getHome(homeUuid); return plugin.supplyAsync(() -> plugin.getDatabase().getHome(homeUuid));
} }
/** /**
@@ -186,7 +186,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public final CompletableFuture<List<Warp>> getWarps() { public final CompletableFuture<List<Warp>> getWarps() {
return plugin.getDatabase().getWarps(); return plugin.supplyAsync(() -> plugin.getDatabase().getWarps());
} }
/** /**
@@ -197,7 +197,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public final CompletableFuture<Optional<Warp>> getWarp(@NotNull String warpName) { public final CompletableFuture<Optional<Warp>> getWarp(@NotNull String warpName) {
return plugin.getDatabase().getWarp(warpName); return plugin.supplyAsync(() -> plugin.getDatabase().getWarp(warpName));
} }
/** /**
@@ -207,7 +207,7 @@ public abstract class BaseHuskHomesAPI {
* @return A {@link CompletableFuture} that will complete with the {@link Warp} if it exists, otherwise an empty {@link Optional} * @return A {@link CompletableFuture} that will complete with the {@link Warp} if it exists, otherwise an empty {@link Optional}
*/ */
public final CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID warpUuid) { public final CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID warpUuid) {
return plugin.getDatabase().getWarp(warpUuid); return plugin.supplyAsync(() -> plugin.getDatabase().getWarp(warpUuid));
} }
/** /**
@@ -217,76 +217,7 @@ public abstract class BaseHuskHomesAPI {
* @return A {@link CompletableFuture} that will complete with the {@link Position} of the spawn point * @return A {@link CompletableFuture} that will complete with the {@link Position} of the spawn point
*/ */
public final CompletableFuture<Optional<? extends Position>> getSpawn() { public final CompletableFuture<Optional<? extends Position>> getSpawn() {
return plugin.getSpawn(); return plugin.supplyAsync(plugin::getSpawn);
}
/**
* Update the {@link PositionMeta} of a {@link Home}
*
* @param home The {@link Home} to update
* @param newMeta The new {@link PositionMeta} to set
* @return A {@link CompletableFuture} that will complete when the {@link Home} has been updated with a
* {@link SavedPositionManager.SaveResult} indicating if the update was successful
* @since 3.0
*/
public final CompletableFuture<SavedPositionManager.SaveResult> updateHomeMeta(@NotNull Home home,
@NotNull PositionMeta newMeta) {
return plugin.getSavedPositionManager().updateHomeMeta(home, newMeta);
}
/**
* Update the position of a {@link Home}, relocating it
*
* @param home The {@link Home} to update
* @param newPosition The new {@link Position} to relocate the home to
* @return A {@link CompletableFuture} that will complete with a boolean indicating if the home was
* updated ({@code true} if it was updated; otherwise, {@code false})
* @since 3.0
*/
public final CompletableFuture<Boolean> updateHomePosition(@NotNull Home home,
@NotNull Position newPosition) {
return plugin.getSavedPositionManager().updateHomePosition(home, newPosition);
}
/**
* Update the privacy of a {@link Home}
*
* @param home The {@link Home} to update
* @param isPublic Whether the home should be set to public or not
* @return A {@link CompletableFuture} that will complete with a boolean indicating if the home's privacy
* was updated ({@code true} if it was updated; otherwise, {@code false})
* @since 3.0
*/
public final CompletableFuture<Boolean> updateHomePrivacy(@NotNull Home home,
final boolean isPublic) {
return plugin.getSavedPositionManager().updateHomePrivacy(home, isPublic);
}
/**
* Update the {@link PositionMeta} of a {@link Warp}
*
* @param warp The {@link Warp} to update
* @param newMeta The new {@link PositionMeta} to set
* @return A {@link CompletableFuture} that will complete when the {@link Warp} has been updated with a
* {@link SavedPositionManager.SaveResult} indicating if the update was successful
* @since 3.0
*/
public final CompletableFuture<SavedPositionManager.SaveResult> updateWarpMeta(@NotNull Warp warp,
@NotNull PositionMeta newMeta) {
return plugin.getSavedPositionManager().updateWarpMeta(warp, newMeta);
}
/**
* Update the position of a {@link Warp}, relocating it
*
* @param warp The {@link Warp} to update
* @param newPosition The new {@link Position} to relocate the warp to
* @return A {@link CompletableFuture} that will complete with a boolean indicating if the warp was
* updated ({@code true} if it was updated; otherwise, {@code false})
*/
public final CompletableFuture<Boolean> updateWarpPosition(@NotNull Warp warp,
@NotNull Position newPosition) {
return plugin.getSavedPositionManager().updateWarpPosition(warp, newPosition);
} }
/** /**
@@ -297,7 +228,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public final int getMaxHomeSlots(@NotNull OnlineUser user) { public final int getMaxHomeSlots(@NotNull OnlineUser user) {
return user.getMaxHomes(plugin.getSettings().maxHomes, plugin.getSettings().stackPermissionLimits); return user.getMaxHomes(plugin.getSettings().getMaxHomes(), plugin.getSettings().doStackPermissionLimits());
} }
/** /**
@@ -310,7 +241,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public final int getFreeHomeSlots(@NotNull OnlineUser user) { public final int getFreeHomeSlots(@NotNull OnlineUser user) {
return user.getFreeHomes(plugin.getSettings().freeHomeSlots, plugin.getSettings().stackPermissionLimits); return user.getFreeHomes(plugin.getSettings().getFreeHomeSlots(), plugin.getSettings().doStackPermissionLimits());
} }
/** /**
@@ -321,7 +252,7 @@ public abstract class BaseHuskHomesAPI {
* @since 3.0 * @since 3.0
*/ */
public final int getMaxPublicHomeSlots(@NotNull OnlineUser user) { public final int getMaxPublicHomeSlots(@NotNull OnlineUser user) {
return user.getMaxPublicHomes(plugin.getSettings().maxPublicHomes, plugin.getSettings().stackPermissionLimits); return user.getMaxPublicHomes(plugin.getSettings().getMaxPublicHomes(), plugin.getSettings().doStackPermissionLimits());
} }
/** /**
@@ -388,22 +319,19 @@ public abstract class BaseHuskHomesAPI {
public final CompletableFuture<TeleportResult> randomlyTeleportPlayer(@NotNull OnlineUser user, public final CompletableFuture<TeleportResult> randomlyTeleportPlayer(@NotNull OnlineUser user,
final boolean timedTeleport, final boolean timedTeleport,
@NotNull String... rtpArgs) { @NotNull String... rtpArgs) {
return CompletableFuture.supplyAsync(() -> plugin.getRandomTeleportEngine() return plugin.supplyAsync(() -> plugin.getRandomTeleportEngine()
.getRandomPosition(user.getPosition().world, rtpArgs) .getRandomPosition(user.getPosition().world, rtpArgs)
.thenApply(position -> { .map(position -> {
if (position.isPresent()) {
final TeleportBuilder builder = Teleport.builder(plugin, user) final TeleportBuilder builder = Teleport.builder(plugin, user)
.setTarget(position.get()); .setTarget(position);
return timedTeleport return timedTeleport
? builder.toTimedTeleport() ? builder.toTimedTeleport()
.thenApplyAsync(teleport -> teleport.execute().join().getState()).join() .thenApplyAsync(teleport -> teleport.execute().join().getState()).join()
: builder.toTeleport() : builder.toTeleport()
.thenApplyAsync(teleport -> teleport.execute().join().getState()).join(); .thenApplyAsync(teleport -> teleport.execute().join().getState()).join();
} else {
return TeleportResult.CANCELLED; })
} .orElse(TeleportResult.CANCELLED));
}).join());
} }
/** /**
@@ -68,7 +68,7 @@ public class DelHomeCommand extends CommandBase implements TabCompletable {
*/ */
private void deletePlayerHome(@NotNull OnlineUser deleter, @NotNull User homeOwner, @NotNull String homeName, private void deletePlayerHome(@NotNull OnlineUser deleter, @NotNull User homeOwner, @NotNull String homeName,
final boolean delHomeAllConfirm) { final boolean delHomeAllConfirm) {
plugin.getSavedPositionManager().deleteHome(homeOwner, homeName).thenAccept(deleted -> { plugin.getManager().deleteHome(homeOwner, homeName).thenAccept(deleted -> {
if (deleter.equals(homeOwner)) { if (deleter.equals(homeOwner)) {
if (deleted) { if (deleted) {
plugin.getLocales().getLocale("home_deleted", homeName).ifPresent(deleter::sendMessage); plugin.getLocales().getLocale("home_deleted", homeName).ifPresent(deleter::sendMessage);
@@ -108,7 +108,7 @@ public class DelHomeCommand extends CommandBase implements TabCompletable {
return; return;
} }
plugin.getSavedPositionManager().deleteAllHomes(homeOwner).thenAccept(deleted -> { plugin.getManager().deleteAllHomes(homeOwner).thenAccept(deleted -> {
if (deleted == 0) { if (deleted == 0) {
plugin.getLocales().getLocale("error_no_warps_set") plugin.getLocales().getLocale("error_no_warps_set")
.ifPresent(deleter::sendMessage); .ifPresent(deleter::sendMessage);
@@ -26,7 +26,7 @@ public class DelWarpCommand extends CommandBase implements TabCompletable {
if (args.length <= 2) { if (args.length <= 2) {
final String warpName = args[0]; final String warpName = args[0];
final boolean confirm = args.length == 2 && args[1].equalsIgnoreCase("confirm"); final boolean confirm = args.length == 2 && args[1].equalsIgnoreCase("confirm");
plugin.getSavedPositionManager().deleteWarp(warpName).thenAccept(deleted -> { plugin.getManager().deleteWarp(warpName).thenAccept(deleted -> {
if (deleted) { if (deleted) {
plugin.getLocales().getLocale("warp_deleted", warpName) plugin.getLocales().getLocale("warp_deleted", warpName)
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
@@ -59,7 +59,7 @@ public class DelWarpCommand extends CommandBase implements TabCompletable {
return; return;
} }
plugin.getSavedPositionManager().deleteAllWarps().thenAccept(deleted -> { plugin.getManager().deleteAllWarps().thenAccept(deleted -> {
if (deleted == 0) { if (deleted == 0) {
plugin.getLocales().getLocale("error_no_warps_set") plugin.getLocales().getLocale("error_no_warps_set")
.ifPresent(deleter::sendMessage); .ifPresent(deleter::sendMessage);
@@ -116,7 +116,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
final String oldHomeName = home.meta.name; final String oldHomeName = home.meta.name;
final String newHomeName = editArgs; final String newHomeName = editArgs;
plugin.getSavedPositionManager().updateHomeMeta(home, new PositionMeta(newHomeName, home.meta.description)) plugin.getManager().updateHomeMeta(home, new PositionMeta(newHomeName, home.meta.description))
.thenAccept(renameResult -> (switch (renameResult.resultType()) { .thenAccept(renameResult -> (switch (renameResult.resultType()) {
case SUCCESS -> { case SUCCESS -> {
if (home.owner.equals(editor)) { if (home.owner.equals(editor)) {
@@ -137,7 +137,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
final String oldHomeDescription = home.meta.description; final String oldHomeDescription = home.meta.description;
final String newDescription = editArgs != null ? editArgs : ""; final String newDescription = editArgs != null ? editArgs : "";
plugin.getSavedPositionManager().updateHomeMeta(home, new PositionMeta(home.meta.name, newDescription)) plugin.getManager().updateHomeMeta(home, new PositionMeta(home.meta.name, newDescription))
.thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) { .thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) {
case SUCCESS -> { case SUCCESS -> {
if (home.owner.equals(editor)) { if (home.owner.equals(editor)) {
@@ -165,7 +165,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
}).ifPresent(editor::sendMessage)); }).ifPresent(editor::sendMessage));
} }
case "relocate" -> case "relocate" ->
plugin.getSavedPositionManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> { plugin.getManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> {
if (home.owner.equals(editor)) { if (home.owner.equals(editor)) {
editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location", editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location",
home.meta.name).orElse(new MineDown(""))); home.meta.name).orElse(new MineDown("")));
@@ -216,8 +216,8 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
// Check against maximum public homes // Check against maximum public homes
final List<Home> existingPublicHomes = editorHomes.stream() final List<Home> existingPublicHomes = editorHomes.stream()
.filter(existingHome -> existingHome.isPublic).toList(); .filter(existingHome -> existingHome.isPublic).toList();
final int maxPublicHomes = editor.getMaxPublicHomes(plugin.getSettings().maxPublicHomes, final int maxPublicHomes = editor.getMaxPublicHomes(plugin.getSettings().getMaxPublicHomes(),
plugin.getSettings().stackPermissionLimits); plugin.getSettings().doStackPermissionLimits());
if (existingPublicHomes.size() >= maxPublicHomes) { if (existingPublicHomes.size() >= maxPublicHomes) {
plugin.getLocales().getLocale("error_edit_home_maximum_public_homes", plugin.getLocales().getLocale("error_edit_home_maximum_public_homes",
Integer.toString(maxPublicHomes)) Integer.toString(maxPublicHomes))
@@ -232,7 +232,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
} }
// Execute the update // Execute the update
plugin.getSavedPositionManager().updateHomePrivacy(home, newIsPublic.get()).thenRun(() -> { plugin.getManager().updateHomePrivacy(home, newIsPublic.get()).thenRun(() -> {
if (home.owner.equals(editor)) { if (home.owner.equals(editor)) {
editor.sendMessage(plugin.getLocales().getLocale( editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success", "edit_home_privacy_" + privacyKeyedString + "_success",
@@ -313,7 +313,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
.ifPresent(this::add); .ifPresent(this::add);
} }
if (!plugin.getSettings().crossServer) { if (!plugin.getSettings().isCrossServer()) {
plugin.getLocales().getLocale("edit_home_menu_world", home.world.name) plugin.getLocales().getLocale("edit_home_menu_world", home.world.name)
.ifPresent(this::add); .ifPresent(this::add);
} else { } else {
@@ -85,7 +85,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
final String oldWarpName = warp.meta.name; final String oldWarpName = warp.meta.name;
final String newWarpName = editArgs; final String newWarpName = editArgs;
plugin.getSavedPositionManager().updateWarpMeta(warp, new PositionMeta(newWarpName, warp.meta.description)) plugin.getManager().updateWarpMeta(warp, new PositionMeta(newWarpName, warp.meta.description))
.thenAccept(renameResult -> (switch (renameResult.resultType()) { .thenAccept(renameResult -> (switch (renameResult.resultType()) {
case SUCCESS -> case SUCCESS ->
plugin.getLocales().getLocale("edit_warp_update_name", oldWarpName, newWarpName); plugin.getLocales().getLocale("edit_warp_update_name", oldWarpName, newWarpName);
@@ -99,7 +99,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
final String oldWarpDescription = warp.meta.description; final String oldWarpDescription = warp.meta.description;
final String newDescription = editArgs != null ? editArgs : ""; final String newDescription = editArgs != null ? editArgs : "";
plugin.getSavedPositionManager().updateWarpMeta(warp, new PositionMeta(warp.meta.name, newDescription)) plugin.getManager().updateWarpMeta(warp, new PositionMeta(warp.meta.name, newDescription))
.thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) { .thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) {
case SUCCESS -> plugin.getLocales().getLocale("edit_warp_update_description", case SUCCESS -> plugin.getLocales().getLocale("edit_warp_update_description",
warp.meta.name, warp.meta.name,
@@ -115,7 +115,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
}).ifPresent(editor::sendMessage)); }).ifPresent(editor::sendMessage));
} }
case "relocate" -> case "relocate" ->
plugin.getSavedPositionManager().updateWarpPosition(warp, editor.getPosition()).thenRun(() -> { plugin.getManager().updateWarpPosition(warp, editor.getPosition()).thenRun(() -> {
editor.sendMessage(plugin.getLocales().getLocale("edit_warp_update_location", editor.sendMessage(plugin.getLocales().getLocale("edit_warp_update_location",
warp.meta.name).orElse(new MineDown(""))); warp.meta.name).orElse(new MineDown("")));
@@ -175,7 +175,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
.ifPresent(this::add); .ifPresent(this::add);
} }
if (!plugin.getSettings().crossServer) { if (!plugin.getSettings().isCrossServer()) {
plugin.getLocales().getLocale("edit_warp_menu_world", warp.world.name).ifPresent(this::add); plugin.getLocales().getLocale("edit_warp_menu_world", warp.world.name).ifPresent(this::add);
} else { } else {
plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.world.name, warp.server.name).ifPresent(this::add); plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.world.name, warp.server.name).ifPresent(this::add);
@@ -36,7 +36,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
.setTarget(homes.get(0)) .setTarget(homes.get(0))
.toTimedTeleport().thenAccept(TimedTeleport::execute); .toTimedTeleport().thenAccept(TimedTeleport::execute);
default -> plugin.getCache().getHomeList(onlineUser, onlineUser, default -> plugin.getCache().getHomeList(onlineUser, onlineUser,
plugin.getLocales(), homes, plugin.getSettings().listItemsPerPage, 1) plugin.getLocales(), homes, plugin.getSettings().getListItemsPerPage(), 1)
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
} }
}); });
@@ -76,7 +76,7 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
} }
plugin.getCache().getHomeList(onlineUser, userData.user(), plugin.getCache().getHomeList(onlineUser, userData.user(),
plugin.getLocales(), homes, plugin.getLocales(), homes,
plugin.getSettings().listItemsPerPage, pageNumber) plugin.getSettings().getListItemsPerPage(), pageNumber)
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
}); });
}, () -> plugin.getLocales().getLocale("error_player_not_found", homeOwner).ifPresent(onlineUser::sendMessage))); }, () -> plugin.getLocales().getLocale("error_player_not_found", homeOwner).ifPresent(onlineUser::sendMessage)));
@@ -78,7 +78,7 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable,
} }
} }
onlineUser.sendMessage(plugin.getCache().getCommandList(onlineUser, onlineUser.sendMessage(plugin.getCache().getCommandList(onlineUser,
plugin.getLocales(), plugin.getCommands(), plugin.getSettings().listItemsPerPage, page)); plugin.getLocales(), plugin.getCommands(), plugin.getSettings().getListItemsPerPage(), page));
} }
case "reload" -> { case "reload" -> {
if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_RELOAD.node)) { if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_RELOAD.node)) {
@@ -37,7 +37,7 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
} }
plugin.getCache().getPublicHomeList(onlineUser, plugin.getLocales(), plugin.getCache().getPublicHomeList(onlineUser, plugin.getLocales(),
publicHomes, plugin.getSettings().listItemsPerPage, 1) publicHomes, plugin.getSettings().getListItemsPerPage(), 1)
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
}); });
case 1 -> { case 1 -> {
@@ -54,7 +54,7 @@ public class PublicHomeListCommand extends CommandBase implements ConsoleExecuta
} }
plugin.getCache().getPublicHomeList(onlineUser, plugin.getCache().getPublicHomeList(onlineUser,
plugin.getLocales(), publicHomes, plugin.getLocales(), publicHomes,
plugin.getSettings().listItemsPerPage, pageNumber) plugin.getSettings().getListItemsPerPage(), pageNumber)
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
}); });
@@ -41,7 +41,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
} }
final Position userPosition = target.getPosition(); final Position userPosition = target.getPosition();
final String[] rtpArguments = args.length >= 1 ? ArrayUtils.subarray(args, 1, args.length) : args; final String[] rtpArguments = args.length >= 1 ? ArrayUtils.subarray(args, 1, args.length) : args;
if (plugin.getSettings().rtpRestrictedWorlds.stream() if (plugin.getSettings().getRtpRestrictedWorlds().stream()
.anyMatch(worldName -> worldName.equals(userPosition.world.name))) { .anyMatch(worldName -> worldName.equals(userPosition.world.name))) {
plugin.getLocales().getLocale("error_rtp_restricted_world") plugin.getLocales().getLocale("error_rtp_restricted_world")
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
@@ -72,7 +72,8 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
// Get a random position and teleport // Get a random position and teleport
plugin.getLocales().getLocale("teleporting_random_generation") plugin.getLocales().getLocale("teleporting_random_generation")
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
plugin.getRandomTeleportEngine().getRandomPosition(onlineUser.getPosition().world, rtpArguments).thenAccept(position -> {
final Optional<Position> position = plugin.getRandomTeleportEngine().getRandomPosition(onlineUser.getPosition().world, rtpArguments);
if (position.isEmpty()) { if (position.isEmpty()) {
plugin.getLocales().getLocale("error_rtp_randomization_timeout") plugin.getLocales().getLocale("error_rtp_randomization_timeout")
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
@@ -91,11 +92,10 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
result.successful() && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) { result.successful() && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) {
plugin.getDatabase().updateUserData(new UserData(onlineUser, plugin.getDatabase().updateUserData(new UserData(onlineUser,
userData.get().homeSlots(), userData.get().ignoringTeleports(), userData.get().homeSlots(), userData.get().ignoringTeleports(),
Instant.now().plus(plugin.getSettings().rtpCooldownLength, ChronoUnit.MINUTES))); Instant.now().plus(plugin.getSettings().getRtpCooldownLength(), ChronoUnit.MINUTES)));
} }
})); }));
}); });
});
} }
@Override @Override
@@ -55,7 +55,7 @@ public class SetHomeCommand extends CommandBase {
*/ */
private void setHome(@NotNull OnlineUser onlineUser, @NotNull String homeName, @NotNull List<Home> currentHomes) { private void setHome(@NotNull OnlineUser onlineUser, @NotNull String homeName, @NotNull List<Home> currentHomes) {
// Check against maximum homes // Check against maximum homes
final int maxHomes = onlineUser.getMaxHomes(plugin.getSettings().maxHomes, plugin.getSettings().stackPermissionLimits); final int maxHomes = onlineUser.getMaxHomes(plugin.getSettings().getMaxHomes(), plugin.getSettings().doStackPermissionLimits());
if (currentHomes.size() >= maxHomes) { if (currentHomes.size() >= maxHomes) {
plugin.getLocales().getLocale("error_set_home_maximum_homes", Integer.toString(maxHomes)) plugin.getLocales().getLocale("error_set_home_maximum_homes", Integer.toString(maxHomes))
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
@@ -67,9 +67,9 @@ public class SetHomeCommand extends CommandBase {
// Check against economy if needed // Check against economy if needed
final AtomicBoolean newSlotNeeded = new AtomicBoolean(false); final AtomicBoolean newSlotNeeded = new AtomicBoolean(false);
final AtomicReference<UserData> userDataToUpdate = new AtomicReference<>(null); final AtomicReference<UserData> userDataToUpdate = new AtomicReference<>(null);
if (plugin.getSettings().economy) { if (plugin.getSettings().isEconomy()) {
final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().freeHomeSlots, final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().getFreeHomeSlots(),
plugin.getSettings().stackPermissionLimits); plugin.getSettings().doStackPermissionLimits());
if (fetchedData.isPresent()) { if (fetchedData.isPresent()) {
final Settings.EconomyAction action = Settings.EconomyAction.ADDITIONAL_HOME_SLOT; final Settings.EconomyAction action = Settings.EconomyAction.ADDITIONAL_HOME_SLOT;
newSlotNeeded.set((currentHomes.size() + 1) > (freeHomes + fetchedData.get().homeSlots())); newSlotNeeded.set((currentHomes.size() + 1) > (freeHomes + fetchedData.get().homeSlots()));
@@ -95,7 +95,7 @@ public class SetHomeCommand extends CommandBase {
} }
// Set the home in the saved position manager // Set the home in the saved position manager
plugin.getSavedPositionManager() plugin.getManager()
.setHome(new PositionMeta(homeName, ""), onlineUser, onlineUser.getPosition()) .setHome(new PositionMeta(homeName, ""), onlineUser, onlineUser.getPosition())
.thenAccept(setResult -> { .thenAccept(setResult -> {
// Display feedback of the result of the set operation // Display feedback of the result of the set operation
@@ -4,13 +4,9 @@ import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta; import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.util.Permission; import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public class SetSpawnCommand extends CommandBase { public class SetSpawnCommand extends CommandBase {
protected SetSpawnCommand(@NotNull HuskHomes implementor) { protected SetSpawnCommand(@NotNull HuskHomes implementor) {
@@ -26,12 +22,12 @@ public class SetSpawnCommand extends CommandBase {
} }
final Position position = onlineUser.getPosition(); final Position position = onlineUser.getPosition();
if (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn) { if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalSpawn()) {
plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).thenApply(warp -> { plugin.getDatabase().getWarp(plugin.getSettings().getGlobalSpawnName()).thenApply(warp -> {
if (warp.isPresent()) { if (warp.isPresent()) {
return plugin.getSavedPositionManager().updateWarpPosition(warp.get(), position); return plugin.getManager().updateWarpPosition(warp.get(), position);
} else { } else {
return plugin.getSavedPositionManager().setWarp(new PositionMeta(plugin.getSettings().globalSpawnName, return plugin.getManager().setWarp(new PositionMeta(plugin.getSettings().getGlobalSpawnName(),
plugin.getLocales().getRawLocale("spawn_warp_default_description").orElse("")), position) plugin.getLocales().getRawLocale("spawn_warp_default_description").orElse("")), position)
.thenApply(result -> result.resultType().successful); .thenApply(result -> result.resultType().successful);
} }
@@ -23,7 +23,7 @@ public class SetWarpCommand extends CommandBase {
} }
private void setWarp(@NotNull OnlineUser onlineUser, @NotNull String warpName) { private void setWarp(@NotNull OnlineUser onlineUser, @NotNull String warpName) {
plugin.getSavedPositionManager().setWarp( plugin.getManager().setWarp(
new PositionMeta(warpName, ""), onlineUser.getPosition()).thenAccept(setResult -> new PositionMeta(warpName, ""), onlineUser.getPosition()).thenAccept(setResult ->
(switch (setResult.resultType()) { (switch (setResult.resultType()) {
case SUCCESS -> { case SUCCESS -> {
@@ -2,11 +2,14 @@ package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TimedTeleport; import net.william278.huskhomes.teleport.TimedTeleport;
import net.william278.huskhomes.util.Permission; import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Optional;
public class SpawnCommand extends CommandBase { public class SpawnCommand extends CommandBase {
protected SpawnCommand(@NotNull HuskHomes implementor) { protected SpawnCommand(@NotNull HuskHomes implementor) {
@@ -21,15 +24,15 @@ public class SpawnCommand extends CommandBase {
return; return;
} }
plugin.getSpawn().thenAccept(position -> { final Optional<? extends Position> spawn = plugin.getSpawn();
if (position.isEmpty()) { if (spawn.isEmpty()) {
plugin.getLocales().getLocale("error_spawn_not_set") plugin.getLocales().getLocale("error_spawn_not_set")
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
return; return;
} }
Teleport.builder(plugin, onlineUser) Teleport.builder(plugin, onlineUser)
.setTarget(position.get()) .setTarget(spawn.get())
.toTimedTeleport().thenAccept(TimedTeleport::execute); .toTimedTeleport()
}); .thenAccept(TimedTeleport::execute);
} }
} }
@@ -24,7 +24,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
switch (args.length) { switch (args.length) {
case 0 -> plugin.getDatabase().getWarps() case 0 -> plugin.getDatabase().getWarps()
.thenApply(warps -> warps.stream() .thenApply(warps -> warps.stream()
.filter(warp -> warp.hasPermission(plugin.getSettings().permissionRestrictWarps, onlineUser)) .filter(warp -> warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), onlineUser))
.collect(Collectors.toList())) .collect(Collectors.toList()))
.thenAccept(warps -> { .thenAccept(warps -> {
if (warps.isEmpty()) { if (warps.isEmpty()) {
@@ -33,7 +33,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
return; return;
} }
plugin.getCache().getWarpList(onlineUser, plugin.getLocales(), warps, plugin.getCache().getWarpList(onlineUser, plugin.getLocales(), warps,
plugin.getSettings().listItemsPerPage, 1) plugin.getSettings().getListItemsPerPage(), 1)
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
}); });
case 1 -> { case 1 -> {
@@ -42,7 +42,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
.getWarp(warpName) .getWarp(warpName)
.thenAccept(warpResult -> warpResult.ifPresentOrElse(warp -> { .thenAccept(warpResult -> warpResult.ifPresentOrElse(warp -> {
// Handle permission restrictions // Handle permission restrictions
if (!warp.hasPermission(plugin.getSettings().permissionRestrictWarps, onlineUser)) { if (!warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), onlineUser)) {
plugin.getLocales().getLocale("error_no_permission") plugin.getLocales().getLocale("error_no_permission")
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
return; return;
@@ -64,7 +64,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
@Override @Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) { public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return plugin.getCache().warps.stream() return plugin.getCache().warps.stream()
.filter(s -> user == null || Warp.hasPermission(plugin.getSettings().permissionRestrictWarps, user, s)) .filter(s -> user == null || Warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), user, s))
.filter(s -> s.toLowerCase().startsWith(args.length >= 1 ? args[0].toLowerCase() : "")) .filter(s -> s.toLowerCase().startsWith(args.length >= 1 ? args[0].toLowerCase() : ""))
.sorted() .sorted()
.collect(Collectors.toList()); .collect(Collectors.toList());
@@ -48,7 +48,7 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable {
// Dispatch the warp list event // Dispatch the warp list event
plugin.getDatabase().getWarps() plugin.getDatabase().getWarps()
.thenApply(warps -> warps.stream() .thenApply(warps -> warps.stream()
.filter(warp -> warp.hasPermission(plugin.getSettings().permissionRestrictWarps, onlineUser)) .filter(warp -> warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), onlineUser))
.collect(Collectors.toList())) .collect(Collectors.toList()))
.thenAccept(warps -> { .thenAccept(warps -> {
if (warps.isEmpty()) { if (warps.isEmpty()) {
@@ -56,7 +56,7 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable {
return; return;
} }
plugin.getCache().getWarpList(onlineUser, plugin.getLocales(), warps, plugin.getCache().getWarpList(onlineUser, plugin.getLocales(), warps,
plugin.getSettings().listItemsPerPage, pageNumber) plugin.getSettings().getListItemsPerPage(), pageNumber)
.ifPresent(onlineUser::sendMessage); .ifPresent(onlineUser::sendMessage);
}); });
} }
@@ -25,56 +25,57 @@ import java.util.Optional;
public class Settings { public class Settings {
// Top-level settings // Top-level settings
public String language = "en-gb"; @YamlKey("language")
private String language = "en-gb";
@YamlKey("check_for_updates") @YamlKey("check_for_updates")
public boolean checkForUpdates = true; private boolean checkForUpdates = true;
@YamlKey("debug_logging") @YamlKey("debug_logging")
public boolean debugLogging = false; private boolean debugLogging = false;
// Database settings // Database settings
@YamlComment("Database connection settings") @YamlComment("Database connection settings")
@YamlKey("database.type") @YamlKey("database.type")
public DatabaseType databaseType = DatabaseType.SQLITE; private DatabaseType databaseType = DatabaseType.SQLITE;
@YamlKey("database.mysql.credentials.host") @YamlKey("database.mysql.credentials.host")
public String mySqlHost = "localhost"; private String mySqlHost = "localhost";
@YamlKey("database.mysql.credentials.port") @YamlKey("database.mysql.credentials.port")
public int mySqlPort = 3306; private int mySqlPort = 3306;
@YamlKey("database.mysql.credentials.database") @YamlKey("database.mysql.credentials.database")
public String mySqlDatabase = "HuskHomes"; private String mySqlDatabase = "HuskHomes";
@YamlKey("database.mysql.credentials.username") @YamlKey("database.mysql.credentials.username")
public String mySqlUsername = "root"; private String mySqlUsername = "root";
@YamlKey("database.mysql.credentials.password") @YamlKey("database.mysql.credentials.password")
public String mySqlPassword = "pa55w0rd"; private String mySqlPassword = "pa55w0rd";
@YamlKey("database.mysql.credentials.parameters") @YamlKey("database.mysql.credentials.parameters")
public String mySqlConnectionParameters = "?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8"; private String mySqlConnectionParameters = "?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8";
@YamlComment("MySQL connection pool properties") @YamlComment("MySQL connection pool properties")
@YamlKey("database.mysql.connection_pool.size") @YamlKey("database.mysql.connection_pool.size")
public int mySqlConnectionPoolSize = 12; private int mySqlConnectionPoolSize = 12;
@YamlKey("database.mysql.connection_pool.idle") @YamlKey("database.mysql.connection_pool.idle")
public int mySqlConnectionPoolIdle = 12; private int mySqlConnectionPoolIdle = 12;
@YamlKey("database.mysql.connection_pool.lifetime") @YamlKey("database.mysql.connection_pool.lifetime")
public long mySqlConnectionPoolLifetime = 1800000; private long mySqlConnectionPoolLifetime = 1800000;
@YamlKey("database.mysql.connection_pool.keepalive") @YamlKey("database.mysql.connection_pool.keepalive")
public long mySqlConnectionPoolKeepAlive = 30000; private long mySqlConnectionPoolKeepAlive = 30000;
@YamlKey("database.mysql.connection_pool.timeout") @YamlKey("database.mysql.connection_pool.timeout")
public long mySqlConnectionPoolTimeout = 20000; private long mySqlConnectionPoolTimeout = 20000;
@YamlKey("database.table_names") @YamlKey("database.table_names")
public Map<String, String> tableNames = Map.of( private Map<String, String> tableNames = Map.of(
TableName.PLAYER_DATA.name().toLowerCase(), TableName.PLAYER_DATA.defaultName, TableName.PLAYER_DATA.name().toLowerCase(), TableName.PLAYER_DATA.defaultName,
TableName.POSITION_DATA.name().toLowerCase(), TableName.POSITION_DATA.defaultName, TableName.POSITION_DATA.name().toLowerCase(), TableName.POSITION_DATA.defaultName,
TableName.SAVED_POSITION_DATA.name().toLowerCase(), TableName.SAVED_POSITION_DATA.defaultName, TableName.SAVED_POSITION_DATA.name().toLowerCase(), TableName.SAVED_POSITION_DATA.defaultName,
@@ -85,142 +86,142 @@ public class Settings {
@NotNull @NotNull
public String getTableName(@NotNull TableName tableName) { public String getTableName(@NotNull TableName tableName) {
return Optional.ofNullable(tableNames.get(tableName.name().toLowerCase())).orElse(tableName.defaultName); return Optional.ofNullable(getTableNames().get(tableName.name().toLowerCase())).orElse(tableName.defaultName);
} }
// General settings // General settings
@YamlComment("General plugin settings") @YamlComment("General plugin settings")
@YamlKey("general.max_homes") @YamlKey("general.max_homes")
public int maxHomes = 10; private int maxHomes = 10;
@YamlKey("general.max_public_homes") @YamlKey("general.max_public_homes")
public int maxPublicHomes = 10; private int maxPublicHomes = 10;
@YamlKey("general.stack_permission_limits") @YamlKey("general.stack_permission_limits")
public boolean stackPermissionLimits = true; private boolean stackPermissionLimits = true;
@YamlKey("general.permission_restrict_warps") @YamlKey("general.permission_restrict_warps")
public boolean permissionRestrictWarps = false; private boolean permissionRestrictWarps = false;
@YamlKey("general.overwrite_existing_homes_warps") @YamlKey("general.overwrite_existing_homes_warps")
public boolean overwriteExistingHomesWarps = true; private boolean overwriteExistingHomesWarps = true;
@YamlKey("general.teleport_warmup_time") @YamlKey("general.teleport_warmup_time")
public int teleportWarmupTime = 5; private int teleportWarmupTime = 5;
@YamlKey("general.teleport_warmup_display") @YamlKey("general.teleport_warmup_display")
public MessageDisplayType teleportWarmupDisplay = MessageDisplayType.ACTION_BAR; private MessageDisplayType teleportWarmupDisplay = MessageDisplayType.ACTION_BAR;
@YamlKey("general.teleport_request_expiry_time") @YamlKey("general.teleport_request_expiry_time")
public int teleportRequestExpiryTime = 60; private int teleportRequestExpiryTime = 60;
@YamlKey("general.strict_tpa_here_requests") @YamlKey("general.strict_tpa_here_requests")
public boolean strictTpaHereRequests = true; private boolean strictTpaHereRequests = true;
@YamlKey("general.allow_unicode_names") @YamlKey("general.allow_unicode_names")
public boolean allowUnicodeNames = false; private boolean allowUnicodeNames = false;
@YamlKey("general.allow_unicode_descriptions") @YamlKey("general.allow_unicode_descriptions")
public boolean allowUnicodeDescriptions = true; private boolean allowUnicodeDescriptions = true;
@YamlKey("general.back_command_return_by_death") @YamlKey("general.back_command_return_by_death")
public boolean backCommandReturnByDeath = true; private boolean backCommandReturnByDeath = true;
@YamlKey("general.back_command_save_teleport_event") @YamlKey("general.back_command_save_teleport_event")
public boolean backCommandSaveOnTeleportEvent = false; private boolean backCommandSaveOnTeleportEvent = false;
@YamlKey("general.list_items_per_page") @YamlKey("general.list_items_per_page")
public int listItemsPerPage = 12; private int listItemsPerPage = 12;
@YamlKey("general.asynchronous_teleports") @YamlKey("general.asynchronous_teleports")
public boolean asynchronousTeleports = true; private boolean asynchronousTeleports = true;
@YamlKey("general.play_sound_effects") @YamlKey("general.play_sound_effects")
public boolean playSoundEffects = true; private boolean playSoundEffects = true;
@YamlKey("general.sound_effects") @YamlKey("general.sound_effects")
public Map<String, String> soundEffects = Map.of( private Map<String, String> soundEffects = Map.of(
SoundEffectAction.TELEPORTATION_COMPLETE.name().toLowerCase(), SoundEffectAction.TELEPORTATION_COMPLETE.defaultSoundEffect, SoundEffectAction.TELEPORTATION_COMPLETE.name().toLowerCase(), SoundEffectAction.TELEPORTATION_COMPLETE.defaultSoundEffect,
SoundEffectAction.TELEPORTATION_WARMUP.name().toLowerCase(), SoundEffectAction.TELEPORTATION_WARMUP.defaultSoundEffect, SoundEffectAction.TELEPORTATION_WARMUP.name().toLowerCase(), SoundEffectAction.TELEPORTATION_WARMUP.defaultSoundEffect,
SoundEffectAction.TELEPORTATION_CANCELLED.name().toLowerCase(), SoundEffectAction.TELEPORTATION_CANCELLED.defaultSoundEffect SoundEffectAction.TELEPORTATION_CANCELLED.name().toLowerCase(), SoundEffectAction.TELEPORTATION_CANCELLED.defaultSoundEffect
); );
public Optional<String> getSoundEffect(@NotNull SoundEffectAction action) { public Optional<String> getSoundEffect(@NotNull SoundEffectAction action) {
if (!playSoundEffects) { if (!isPlaySoundEffects()) {
return Optional.empty(); return Optional.empty();
} }
return Optional.ofNullable(soundEffects.get(action.name().toLowerCase())); return Optional.ofNullable(getSoundEffects().get(action.name().toLowerCase()));
} }
// Cross-server settings // Cross-server settings
@YamlComment("Enable teleporting across proxied servers. Requires MySQL") @YamlComment("Enable teleporting across proxied servers. Requires MySQL")
@YamlKey("cross_server.enabled") @YamlKey("cross_server.enabled")
public boolean crossServer = false; private boolean crossServer = false;
@YamlKey("cross_server.messenger_type") @YamlKey("cross_server.messenger_type")
public MessengerType messengerType = MessengerType.PLUGIN_MESSAGE; private MessengerType messengerType = MessengerType.PLUGIN_MESSAGE;
@YamlKey("cross_server.cluster_id") @YamlKey("cross_server.cluster_id")
public String clusterId = ""; private String clusterId = "";
@YamlKey("cross_server.global_spawn.enabled") @YamlKey("cross_server.global_spawn.enabled")
public boolean globalSpawn = false; private boolean globalSpawn = false;
@YamlKey("cross_server.global_spawn.warp_name") @YamlKey("cross_server.global_spawn.warp_name")
public String globalSpawnName = "Spawn"; private String globalSpawnName = "Spawn";
@YamlKey("cross_server.global_respawning") @YamlKey("cross_server.global_respawning")
public boolean globalRespawning = false; private boolean globalRespawning = false;
@YamlKey("cross_server.redis_credentials.host") @YamlKey("cross_server.redis_credentials.host")
public String redisHost = "localhost"; private String redisHost = "localhost";
@YamlKey("cross_server.redis_credentials.port") @YamlKey("cross_server.redis_credentials.port")
public int redisPort = 6379; private int redisPort = 6379;
@YamlKey("cross_server.redis_credentials.password") @YamlKey("cross_server.redis_credentials.password")
public String redisPassword = ""; private String redisPassword = "";
@YamlKey("cross_server.redis_credentials.use_ssl") @YamlKey("cross_server.redis_credentials.use_ssl")
public boolean redisUseSsl = false; private boolean redisUseSsl = false;
// Rtp command settings // Rtp command settings
@YamlComment("Random teleport (/rtp) command settings") @YamlComment("Random teleport (/rtp) command settings")
@YamlKey("rtp.cooldown_length") @YamlKey("rtp.cooldown_length")
public int rtpCooldownLength = 10; private int rtpCooldownLength = 10;
@YamlKey("rtp.radius") @YamlKey("rtp.radius")
public int rtpRadius = 5000; private int rtpRadius = 5000;
@YamlKey("rtp.spawn_radius") @YamlKey("rtp.spawn_radius")
public int rtpSpawnRadius = 500; private int rtpSpawnRadius = 500;
@YamlKey("rtp.distribution_mean") @YamlKey("rtp.distribution_mean")
public float rtpDistributionMean = 0.75f; private float rtpDistributionMean = 0.75f;
@YamlKey("rtp.distribution_deviation") @YamlKey("rtp.distribution_deviation")
public float rtpDistributionStandardDeviation = 2f; private float rtpDistributionStandardDeviation = 2f;
@YamlKey("rtp.restricted_worlds") @YamlKey("rtp.restricted_worlds")
public List<String> rtpRestrictedWorlds = List.of("world_nether", "world_the_end"); private List<String> rtpRestrictedWorlds = List.of("world_nether", "world_the_end");
// Economy settings // Economy settings
@YamlComment("Charge for certain actions (requires Vault)") @YamlComment("Charge for certain actions (requires Vault)")
@YamlKey("economy.enabled") @YamlKey("economy.enabled")
public boolean economy = false; private boolean economy = false;
@YamlComment("Use this currency for payments (works only with RedisEconomy), defaults to Vault currency") @YamlComment("Use this currency for payments (works only with RedisEconomy), defaults to Vault currency")
@YamlKey("economy.redis_economy_name") @YamlKey("economy.redis_economy_name")
public String redisEconomyName = "vault"; private String redisEconomyName = "vault";
@YamlKey("economy.free_home_slots") @YamlKey("economy.free_home_slots")
public int freeHomeSlots = 5; private int freeHomeSlots = 5;
@YamlKey("economy.costs") @YamlKey("economy.costs")
public Map<String, Double> economyCosts = Map.of( private Map<String, Double> economyCosts = Map.of(
EconomyAction.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyAction.ADDITIONAL_HOME_SLOT.defaultCost, EconomyAction.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyAction.ADDITIONAL_HOME_SLOT.defaultCost,
EconomyAction.MAKE_HOME_PUBLIC.name().toLowerCase(), EconomyAction.MAKE_HOME_PUBLIC.defaultCost, EconomyAction.MAKE_HOME_PUBLIC.name().toLowerCase(), EconomyAction.MAKE_HOME_PUBLIC.defaultCost,
EconomyAction.RANDOM_TELEPORT.name().toLowerCase(), EconomyAction.RANDOM_TELEPORT.defaultCost, EconomyAction.RANDOM_TELEPORT.name().toLowerCase(), EconomyAction.RANDOM_TELEPORT.defaultCost,
@@ -228,10 +229,10 @@ public class Settings {
); );
public Optional<Double> getEconomyCost(@NotNull EconomyAction action) { public Optional<Double> getEconomyCost(@NotNull EconomyAction action) {
if (!economy) { if (!isEconomy()) {
return Optional.empty(); return Optional.empty();
} }
final Double cost = economyCosts.get(action.name().toLowerCase()); final Double cost = getEconomyCosts().get(action.name().toLowerCase());
if (cost != null && cost > 0d) { if (cost != null && cost > 0d) {
return Optional.of(cost); return Optional.of(cost);
} }
@@ -241,25 +242,257 @@ public class Settings {
// Mapping plugins // Mapping plugins
@YamlComment("Display public homes/warps on web maps (DYNMAP, BLUEMAP)") @YamlComment("Display public homes/warps on web maps (DYNMAP, BLUEMAP)")
@YamlKey("map_hook.enabled") @YamlKey("map_hook.enabled")
public boolean doMapHook = false; private boolean doMapHook = false;
@YamlKey("map_hook.map_plugin") @YamlKey("map_hook.map_plugin")
public MappingPlugin mappingPlugin = MappingPlugin.DYNMAP; private MappingPlugin mappingPlugin = MappingPlugin.DYNMAP;
@YamlKey("map_hook.show_public_homes") @YamlKey("map_hook.show_public_homes")
public boolean publicHomesOnMap = true; private boolean publicHomesOnMap = true;
@YamlKey("map_hook.show_warps") @YamlKey("map_hook.show_warps")
public boolean warpsOnMap = true; private boolean warpsOnMap = true;
// Disabled commands // Disabled commands
@YamlComment("Disabled commands (e.g. ['/home', '/warp'] to disable /home and /warp)") @YamlComment("Disabled commands (e.g. ['/home', '/warp'] to disable /home and /warp)")
@YamlKey("disabled_commands") @YamlKey("disabled_commands")
public List<String> disabledCommands = Collections.emptyList(); private List<String> disabledCommands = Collections.emptyList();
@SuppressWarnings("unused") @SuppressWarnings("unused")
public Settings() { private Settings() {
}
public String getLanguage() {
return language;
}
public boolean doCheckForUpdates() {
return checkForUpdates;
}
public boolean doDebugLogging() {
return debugLogging;
}
public DatabaseType getDatabaseType() {
return databaseType;
}
public String getMySqlHost() {
return mySqlHost;
}
public int getMySqlPort() {
return mySqlPort;
}
public String getMySqlDatabase() {
return mySqlDatabase;
}
public String getMySqlUsername() {
return mySqlUsername;
}
public String getMySqlPassword() {
return mySqlPassword;
}
public String getMySqlConnectionParameters() {
return mySqlConnectionParameters;
}
public int getMySqlConnectionPoolSize() {
return mySqlConnectionPoolSize;
}
public int getMySqlConnectionPoolIdle() {
return mySqlConnectionPoolIdle;
}
public long getMySqlConnectionPoolLifetime() {
return mySqlConnectionPoolLifetime;
}
public long getMySqlConnectionPoolKeepAlive() {
return mySqlConnectionPoolKeepAlive;
}
public long getMySqlConnectionPoolTimeout() {
return mySqlConnectionPoolTimeout;
}
public Map<String, String> getTableNames() {
return tableNames;
}
public int getMaxHomes() {
return maxHomes;
}
public int getMaxPublicHomes() {
return maxPublicHomes;
}
public boolean doStackPermissionLimits() {
return stackPermissionLimits;
}
public boolean isPermissionRestrictWarps() {
return permissionRestrictWarps;
}
public boolean isOverwriteExistingHomesWarps() {
return overwriteExistingHomesWarps;
}
public int getTeleportWarmupTime() {
return teleportWarmupTime;
}
public MessageDisplayType getTeleportWarmupDisplay() {
return teleportWarmupDisplay;
}
public int getTeleportRequestExpiryTime() {
return teleportRequestExpiryTime;
}
public boolean isStrictTpaHereRequests() {
return strictTpaHereRequests;
}
public boolean isAllowUnicodeNames() {
return allowUnicodeNames;
}
public boolean isAllowUnicodeDescriptions() {
return allowUnicodeDescriptions;
}
public boolean isBackCommandReturnByDeath() {
return backCommandReturnByDeath;
}
public boolean isBackCommandSaveOnTeleportEvent() {
return backCommandSaveOnTeleportEvent;
}
public int getListItemsPerPage() {
return listItemsPerPage;
}
public boolean isAsynchronousTeleports() {
return asynchronousTeleports;
}
public boolean isPlaySoundEffects() {
return playSoundEffects;
}
public Map<String, String> getSoundEffects() {
return soundEffects;
}
public boolean isCrossServer() {
return crossServer;
}
public MessengerType getMessengerType() {
return messengerType;
}
public String getClusterId() {
return clusterId;
}
public boolean isGlobalSpawn() {
return globalSpawn;
}
public String getGlobalSpawnName() {
return globalSpawnName;
}
public boolean isGlobalRespawning() {
return globalRespawning;
}
public String getRedisHost() {
return redisHost;
}
public int getRedisPort() {
return redisPort;
}
public String getRedisPassword() {
return redisPassword;
}
public boolean isRedisUseSsl() {
return redisUseSsl;
}
public int getRtpCooldownLength() {
return rtpCooldownLength;
}
public int getRtpRadius() {
return rtpRadius;
}
public int getRtpSpawnRadius() {
return rtpSpawnRadius;
}
public float getRtpDistributionMean() {
return rtpDistributionMean;
}
public float getRtpDistributionStandardDeviation() {
return rtpDistributionStandardDeviation;
}
public List<String> getRtpRestrictedWorlds() {
return rtpRestrictedWorlds;
}
public boolean isEconomy() {
return economy;
}
public String getRedisEconomyName() {
return redisEconomyName;
}
public int getFreeHomeSlots() {
return freeHomeSlots;
}
public Map<String, Double> getEconomyCosts() {
return economyCosts;
}
public boolean isDoMapHook() {
return doMapHook;
}
public MappingPlugin getMappingPlugin() {
return mappingPlugin;
}
public boolean isPublicHomesOnMap() {
return publicHomesOnMap;
}
public boolean isWarpsOnMap() {
return warpsOnMap;
}
public List<String> getDisabledCommands() {
return disabledCommands;
} }
/** /**
@@ -17,7 +17,6 @@ import java.nio.charset.StandardCharsets;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@@ -167,7 +166,7 @@ public abstract class Database {
/** /**
* Initialize the database and ensure tables are present; create tables if they do not exist. * Initialize the database and ensure tables are present; create tables if they do not exist.
* *
* @return A future returning void when complete * @return {@code true} if done successfully
*/ */
public abstract boolean initialize(); public abstract boolean initialize();
@@ -175,9 +174,8 @@ public abstract class Database {
* Execute a MySQL script file read as an InputStream * Execute a MySQL script file read as an InputStream
* *
* @param inputStream The input stream to read the script from * @param inputStream The input stream to read the script from
* @return A future returning void when complete
*/ */
public abstract CompletableFuture<Void> runScript(@NotNull InputStream inputStream, public abstract void runScript(@NotNull InputStream inputStream,
@NotNull Map<String, String> replacements); @NotNull Map<String, String> replacements);
/** /**
@@ -224,9 +222,8 @@ public abstract class Database {
* Ensure a {@link User} has a {@link UserData} entry in the database and that their username is up-to-date * Ensure a {@link User} has a {@link UserData} entry in the database and that their username is up-to-date
* *
* @param user The {@link User} to ensure * @param user The {@link User} to ensure
* @return A future returning void when complete
*/ */
public abstract CompletableFuture<Void> ensureUser(@NotNull User user); public abstract void ensureUser(@NotNull User user);
/** /**
* Get {@link UserData} for a user by their Minecraft username (<i>case-insensitive</i>) * Get {@link UserData} for a user by their Minecraft username (<i>case-insensitive</i>)
@@ -234,7 +231,7 @@ public abstract class Database {
* @param name Username of the {@link UserData} to get (<i>case-insensitive</i>) * @param name Username of the {@link UserData} to get (<i>case-insensitive</i>)
* @return A future returning an optional with the {@link UserData} present if they exist * @return A future returning an optional with the {@link UserData} present if they exist
*/ */
public abstract CompletableFuture<Optional<UserData>> getUserDataByName(@NotNull String name); public abstract Optional<UserData> getUserDataByName(@NotNull String name);
/** /**
* Get {@link UserData} for a user by their Minecraft account {@link UUID} * Get {@link UserData} for a user by their Minecraft account {@link UUID}
@@ -242,7 +239,7 @@ public abstract class Database {
* @param uuid Minecraft account {@link UUID} of the {@link UserData} to get * @param uuid Minecraft account {@link UUID} of the {@link UserData} to get
* @return A future returning an optional with the {@link UserData} present if they exist * @return A future returning an optional with the {@link UserData} present if they exist
*/ */
public abstract CompletableFuture<Optional<UserData>> getUserData(@NotNull UUID uuid); public abstract Optional<UserData> getUserData(@NotNull UUID uuid);
/** /**
@@ -251,14 +248,14 @@ public abstract class Database {
* @param user {@link User} to get the homes of * @param user {@link User} to get the homes of
* @return A future returning void when complete * @return A future returning void when complete
*/ */
public abstract CompletableFuture<List<Home>> getHomes(@NotNull User user); public abstract List<Home> getHomes(@NotNull User user);
/** /**
* Get a list of all {@link Warp}s that have been set * Get a list of all {@link Warp}s that have been set
* *
* @return A future returning a list containing all {@link Warp}s * @return A future returning a list containing all {@link Warp}s
*/ */
public abstract CompletableFuture<List<Warp>> getWarps(); public abstract List<Warp> getWarps();
/** /**
* Get a list of publicly-set {@link Warp}s on <i>this {@link Server}</i> * Get a list of publicly-set {@link Warp}s on <i>this {@link Server}</i>
@@ -267,16 +264,16 @@ public abstract class Database {
* @return A future returning a list containing all {@link Warp}s set on this server * @return A future returning a list containing all {@link Warp}s set on this server
* @implNote If the {@link Server} has not been initialized, this method will check against local world UUIDs * @implNote If the {@link Server} has not been initialized, this method will check against local world UUIDs
*/ */
public final CompletableFuture<List<Warp>> getLocalWarps(@NotNull HuskHomes plugin) { public final List<Warp> getLocalWarps(@NotNull HuskHomes plugin) {
try { try {
final Server server = plugin.getServerName(); final Server server = plugin.getServerName();
return getWarps().thenApplyAsync(warps -> warps.stream() return getWarps().stream()
.filter(warp -> warp.server.equals(server)) .filter(warp -> warp.server.equals(server))
.collect(Collectors.toList())); .collect(Collectors.toList());
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
return getWarps().thenApplyAsync(warps -> warps.stream() return getWarps().stream()
.filter(warp -> plugin.getWorlds().stream().anyMatch(world -> world.equals(warp.world))) .filter(warp -> plugin.getWorlds().stream().anyMatch(world -> world.equals(warp.world)))
.collect(Collectors.toList())); .collect(Collectors.toList());
} }
} }
@@ -285,7 +282,7 @@ public abstract class Database {
* *
* @return A future returning a list containing all publicly-set {@link Home}s * @return A future returning a list containing all publicly-set {@link Home}s
*/ */
public abstract CompletableFuture<List<Home>> getPublicHomes(); public abstract List<Home> getPublicHomes();
/** /**
* Get a list of publicly-set {@link Home}s on <i>this {@link Server}</i> * Get a list of publicly-set {@link Home}s on <i>this {@link Server}</i>
@@ -294,16 +291,16 @@ public abstract class Database {
* @return A future returning a list containing all publicly-set {@link Home}s on this server * @return A future returning a list containing all publicly-set {@link Home}s on this server
* @implNote If the {@link Server} has not been initialized, this method will check against local world UUIDs * @implNote If the {@link Server} has not been initialized, this method will check against local world UUIDs
*/ */
public final CompletableFuture<List<Home>> getLocalPublicHomes(@NotNull HuskHomes plugin) { public final List<Home> getLocalPublicHomes(@NotNull HuskHomes plugin) {
try { try {
final Server server = plugin.getServerName(); final Server server = plugin.getServerName();
return getPublicHomes().thenApplyAsync(homes -> homes.stream() return getPublicHomes().stream()
.filter(home -> home.server.equals(server)) .filter(home -> home.server.equals(server))
.collect(Collectors.toList())); .collect(Collectors.toList());
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
return plugin.getDatabase().getPublicHomes().thenApplyAsync(homes -> homes.stream() return plugin.getDatabase().getPublicHomes().stream()
.filter(home -> plugin.getWorlds().stream().anyMatch(world -> world.equals(home.world))) .filter(home -> plugin.getWorlds().stream().anyMatch(world -> world.equals(home.world)))
.collect(Collectors.toList())); .collect(Collectors.toList());
} }
} }
@@ -314,7 +311,7 @@ public abstract class Database {
* @param homeName The <i>case-insensitive</i> name of the home to get * @param homeName The <i>case-insensitive</i> name of the home to get
* @return A future returning an optional with the {@link Home} present if it exists * @return A future returning an optional with the {@link Home} present if it exists
*/ */
public abstract CompletableFuture<Optional<Home>> getHome(@NotNull User user, @NotNull String homeName); public abstract Optional<Home> getHome(@NotNull User user, @NotNull String homeName);
/** /**
* Get a {@link Home} by its unique id * Get a {@link Home} by its unique id
@@ -322,7 +319,7 @@ public abstract class Database {
* @param uuid the {@link UUID} of the home to get * @param uuid the {@link UUID} of the home to get
* @return A future returning an optional with the {@link Home} present if it exists * @return A future returning an optional with the {@link Home} present if it exists
*/ */
public abstract CompletableFuture<Optional<Home>> getHome(@NotNull UUID uuid); public abstract Optional<Home> getHome(@NotNull UUID uuid);
/** /**
* Get a {@link Warp} with the given name (<i>case-insensitive</i>) * Get a {@link Warp} with the given name (<i>case-insensitive</i>)
@@ -330,7 +327,7 @@ public abstract class Database {
* @param warpName The <i>case-insensitive</i> name of the warp to get * @param warpName The <i>case-insensitive</i> name of the warp to get
* @return A future returning an optional with the {@link Warp} present if it exists * @return A future returning an optional with the {@link Warp} present if it exists
*/ */
public abstract CompletableFuture<Optional<Warp>> getWarp(@NotNull String warpName); public abstract Optional<Warp> getWarp(@NotNull String warpName);
/** /**
* Get a {@link Warp} by its unique id * Get a {@link Warp} by its unique id
@@ -338,7 +335,7 @@ public abstract class Database {
* @param uuid the {@link UUID} of the warp to get * @param uuid the {@link UUID} of the warp to get
* @return A future returning an optional with the {@link Warp} present if it exists * @return A future returning an optional with the {@link Warp} present if it exists
*/ */
public abstract CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID uuid); public abstract Optional<Warp> getWarp(@NotNull UUID uuid);
/** /**
* Get the current {@link Teleport} being executed by the specified {@link OnlineUser} * Get the current {@link Teleport} being executed by the specified {@link OnlineUser}
@@ -346,15 +343,14 @@ public abstract class Database {
* @param onlineUser The {@link OnlineUser} to check * @param onlineUser The {@link OnlineUser} to check
* @return A future returning an optional with the {@link Teleport} present if they are teleporting cross-server * @return A future returning an optional with the {@link Teleport} present if they are teleporting cross-server
*/ */
public abstract CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull OnlineUser onlineUser); public abstract Optional<Teleport> getCurrentTeleport(@NotNull OnlineUser onlineUser);
/** /**
* Updates a user in the database with new {@link UserData} * Updates a user in the database with new {@link UserData}
* *
* @param userData The {@link UserData} to update * @param userData The {@link UserData} to update
* @return A future returning void when complete
*/ */
public abstract CompletableFuture<Void> updateUserData(@NotNull UserData userData); public abstract void updateUserData(@NotNull UserData userData);
/** /**
* Sets or clears the current {@link Teleport} being executed by a {@link User} * Sets or clears the current {@link Teleport} being executed by a {@link User}
@@ -362,9 +358,8 @@ public abstract class Database {
* @param user The {@link User} to set the current teleport of. * @param user The {@link User} to set the current teleport of.
* Pass as {@code null} to clear the player's current teleport.<p> * Pass as {@code null} to clear the player's current teleport.<p>
* @param teleport The {@link Teleport} to set as their current cross-server teleport * @param teleport The {@link Teleport} to set as their current cross-server teleport
* @return A future returning void when complete
*/ */
public abstract CompletableFuture<Void> setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport); public abstract void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport);
/** /**
* Get the last teleport {@link Position} of a specified {@link User} * Get the last teleport {@link Position} of a specified {@link User}
@@ -372,16 +367,15 @@ public abstract class Database {
* @param user The {@link User} to check * @param user The {@link User} to check
* @return A future returning an optional with the {@link Position} present if it has been set * @return A future returning an optional with the {@link Position} present if it has been set
*/ */
public abstract CompletableFuture<Optional<Position>> getLastPosition(@NotNull User user); public abstract Optional<Position> getLastPosition(@NotNull User user);
/** /**
* Sets the last teleport {@link Position} of a {@link User} * Sets the last teleport {@link Position} of a {@link User}
* *
* @param user The {@link User} to set the last position of * @param user The {@link User} to set the last position of
* @param position The {@link Position} to set as their last position * @param position The {@link Position} to set as their last position
* @return A future returning void when complete
*/ */
public abstract CompletableFuture<Void> setLastPosition(@NotNull User user, @NotNull Position position); public abstract void setLastPosition(@NotNull User user, @NotNull Position position);
/** /**
* Get the offline {@link Position} of a specified {@link User} * Get the offline {@link Position} of a specified {@link User}
@@ -389,16 +383,15 @@ public abstract class Database {
* @param user The {@link User} to check * @param user The {@link User} to check
* @return A future returning an optional with the {@link Position} present if it has been set * @return A future returning an optional with the {@link Position} present if it has been set
*/ */
public abstract CompletableFuture<Optional<Position>> getOfflinePosition(@NotNull User user); public abstract Optional<Position> getOfflinePosition(@NotNull User user);
/** /**
* Sets the offline {@link Position} of a {@link User} * Sets the offline {@link Position} of a {@link User}
* *
* @param user The {@link User} to set the offline position of * @param user The {@link User} to set the offline position of
* @param position The {@link Position} to set as their offline position * @param position The {@link Position} to set as their offline position
* @return A future returning void when complete
*/ */
public abstract CompletableFuture<Void> setOfflinePosition(@NotNull User user, @NotNull Position position); public abstract void setOfflinePosition(@NotNull User user, @NotNull Position position);
/** /**
* Get the respawn {@link Position} of a specified {@link User} * Get the respawn {@link Position} of a specified {@link User}
@@ -406,7 +399,7 @@ public abstract class Database {
* @param user The {@link User} to check * @param user The {@link User} to check
* @return A future returning an optional with the {@link Position} present if it has been set * @return A future returning an optional with the {@link Position} present if it has been set
*/ */
public abstract CompletableFuture<Optional<Position>> getRespawnPosition(@NotNull User user); public abstract Optional<Position> getRespawnPosition(@NotNull User user);
/** /**
* Sets or clears the respawn {@link Position} of a {@link User} * Sets or clears the respawn {@link Position} of a {@link User}
@@ -414,33 +407,29 @@ public abstract class Database {
* @param user The {@link User} to set the respawn position of * @param user The {@link User} to set the respawn position of
* @param position The {@link Position} to set as their respawn position * @param position The {@link Position} to set as their respawn position
* Pass as {@code null} to clear the player's current respawn position.<p> * Pass as {@code null} to clear the player's current respawn position.<p>
* @return A future returning void when complete
*/ */
public abstract CompletableFuture<Void> setRespawnPosition(@NotNull User user, @Nullable Position position); public abstract void setRespawnPosition(@NotNull User user, @Nullable Position position);
/** /**
* Sets or updates a {@link Home} into the home data table on the database. * Sets or updates a {@link Home} into the home data table on the database.
* *
* @param home The {@link Home} to set - or update - in the database. * @param home The {@link Home} to set - or update - in the database.
* @return A future returning void when complete
*/ */
public abstract CompletableFuture<Void> saveHome(@NotNull Home home); public abstract void saveHome(@NotNull Home home);
/** /**
* Sets or updates a {@link Warp} into the warp data table on the database. * Sets or updates a {@link Warp} into the warp data table on the database.
* *
* @param warp The {@link Warp} to set - or update - in the database. * @param warp The {@link Warp} to set - or update - in the database.
* @return A future returning void when complete
*/ */
public abstract CompletableFuture<Void> saveWarp(@NotNull Warp warp); public abstract void saveWarp(@NotNull Warp warp);
/** /**
* Deletes a {@link Home} by the given unique id from the home table on the database. * Deletes a {@link Home} by the given unique id from the home table on the database.
* *
* @param uuid {@link UUID} of the home to delete * @param uuid {@link UUID} of the home to delete
* @return A future returning void when complete
*/ */
public abstract CompletableFuture<Void> deleteHome(@NotNull UUID uuid); public abstract void deleteHome(@NotNull UUID uuid);
/** /**
* Deletes all {@link Home}s of a {@link User} from the home table on the database. * Deletes all {@link Home}s of a {@link User} from the home table on the database.
@@ -448,22 +437,21 @@ public abstract class Database {
* @param user The {@link User} to delete all homes of * @param user The {@link User} to delete all homes of
* @return A future returning an integer; the number of deleted homes * @return A future returning an integer; the number of deleted homes
*/ */
public abstract CompletableFuture<Integer> deleteAllHomes(@NotNull User user); public abstract int deleteAllHomes(@NotNull User user);
/** /**
* Deletes a {@link Warp} by the given unique id from the warp table on the database. * Deletes a {@link Warp} by the given unique id from the warp table on the database.
* *
* @param uuid {@link UUID} of the warp to delete * @param uuid {@link UUID} of the warp to delete
* @return A future returning void when complete
*/ */
public abstract CompletableFuture<Void> deleteWarp(@NotNull UUID uuid); public abstract void deleteWarp(@NotNull UUID uuid);
/** /**
* Deletes all {@link Warp}s set on the database table * Deletes all {@link Warp}s set on the database table
* *
* @return A future returning an integer; the number of deleted warps * @return A future returning an integer; the number of deleted warps
*/ */
public abstract CompletableFuture<Integer> deleteAllWarps(); public abstract int deleteAllWarps();
/** /**
* Close any remaining connection to the database source * Close any remaining connection to the database source
@@ -16,7 +16,6 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level; import java.util.logging.Level;
/** /**
@@ -43,17 +42,17 @@ public class MySqlDatabase extends Database {
public MySqlDatabase(@NotNull HuskHomes plugin) { public MySqlDatabase(@NotNull HuskHomes plugin) {
super(plugin); super(plugin);
this.host = plugin.getSettings().mySqlHost; this.host = plugin.getSettings().getMySqlHost();
this.port = plugin.getSettings().mySqlPort; this.port = plugin.getSettings().getMySqlPort();
this.database = plugin.getSettings().mySqlDatabase; this.database = plugin.getSettings().getMySqlDatabase();
this.username = plugin.getSettings().mySqlUsername; this.username = plugin.getSettings().getMySqlUsername();
this.password = plugin.getSettings().mySqlPassword; this.password = plugin.getSettings().getMySqlPassword();
this.connectionParameters = plugin.getSettings().mySqlConnectionParameters; this.connectionParameters = plugin.getSettings().getMySqlConnectionParameters();
this.connectionPoolSize = plugin.getSettings().mySqlConnectionPoolSize; this.connectionPoolSize = plugin.getSettings().getMySqlConnectionPoolSize();
this.connectionPoolIdle = plugin.getSettings().mySqlConnectionPoolIdle; this.connectionPoolIdle = plugin.getSettings().getMySqlConnectionPoolIdle();
this.connectionPoolLifetime = plugin.getSettings().mySqlConnectionPoolLifetime; this.connectionPoolLifetime = plugin.getSettings().getMySqlConnectionPoolLifetime();
this.connectionPoolKeepAlive = plugin.getSettings().mySqlConnectionPoolKeepAlive; this.connectionPoolKeepAlive = plugin.getSettings().getMySqlConnectionPoolKeepAlive();
this.connectionPoolTimeout = plugin.getSettings().mySqlConnectionPoolTimeout; this.connectionPoolTimeout = plugin.getSettings().getMySqlConnectionPoolTimeout();
} }
/** /**
@@ -121,8 +120,7 @@ public class MySqlDatabase extends Database {
} }
@Override @Override
public CompletableFuture<Void> runScript(@NotNull InputStream inputStream, @NotNull Map<String, String> replacements) { public void runScript(@NotNull InputStream inputStream, @NotNull Map<String, String> replacements) {
return CompletableFuture.runAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
final String[] scriptString; final String[] scriptString;
scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)}; scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)};
@@ -138,7 +136,6 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "An error occurred running a script on the MySQL database: ", e); getLogger().log(Level.SEVERE, "An error occurred running a script on the MySQL database: ", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
});
} }
@Override @Override
@@ -244,9 +241,8 @@ public class MySqlDatabase extends Database {
} }
@Override @Override
public CompletableFuture<Void> ensureUser(@NotNull User onlineUser) { public void ensureUser(@NotNull User onlineUser) {
return CompletableFuture.runAsync(() -> getUserData(onlineUser.uuid).thenAccept(optionalUser -> getUserData(onlineUser.uuid).ifPresentOrElse(existingUserData -> {
optionalUser.ifPresentOrElse(existingUserData -> {
if (!existingUserData.getUsername().equals(onlineUser.username)) { if (!existingUserData.getUsername().equals(onlineUser.username)) {
// Update a player's name if it has changed in the database // Update a player's name if it has changed in the database
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
@@ -279,12 +275,11 @@ public class MySqlDatabase extends Database {
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e); getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e);
} }
}))); });
} }
@Override @Override
public CompletableFuture<Optional<UserData>> getUserDataByName(@NotNull String name) { public Optional<UserData> getUserDataByName(@NotNull String name) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
@@ -306,12 +301,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e); getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Optional<UserData>> getUserData(@NotNull UUID uuid) { public Optional<UserData> getUserData(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
@@ -334,12 +327,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<List<Home>> getHomes(@NotNull User user) { public List<Home> getHomes(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
final List<Home> userHomes = new ArrayList<>(); final List<Home> userHomes = new ArrayList<>();
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
@@ -376,12 +367,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username); getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username);
} }
return userHomes; return userHomes;
});
} }
@Override @Override
public CompletableFuture<List<Warp>> getWarps() { public List<Warp> getWarps() {
return CompletableFuture.supplyAsync(() -> {
final List<Warp> warps = new ArrayList<>(); final List<Warp> warps = new ArrayList<>();
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
@@ -412,12 +401,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query the database for warp data."); getLogger().log(Level.SEVERE, "Failed to query the database for warp data.");
} }
return warps; return warps;
});
} }
@Override @Override
public CompletableFuture<List<Home>> getPublicHomes() { public List<Home> getPublicHomes() {
return CompletableFuture.supplyAsync(() -> {
final List<Home> userHomes = new ArrayList<>(); final List<Home> userHomes = new ArrayList<>();
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
@@ -453,12 +440,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query the database for public home data"); getLogger().log(Level.SEVERE, "Failed to query the database for public home data");
} }
return userHomes; return userHomes;
});
} }
@Override @Override
public CompletableFuture<Optional<Home>> getHome(@NotNull User user, @NotNull String homeName) { public Optional<Home> getHome(@NotNull User user, @NotNull String homeName) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
@@ -495,12 +480,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query a player's home", e); getLogger().log(Level.SEVERE, "Failed to query a player's home", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Optional<Home>> getHome(@NotNull UUID uuid) { public Optional<Home> getHome(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
@@ -535,12 +518,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query a player's home by uuid", e); getLogger().log(Level.SEVERE, "Failed to query a player's home by uuid", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Optional<Warp>> getWarp(@NotNull String warpName) { public Optional<Warp> getWarp(@NotNull String warpName) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
@@ -571,12 +552,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query a server warp", e); getLogger().log(Level.SEVERE, "Failed to query a server warp", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID uuid) { public Optional<Warp> getWarp(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
@@ -607,12 +586,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query a server warp", e); getLogger().log(Level.SEVERE, "Failed to query a server warp", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull OnlineUser onlineUser) { public Optional<Teleport> getCurrentTeleport(@NotNull OnlineUser onlineUser) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type`
@@ -643,12 +620,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e); getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Void> updateUserData(@NotNull UserData userData) { public void updateUserData(@NotNull UserData userData) {
return CompletableFuture.runAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
UPDATE `%players_table%` UPDATE `%players_table%`
@@ -664,12 +639,10 @@ public class MySqlDatabase extends Database {
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e); getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e);
} }
});
} }
@Override @Override
public CompletableFuture<Void> setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) {
return CompletableFuture.runAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
// Clear the user's current teleport // Clear the user's current teleport
try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables("""
@@ -698,12 +671,10 @@ public class MySqlDatabase extends Database {
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.username, e);
} }
});
} }
@Override @Override
public CompletableFuture<Optional<Position>> getLastPosition(@NotNull User user) { public Optional<Position> getLastPosition(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
@@ -728,12 +699,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Void> setLastPosition(@NotNull User user, @NotNull Position position) { public void setLastPosition(@NotNull User user, @NotNull Position position) {
return CompletableFuture.runAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
SELECT `last_position` SELECT `last_position`
@@ -761,12 +730,10 @@ public class MySqlDatabase extends Database {
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e);
} }
});
} }
@Override @Override
public CompletableFuture<Optional<Position>> getOfflinePosition(@NotNull User user) { public Optional<Position> getOfflinePosition(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
@@ -791,12 +758,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Void> setOfflinePosition(@NotNull User user, @NotNull Position position) { public void setOfflinePosition(@NotNull User user, @NotNull Position position) {
return CompletableFuture.runAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
SELECT `offline_position` FROM `%players_table%` SELECT `offline_position` FROM `%players_table%`
@@ -823,12 +788,10 @@ public class MySqlDatabase extends Database {
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e);
} }
});
} }
@Override @Override
public CompletableFuture<Optional<Position>> getRespawnPosition(@NotNull User user) { public Optional<Position> getRespawnPosition(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
@@ -853,12 +816,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Void> setRespawnPosition(@NotNull User user, @Nullable Position position) { public void setRespawnPosition(@NotNull User user, @Nullable Position position) {
return CompletableFuture.runAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
SELECT `respawn_position` FROM `%players_table%` SELECT `respawn_position` FROM `%players_table%`
@@ -901,13 +862,11 @@ public class MySqlDatabase extends Database {
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e);
} }
});
} }
@Override @Override
public CompletableFuture<Void> saveHome(@NotNull Home home) { public void saveHome(@NotNull Home home) {
return CompletableFuture.runAsync(() -> getHome(home.uuid) getHome(home.uuid).ifPresentOrElse(presentHome -> {
.thenAccept(existingHome -> existingHome.ifPresentOrElse(presentHome -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
// Update the home's saved position, including metadata // Update the home's saved position, including metadata
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
@@ -950,13 +909,12 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, getLogger().log(Level.SEVERE,
"Failed to set a home to the database for " + home.owner.username, e); "Failed to set a home to the database for " + home.owner.username, e);
} }
}))); });
} }
@Override @Override
public CompletableFuture<Void> saveWarp(@NotNull Warp warp) { public void saveWarp(@NotNull Warp warp) {
return CompletableFuture.runAsync(() -> getWarp(warp.uuid) getWarp(warp.uuid).ifPresentOrElse(presentWarp -> {
.thenAccept(existingHome -> existingHome.ifPresentOrElse(presentWarp -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%warps_table%` SELECT `saved_position_id` FROM `%warps_table%`
@@ -984,12 +942,11 @@ public class MySqlDatabase extends Database {
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e); getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e);
} }
}))); });
} }
@Override @Override
public CompletableFuture<Void> deleteHome(@NotNull UUID uuid) { public void deleteHome(@NotNull UUID uuid) {
return CompletableFuture.runAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%` DELETE FROM `%positions_table%`
@@ -1009,12 +966,10 @@ public class MySqlDatabase extends Database {
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e); getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e);
} }
});
} }
@Override @Override
public CompletableFuture<Integer> deleteAllHomes(@NotNull User user) { public int deleteAllHomes(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%` DELETE FROM `%positions_table%`
@@ -1035,12 +990,10 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e); getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e);
} }
return 0; return 0;
});
} }
@Override @Override
public CompletableFuture<Void> deleteWarp(@NotNull UUID uuid) { public void deleteWarp(@NotNull UUID uuid) {
return CompletableFuture.runAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%` DELETE FROM `%positions_table%`
@@ -1060,12 +1013,11 @@ public class MySqlDatabase extends Database {
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e); getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e);
} }
});
} }
@Override @Override
public CompletableFuture<Integer> deleteAllWarps() { public int deleteAllWarps() {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%` DELETE FROM `%positions_table%`
@@ -1083,7 +1035,6 @@ public class MySqlDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to delete all warps from the database", e); getLogger().log(Level.SEVERE, "Failed to delete all warps from the database", e);
} }
return 0; return 0;
});
} }
@Override @Override
@@ -17,7 +17,6 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level; import java.util.logging.Level;
/** /**
@@ -109,8 +108,7 @@ public class SqLiteDatabase extends Database {
} }
@Override @Override
public CompletableFuture<Void> runScript(@NotNull InputStream inputStream, @NotNull Map<String, String> replacements) { public void runScript(@NotNull InputStream inputStream, @NotNull Map<String, String> replacements) {
return CompletableFuture.runAsync(() -> {
try { try {
final String[] scriptString; final String[] scriptString;
scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)}; scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)};
@@ -130,7 +128,6 @@ public class SqLiteDatabase extends Database {
getLogger().log(Level.SEVERE, "An exception occurred running script on the SQLite database", e); getLogger().log(Level.SEVERE, "An exception occurred running script on the SQLite database", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
});
} }
@Override @Override
@@ -240,9 +237,8 @@ public class SqLiteDatabase extends Database {
} }
@Override @Override
public CompletableFuture<Void> ensureUser(@NotNull User onlineUser) { public void ensureUser(@NotNull User onlineUser) {
return CompletableFuture.runAsync(() -> getUserData(onlineUser.uuid).thenAccept(optionalUser -> getUserData(onlineUser.uuid).ifPresentOrElse(existingUser -> {
optionalUser.ifPresentOrElse(existingUser -> {
if (!existingUser.getUsername().equals(onlineUser.username)) { if (!existingUser.getUsername().equals(onlineUser.username)) {
// Update a player's name if it has changed in the database // Update a player's name if it has changed in the database
try { try {
@@ -275,12 +271,11 @@ public class SqLiteDatabase extends Database {
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e); getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e);
} }
}))); });
} }
@Override @Override
public CompletableFuture<Optional<UserData>> getUserDataByName(@NotNull String name) { public Optional<UserData> getUserDataByName(@NotNull String name) {
return CompletableFuture.supplyAsync(() -> {
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
@@ -302,12 +297,10 @@ public class SqLiteDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e); getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Optional<UserData>> getUserData(@NotNull UUID uuid) { public Optional<UserData> getUserData(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown` SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
@@ -330,12 +323,10 @@ public class SqLiteDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<List<Home>> getHomes(@NotNull User user) { public List<Home> getHomes(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
final List<Home> userHomes = new ArrayList<>(); final List<Home> userHomes = new ArrayList<>();
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -372,12 +363,10 @@ public class SqLiteDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username); getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username);
} }
return userHomes; return userHomes;
});
} }
@Override @Override
public CompletableFuture<List<Warp>> getWarps() { public List<Warp> getWarps() {
return CompletableFuture.supplyAsync(() -> {
final List<Warp> warps = new ArrayList<>(); final List<Warp> warps = new ArrayList<>();
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -408,12 +397,10 @@ public class SqLiteDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query the database for warp data."); getLogger().log(Level.SEVERE, "Failed to query the database for warp data.");
} }
return warps; return warps;
});
} }
@Override @Override
public CompletableFuture<List<Home>> getPublicHomes() { public List<Home> getPublicHomes() {
return CompletableFuture.supplyAsync(() -> {
final List<Home> userHomes = new ArrayList<>(); final List<Home> userHomes = new ArrayList<>();
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -449,12 +436,10 @@ public class SqLiteDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query the database for public home data"); getLogger().log(Level.SEVERE, "Failed to query the database for public home data");
} }
return userHomes; return userHomes;
});
} }
@Override @Override
public CompletableFuture<Optional<Home>> getHome(@NotNull User user, @NotNull String homeName) { public Optional<Home> getHome(@NotNull User user, @NotNull String homeName) {
return CompletableFuture.supplyAsync(() -> {
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
@@ -491,12 +476,10 @@ public class SqLiteDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query a player's home", e); getLogger().log(Level.SEVERE, "Failed to query a player's home", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Optional<Home>> getHome(@NotNull UUID uuid) { public Optional<Home> getHome(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
@@ -531,12 +514,10 @@ public class SqLiteDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query a player's home by uuid", e); getLogger().log(Level.SEVERE, "Failed to query a player's home by uuid", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Optional<Warp>> getWarp(@NotNull String warpName) { public Optional<Warp> getWarp(@NotNull String warpName) {
return CompletableFuture.supplyAsync(() -> {
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
@@ -567,12 +548,10 @@ public class SqLiteDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query a server warp", e); getLogger().log(Level.SEVERE, "Failed to query a server warp", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID uuid) { public Optional<Warp> getWarp(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
@@ -603,13 +582,11 @@ public class SqLiteDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to query a server warp", e); getLogger().log(Level.SEVERE, "Failed to query a server warp", e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull OnlineUser onlineUser) { public Optional<Teleport> getCurrentTeleport(@NotNull OnlineUser onlineUser) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type`
FROM `%teleports_table%` FROM `%teleports_table%`
@@ -634,18 +611,15 @@ public class SqLiteDatabase extends Database {
.toTeleport() .toTeleport()
.join()); .join());
} }
}
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e); getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.username, e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Void> updateUserData(@NotNull UserData userData) { public void updateUserData(@NotNull UserData userData) {
return CompletableFuture.runAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
UPDATE `%players_table%` UPDATE `%players_table%`
SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=? SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=?
@@ -656,16 +630,13 @@ public class SqLiteDatabase extends Database {
statement.setTimestamp(3, Timestamp.from(userData.rtpCooldown())); statement.setTimestamp(3, Timestamp.from(userData.rtpCooldown()));
statement.setString(4, userData.getUserUuid().toString()); statement.setString(4, userData.getUserUuid().toString());
statement.executeUpdate(); statement.executeUpdate();
}
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e); getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.getUsername() + " on the database", e);
} }
});
} }
@Override @Override
public CompletableFuture<Void> setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) {
return CompletableFuture.runAsync(() -> {
// Clear the user's current teleport // Clear the user's current teleport
try { try {
try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables("""
@@ -684,7 +655,6 @@ public class SqLiteDatabase extends Database {
// 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)
if (teleport != null && teleport.target != null) { if (teleport != null && teleport.target != null) {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`)
VALUES (?,?,?);"""))) { VALUES (?,?,?);"""))) {
@@ -693,18 +663,15 @@ public class SqLiteDatabase extends Database {
statement.setInt(3, teleport.type.typeId); statement.setInt(3, teleport.type.typeId);
statement.executeUpdate(); statement.executeUpdate();
}
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the current teleport of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to set the current teleport of " + user.username, e);
} }
} }
});
} }
@Override @Override
public CompletableFuture<Optional<Position>> getLastPosition(@NotNull User user) { public Optional<Position> getLastPosition(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%players_table%` FROM `%players_table%`
@@ -723,18 +690,15 @@ public class SqLiteDatabase extends Database {
UUID.fromString(resultSet.getString("world_uuid"))), UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")))); new Server(resultSet.getString("server_name"))));
} }
}
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Void> setLastPosition(@NotNull User user, @NotNull Position position) { public void setLastPosition(@NotNull User user, @NotNull Position position) {
return CompletableFuture.runAsync(() -> {
try {
try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
SELECT `last_position` FROM `%players_table%` SELECT `last_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id` INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id`
@@ -756,17 +720,15 @@ public class SqLiteDatabase extends Database {
updateStatement.executeUpdate(); updateStatement.executeUpdate();
} }
} }
}
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e);
} }
});
} }
@Override @Override
public CompletableFuture<Optional<Position>> getOfflinePosition(@NotNull User user) { public Optional<Position> getOfflinePosition(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%players_table%` FROM `%players_table%`
@@ -785,18 +747,15 @@ public class SqLiteDatabase extends Database {
UUID.fromString(resultSet.getString("world_uuid"))), UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")))); new Server(resultSet.getString("server_name"))));
} }
}
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Void> setOfflinePosition(@NotNull User user, @NotNull Position position) { public void setOfflinePosition(@NotNull User user, @NotNull Position position) {
return CompletableFuture.runAsync(() -> {
try {
try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
SELECT `offline_position` FROM `%players_table%` SELECT `offline_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.offline_position = `%positions_table%`.`id` INNER JOIN `%positions_table%` ON `%players_table%`.offline_position = `%positions_table%`.`id`
@@ -818,17 +777,13 @@ public class SqLiteDatabase extends Database {
updateStatement.executeUpdate(); updateStatement.executeUpdate();
} }
} }
}
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e);
} }
});
} }
@Override @Override
public CompletableFuture<Optional<Position>> getRespawnPosition(@NotNull User user) { public Optional<Position> getRespawnPosition(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%players_table%` FROM `%players_table%`
@@ -847,18 +802,14 @@ public class SqLiteDatabase extends Database {
UUID.fromString(resultSet.getString("world_uuid"))), UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")))); new Server(resultSet.getString("server_name"))));
} }
}
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e);
} }
return Optional.empty(); return Optional.empty();
});
} }
@Override @Override
public CompletableFuture<Void> setRespawnPosition(@NotNull User user, @Nullable Position position) { public void setRespawnPosition(@NotNull User user, @Nullable Position position) {
return CompletableFuture.runAsync(() -> {
try {
try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
SELECT `respawn_position` FROM `%players_table%` SELECT `respawn_position` FROM `%players_table%`
INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id` INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id`
@@ -896,17 +847,15 @@ public class SqLiteDatabase extends Database {
} }
} }
} }
}
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e); getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e);
} }
});
} }
@Override @Override
public CompletableFuture<Void> saveHome(@NotNull Home home) { public void saveHome(@NotNull Home home) {
return CompletableFuture.runAsync(() -> getHome(home.uuid) getHome(home.uuid).ifPresentOrElse(presentHome -> {
.thenAccept(existingHome -> existingHome.ifPresentOrElse(presentHome -> {
try { try {
// Update the home's saved position, including metadata // Update the home's saved position, including metadata
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -934,7 +883,6 @@ public class SqLiteDatabase extends Database {
"Failed to update a home in the database for " + home.owner.username, e); "Failed to update a home in the database for " + home.owner.username, e);
} }
}, () -> { }, () -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
VALUES (?,?,?,?);"""))) { VALUES (?,?,?,?);"""))) {
@@ -944,19 +892,18 @@ public class SqLiteDatabase extends Database {
statement.setBoolean(4, home.isPublic); statement.setBoolean(4, home.isPublic);
statement.executeUpdate(); statement.executeUpdate();
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
getLogger().log(Level.SEVERE, getLogger().log(Level.SEVERE,
"Failed to set a home to the database for " + home.owner.username, e); "Failed to set a home to the database for " + home.owner.username, e);
} }
}))); });
} }
@Override @Override
public CompletableFuture<Void> saveWarp(@NotNull Warp warp) { public void saveWarp(@NotNull Warp warp) {
return CompletableFuture.runAsync(() -> getWarp(warp.uuid) getWarp(warp.uuid)
.thenAccept(existingHome -> existingHome.ifPresentOrElse(presentWarp -> { .ifPresentOrElse(presentWarp -> {
try { try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%warps_table%` SELECT `saved_position_id` FROM `%warps_table%`
@@ -972,7 +919,6 @@ public class SqLiteDatabase extends Database {
getLogger().log(Level.SEVERE, "Failed to update a warp in the database", e); getLogger().log(Level.SEVERE, "Failed to update a warp in the database", e);
} }
}, () -> { }, () -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`) INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`)
VALUES (?,?);"""))) { VALUES (?,?);"""))) {
@@ -980,17 +926,14 @@ public class SqLiteDatabase extends Database {
statement.setInt(2, setSavedPosition(warp, connection)); statement.setInt(2, setSavedPosition(warp, connection));
statement.executeUpdate(); statement.executeUpdate();
}
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e); getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e);
} }
}))); });
} }
@Override @Override
public CompletableFuture<Void> deleteHome(@NotNull UUID uuid) { public void deleteHome(@NotNull UUID uuid) {
return CompletableFuture.runAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%` DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id`=( WHERE `%positions_table%`.`id`=(
@@ -1005,18 +948,15 @@ 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 home from the database", e); getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e);
} }
});
} }
@Override @Override
public CompletableFuture<Integer> deleteAllHomes(@NotNull User user) { public int deleteAllHomes(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%` DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN ( WHERE `%positions_table%`.`id` IN (
SELECT `position_id` SELECT `position_id`
@@ -1030,18 +970,14 @@ public class SqLiteDatabase extends Database {
statement.setString(1, user.uuid.toString()); statement.setString(1, user.uuid.toString());
return statement.executeUpdate(); return statement.executeUpdate();
}
} catch (SQLException e) { } catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e); getLogger().log(Level.SEVERE, "Failed to delete all homes for " + user.username + " from the database", e);
} }
return 0; return 0;
});
} }
@Override @Override
public CompletableFuture<Void> deleteWarp(@NotNull UUID uuid) { public void deleteWarp(@NotNull UUID uuid) {
return CompletableFuture.runAsync(() -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%` DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id`=( WHERE `%positions_table%`.`id`=(
@@ -1054,20 +990,15 @@ 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); getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e);
} }
});
} }
@Override @Override
public CompletableFuture<Integer> deleteAllWarps() { public int deleteAllWarps() {
return CompletableFuture.supplyAsync(() -> { try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
DELETE FROM `%positions_table%` DELETE FROM `%positions_table%`
WHERE `%positions_table%`.`id` IN ( WHERE `%positions_table%`.`id` IN (
SELECT `position_id` SELECT `position_id`
@@ -1078,12 +1009,10 @@ 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); getLogger().log(Level.SEVERE, "Failed to delete all warps from the database", e);
} }
return 0; return 0;
});
} }
@Override @Override
@@ -39,11 +39,11 @@ public class BlueMapHook extends MapHook {
// Create marker sets // Create marker sets
plugin.getWorlds().forEach(world -> blueMapAPI.getWorld(world.uuid) plugin.getWorlds().forEach(world -> blueMapAPI.getWorld(world.uuid)
.ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(map -> { .ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(map -> {
if (plugin.getSettings().publicHomesOnMap) { if (plugin.getSettings().isPublicHomesOnMap()) {
map.getMarkerSets().put(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, map.getMarkerSets().put(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID,
MarkerSet.builder().label("Public Homes").build()); MarkerSet.builder().label("Public Homes").build());
} }
if (plugin.getSettings().warpsOnMap) { if (plugin.getSettings().isWarpsOnMap()) {
map.getMarkerSets().put(blueMapWorld.getId() + ":" + WARPS_MARKER_SET_ID, map.getMarkerSets().put(blueMapWorld.getId() + ":" + WARPS_MARKER_SET_ID,
MarkerSet.builder().label("Warps").build()); MarkerSet.builder().label("Warps").build());
} }
@@ -26,13 +26,15 @@ public abstract class MapHook extends PluginHook {
@Override @Override
public final boolean initialize() { public final boolean initialize() {
initializeMap().thenRun(() -> { initializeMap().thenRun(() -> {
if (plugin.getSettings().publicHomesOnMap) { if (plugin.getSettings().isPublicHomesOnMap()) {
plugin.getDatabase().getLocalPublicHomes(plugin) plugin.getDatabase()
.thenAcceptAsync(homes -> homes.forEach(this::updateHome)); .getLocalPublicHomes(plugin)
.forEach(this::updateHome);
} }
if (plugin.getSettings().warpsOnMap) { if (plugin.getSettings().isWarpsOnMap()) {
plugin.getDatabase().getLocalWarps(plugin) plugin.getDatabase()
.thenAcceptAsync(warps -> warps.forEach(this::updateWarp)); .getLocalWarps(plugin)
.forEach(this::updateWarp);
} }
}); });
return true; return true;
@@ -98,8 +100,8 @@ public abstract class MapHook extends PluginHook {
*/ */
@SuppressWarnings("BooleanMethodIsAlwaysInverted") @SuppressWarnings("BooleanMethodIsAlwaysInverted")
protected final boolean isValidPosition(@NotNull SavedPosition position) { protected final boolean isValidPosition(@NotNull SavedPosition position) {
if (position instanceof Warp && !plugin.getSettings().warpsOnMap) return false; if (position instanceof Warp && !plugin.getSettings().isWarpsOnMap()) return false;
if (position instanceof Home && !plugin.getSettings().publicHomesOnMap) return false; if (position instanceof Home && !plugin.getSettings().isPublicHomesOnMap()) return false;
try { try {
return position.server.equals(plugin.getServerName()); return position.server.equals(plugin.getServerName());
@@ -50,7 +50,7 @@ public class PlanDataExtension implements DataExtension {
hidden = true hidden = true
) )
public boolean getHasUserData(@NotNull UUID uuid) { public boolean getHasUserData(@NotNull UUID uuid) {
return database.getUserData(uuid).join().isPresent(); return database.getUserData(uuid).isPresent();
} }
@NumberProvider( @NumberProvider(
@@ -62,8 +62,8 @@ public class PlanDataExtension implements DataExtension {
) )
@Conditional("hasData") @Conditional("hasData")
public long getHomeCount(@NotNull UUID uuid) { public long getHomeCount(@NotNull UUID uuid) {
return database.getUserData(uuid).join() return database.getUserData(uuid)
.map(userData -> (long) database.getHomes(userData.user()).join().size()) .map(userData -> (long) database.getHomes(userData.user()).size())
.orElse(0L); .orElse(0L);
} }
@@ -76,8 +76,8 @@ public class PlanDataExtension implements DataExtension {
) )
@Conditional("hasData") @Conditional("hasData")
public long getPublicHomeCount(@NotNull UUID uuid) { public long getPublicHomeCount(@NotNull UUID uuid) {
return database.getUserData(uuid).join() return database.getUserData(uuid)
.map(userData -> database.getHomes(userData.user()).join() .map(userData -> database.getHomes(userData.user())
.stream().filter(home -> home.isPublic).count()) .stream().filter(home -> home.isPublic).count())
.orElse(0L); .orElse(0L);
} }
@@ -91,7 +91,7 @@ public class PlanDataExtension implements DataExtension {
) )
@Conditional("hasData") @Conditional("hasData")
public long getPurchasedHomeSlots(@NotNull UUID uuid) { public long getPurchasedHomeSlots(@NotNull UUID uuid) {
return database.getUserData(uuid).join() return database.getUserData(uuid)
.map(userData -> (long) userData.homeSlots()) .map(userData -> (long) userData.homeSlots())
.orElse(0L); .orElse(0L);
} }
@@ -105,7 +105,7 @@ public class PlanDataExtension implements DataExtension {
) )
@Conditional("hasData") @Conditional("hasData")
public boolean isIgnoringTeleportRequests(@NotNull UUID uuid) { public boolean isIgnoringTeleportRequests(@NotNull UUID uuid) {
return database.getUserData(uuid).join() return database.getUserData(uuid)
.map(UserData::ignoringTeleports) .map(UserData::ignoringTeleports)
.orElse(false); .orElse(false);
} }
@@ -119,8 +119,8 @@ public class PlanDataExtension implements DataExtension {
) )
@Conditional("hasData") @Conditional("hasData")
public String getOfflinePosition(@NotNull UUID uuid) { public String getOfflinePosition(@NotNull UUID uuid) {
return database.getUserData(uuid).join() return database.getUserData(uuid)
.map(userData -> database.getOfflinePosition(userData.user()).join() .map(userData -> database.getOfflinePosition(userData.user())
.map(position -> "x: " + (int) position.x + ", y: " + (int) position.y + ", z: " + (int) position.z .map(position -> "x: " + (int) position.x + ", y: " + (int) position.y + ", z: " + (int) position.z
+ " (" + position.world.name + + " (" + position.world.name +
((crossServer) ? "/" + position.server.name + ")" : ")")) ((crossServer) ? "/" + position.server.name + ")" : ")"))
@@ -41,7 +41,7 @@ public class PlanHook extends PluginHook {
private void registerDataExtension() { private void registerDataExtension() {
try { try {
ExtensionService.getInstance().register(new PlanDataExtension(database, plugin.getSettings().crossServer)); ExtensionService.getInstance().register(new PlanDataExtension(database, plugin.getSettings().isCrossServer()));
} catch (IllegalStateException planIsNotEnabled) { } catch (IllegalStateException planIsNotEnabled) {
logger.log(Level.SEVERE, "Plan extension hook failed to register. Plan is not enabled.", planIsNotEnabled); logger.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
@@ -71,7 +71,7 @@ public class EventListener {
*/ */
private CompletableFuture<Void> handleInboundTeleport(@NotNull OnlineUser onlineUser) { private CompletableFuture<Void> handleInboundTeleport(@NotNull OnlineUser onlineUser) {
// If the server is in proxy mode, check if the player is teleporting cross-server and handle // If the server is in proxy mode, check if the player is teleporting cross-server and handle
if (plugin.getSettings().crossServer) { if (plugin.getSettings().isCrossServer()) {
return plugin.getDatabase().getCurrentTeleport(onlineUser).thenAccept(teleport -> { return plugin.getDatabase().getCurrentTeleport(onlineUser).thenAccept(teleport -> {
if (teleport.isEmpty()) { if (teleport.isEmpty()) {
return; return;
@@ -82,10 +82,10 @@ public class EventListener {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition(); final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (bedPosition.isEmpty()) { if (bedPosition.isEmpty()) {
plugin.getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(plugin.getServerName())) plugin.getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(plugin.getServerName()))
.ifPresent(position -> onlineUser.teleportLocally(position, plugin.getSettings().asynchronousTeleports)); .ifPresent(position -> onlineUser.teleportLocally(position, plugin.getSettings().isAsynchronousTeleports()));
onlineUser.sendTranslatableMessage("block.minecraft.spawn.not_valid"); onlineUser.sendTranslatableMessage("block.minecraft.spawn.not_valid");
} else { } else {
onlineUser.teleportLocally(bedPosition.get(), plugin.getSettings().asynchronousTeleports); onlineUser.teleportLocally(bedPosition.get(), plugin.getSettings().isAsynchronousTeleports());
} }
plugin.getDatabase().setCurrentTeleport(onlineUser, null).thenRunAsync(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null).thenRunAsync(() ->
plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null))); plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null)));
@@ -133,7 +133,7 @@ public class EventListener {
*/ */
protected final void handlePlayerDeath(@NotNull OnlineUser onlineUser) { protected final void handlePlayerDeath(@NotNull OnlineUser onlineUser) {
// Set the player's last position to where they died // Set the player's last position to where they died
if (plugin.getSettings().backCommandReturnByDeath if (plugin.getSettings().isBackCommandReturnByDeath()
&& onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) {
plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition()); plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition());
} }
@@ -146,7 +146,7 @@ public class EventListener {
*/ */
protected final void handlePlayerRespawn(@NotNull OnlineUser onlineUser) { protected final void handlePlayerRespawn(@NotNull OnlineUser onlineUser) {
// Display the return by death via /back notification // Display the return by death via /back notification
if (plugin.getSettings().backCommandReturnByDeath if (plugin.getSettings().isBackCommandReturnByDeath()
&& onlineUser.hasPermission(Permission.COMMAND_BACK.node) && onlineUser.hasPermission(Permission.COMMAND_BACK.node)
&& onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) { && onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) {
plugin.getLocales().getLocale("return_by_death_notification") plugin.getLocales().getLocale("return_by_death_notification")
@@ -154,7 +154,7 @@ public class EventListener {
} }
// Respawn the player cross-server if needed // Respawn the player cross-server if needed
if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) { if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning()) {
plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> { plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> {
if (!respawnPosition.server.equals(plugin.getServerName())) { if (!respawnPosition.server.equals(plugin.getServerName())) {
Teleport.builder(plugin, onlineUser) Teleport.builder(plugin, onlineUser)
@@ -174,7 +174,7 @@ public class EventListener {
* @param sourcePosition the source {@link Position} they came from * @param sourcePosition the source {@link Position} they came from
*/ */
protected final void handlePlayerTeleport(@NotNull OnlineUser onlineUser, @NotNull Position sourcePosition) { protected final void handlePlayerTeleport(@NotNull OnlineUser onlineUser, @NotNull Position sourcePosition) {
if (!plugin.getSettings().backCommandSaveOnTeleportEvent) return; if (!plugin.getSettings().isBackCommandSaveOnTeleportEvent()) return;
plugin.getDatabase().getUserData(onlineUser.uuid) plugin.getDatabase().getUserData(onlineUser.uuid)
.thenAccept(userData -> userData.ifPresent(data -> plugin.getDatabase() .thenAccept(userData -> userData.ifPresent(data -> plugin.getDatabase()
@@ -188,7 +188,7 @@ public class EventListener {
* @param position the new spawn point * @param position the new spawn point
*/ */
protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) { protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) {
if (plugin.getSettings().crossServer && plugin.getSettings().globalRespawning) { if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning()) {
plugin.getDatabase().setRespawnPosition(onlineUser, position); plugin.getDatabase().setRespawnPosition(onlineUser, position);
} }
} }
@@ -0,0 +1,98 @@
package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.ValidationException;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
public class HomesManager {
private final HuskHomes plugin;
protected HomesManager(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
public void createHome(@NotNull User owner, @NotNull String name, @NotNull Position position, boolean overwrite) throws ValidationException {
final Optional<Home> existingHome = plugin.getDatabase().getHome(owner, name);
if (existingHome.isPresent() && !overwrite) {
throw new ValidationException(ValidationException.ValidationError.NAME_TAKEN);
}
if (!plugin.getValidator().isValidName(name)) {
throw new ValidationException(ValidationException.ValidationError.NAME_INVALID);
}
final Home home = existingHome
.map(existing -> {
existing.x = position.x;
existing.y = position.y;
existing.z = position.z;
existing.world = position.world;
existing.server = position.server;
existing.yaw = position.yaw;
existing.pitch = position.pitch;
return existing;
})
.orElse(new Home(position, new PositionMeta(name, ""), owner));
plugin.getDatabase().saveHome(home);
}
public void deleteHome(@NotNull User owner, @NotNull String name) throws ValidationException {
final Optional<Home> home = plugin.getDatabase().getHome(owner, name);
if (home.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
}
plugin.getDatabase().deleteHome(home.get().uuid);
}
public void relocateHome(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException {
createHome(owner, name, position, true);
}
public void renameHome(@NotNull User owner, @NotNull String name, @NotNull String newName) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
}
if (!plugin.getValidator().isValidName(newName)) {
throw new ValidationException(ValidationException.ValidationError.NAME_INVALID);
}
final Home home = optionalHome.get();
home.meta.name = newName;
plugin.getDatabase().saveHome(home);
}
public void updateHomeDescription(@NotNull User owner, @NotNull String name, @NotNull String description) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
}
if (!plugin.getValidator().isValidDescription(description)) {
throw new ValidationException(ValidationException.ValidationError.DESCRIPTION_INVALID);
}
final Home home = optionalHome.get();
home.meta.description = description;
plugin.getDatabase().saveHome(home);
}
public void updateHomePrivacy(@NotNull User owner, @NotNull String name, boolean isPublic) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
}
final Home home = optionalHome.get();
home.isPublic = isPublic;
plugin.getDatabase().saveHome(home);
}
}
@@ -0,0 +1,34 @@
package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
public class Manager {
private final HuskHomes plugin;
private final HomesManager homes;
private final WarpsManager warps;
private final UsersManager users;
public Manager(@NotNull HuskHomes plugin) {
this.plugin = plugin;
this.homes = new HomesManager(plugin);
this.warps = new WarpsManager(plugin);
this.users = new UsersManager(plugin);
}
@NotNull
public HomesManager homes() {
return homes;
}
@NotNull
public WarpsManager warps() {
return warps;
}
@NotNull
public UsersManager users() {
return users;
}
}
@@ -0,0 +1,15 @@
package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.User;
import org.jetbrains.annotations.NotNull;
public class UsersManager {
protected UsersManager(@NotNull HuskHomes plugin) {
}
public void ensureUser(@NotNull User user) {
}
}
@@ -0,0 +1,83 @@
package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.ValidationException;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.Warp;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
public class WarpsManager {
private final HuskHomes plugin;
protected WarpsManager(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
public void createWarp(@NotNull String name, @NotNull Position position, boolean overwrite) {
final Optional<Warp> existingWarp = plugin.getDatabase().getWarp(name);
if (existingWarp.isPresent() && !overwrite) {
throw new ValidationException(ValidationException.ValidationError.NAME_TAKEN);
}
if (!plugin.getValidator().isValidName(name)) {
throw new ValidationException(ValidationException.ValidationError.NAME_INVALID);
}
final Warp warp = existingWarp
.map(existing -> {
existing.x = position.x;
existing.y = position.y;
existing.z = position.z;
existing.world = position.world;
existing.server = position.server;
existing.yaw = position.yaw;
existing.pitch = position.pitch;
return existing;
})
.orElse(new Warp(position, new PositionMeta(name, "")));
plugin.getDatabase().saveWarp(warp);
}
public void deleteWarp(@NotNull String name) {
final Optional<Warp> warp = plugin.getDatabase().getWarp(name);
if (warp.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
}
plugin.getDatabase().deleteWarp(warp.get().uuid);
}
public void relocateWarp(@NotNull String name, @NotNull Position position) {
createWarp(name, position, true);
}
public void renameHome(@NotNull String name, @NotNull String newName) throws ValidationException {
final Optional<Warp> optionalWarp = plugin.getDatabase().getWarp(name);
if (optionalWarp.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
}
if (!plugin.getValidator().isValidName(newName)) {
throw new ValidationException(ValidationException.ValidationError.NAME_INVALID);
}
final Warp warp = optionalWarp.get();
warp.meta.name = newName;
plugin.getDatabase().saveWarp(warp);
}
public void setWarpDescription(@NotNull String name, @NotNull String description) {
final Optional<Warp> optionalWarp = plugin.getDatabase().getWarp(name);
if (optionalWarp.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
}
final Warp warp = optionalWarp.get();
warp.meta.description = description;
plugin.getDatabase().saveWarp(warp);
}
}
@@ -57,7 +57,7 @@ public abstract class Messenger implements AutoCloseable {
this.processingMessages = new HashMap<>(); this.processingMessages = new HashMap<>();
this.onlinePlayerNamesRequests = new ArrayList<>(); this.onlinePlayerNamesRequests = new ArrayList<>();
this.onlineServersRequests = new ArrayList<>(); this.onlineServersRequests = new ArrayList<>();
this.clusterId = implementor.getSettings().clusterId; this.clusterId = implementor.getSettings().getClusterId();
this.plugin = implementor; this.plugin = implementor;
} }
@@ -157,14 +157,14 @@ public class Request {
public CompletableFuture<Optional<Request>> send(@NotNull OnlineUser sender, @NotNull HuskHomes plugin) { public CompletableFuture<Optional<Request>> send(@NotNull OnlineUser sender, @NotNull HuskHomes plugin) {
this.sender = sender.username; this.sender = sender.username;
this.clusterId = plugin.getSettings().clusterId; this.clusterId = plugin.getSettings().getClusterId();
return plugin.getMessenger().sendMessage(sender, this); return plugin.getMessenger().sendMessage(sender, this);
} }
public void reply(@NotNull OnlineUser sender, @NotNull Payload payload, @NotNull HuskHomes plugin) { public void reply(@NotNull OnlineUser sender, @NotNull Payload payload, @NotNull HuskHomes plugin) {
this.targetPlayer = this.sender; this.targetPlayer = this.sender;
this.sender = sender.username; this.sender = sender.username;
this.clusterId = plugin.getSettings().clusterId; this.clusterId = plugin.getSettings().getClusterId();
this.payload = payload; this.payload = payload;
this.relayType = RelayType.REPLY; this.relayType = RelayType.REPLY;
plugin.getMessenger().sendReply(sender, this); plugin.getMessenger().sendReply(sender, this);
@@ -1,443 +0,0 @@
package net.william278.huskhomes.position;
import net.william278.huskhomes.Cache;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.hook.MapHook;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.util.RegexUtil;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/**
* Cross-platform manager for validating homes and warps and updating them as necessary
*/
public class SavedPositionManager {
private final HuskHomes plugin;
public SavedPositionManager(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
/**
* Tries to create a {@link Home} for a {@link User} at the specified {@link Position} from supplied
* {@link PositionMeta} data and add it to the database
*
* @param homeMeta metadata about the home
* @param homeOwner the owner of the home
* @param position where the home should be set
* @return a future supplying the {@link SaveResult}; the result of setting the home
*/
public CompletableFuture<SaveResult> setHome(@NotNull PositionMeta homeMeta, @NotNull User homeOwner,
@NotNull Position position) {
return plugin.getDatabase().getHome(homeOwner, homeMeta.name).thenApplyAsync(optionalHome ->
validateMeta(homeMeta).map(resultType -> new SaveResult(resultType, Optional.empty())).orElseGet(() -> {
if (optionalHome.isEmpty()) {
// Handle setting a new home
final Home home = new Home(position, homeMeta, homeOwner);
return plugin.getEventDispatcher().dispatchHomeSaveEvent(home).thenApplyAsync(event -> {
if (event.isCancelled()) {
return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty());
}
final Cache cache = plugin.getCache();
cache.homes.putIfAbsent(home.owner.uuid, new ArrayList<>());
cache.homes.get(home.owner.uuid).add(home.meta.name);
cache.privateHomeLists.remove(home.owner.username);
return plugin.getDatabase().saveHome(home).thenApplyAsync(value ->
new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(home))).join();
}).join();
} else if (plugin.getSettings().overwriteExistingHomesWarps) {
// Handle overwriting existing homes if the option is enabled
final Home existingHome = optionalHome.get();
updateHomePosition(existingHome, position).thenApplyAsync(result -> {
if (result) {
if (existingHome.isPublic) {
plugin.getMapHook().ifPresent(hook -> hook.updateHome(existingHome));
}
return new SaveResult(SaveResult.ResultType.SUCCESS_OVERWRITTEN, Optional.of(existingHome));
}
return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty());
}).join();
}
return new SaveResult(SaveResult.ResultType.FAILED_DUPLICATE, Optional.empty());
}));
}
/**
* Tries to delete a {@link User}'s home by given name
*
* @param homeOwner the owner of the home
* @param homeName the name of the home
* @return a future supplying a boolean; {@code true} if the home was deleted, otherwise {@code false}
* if the home name was invalid.
*/
public CompletableFuture<Boolean> deleteHome(@NotNull User homeOwner, @NotNull String homeName) {
return plugin.getDatabase().getHome(homeOwner, homeName).thenApplyAsync(optionalHome -> {
if (optionalHome.isPresent()) {
return plugin.getEventDispatcher().dispatchHomeDeleteEvent(optionalHome.get()).thenApplyAsync(event -> {
if (event.isCancelled()) {
return false;
}
final Home home = event.getHome();
return plugin.getDatabase().deleteHome(home.uuid).thenApplyAsync(ignored -> {
final Cache cache = plugin.getCache();
cache.homes.computeIfPresent(home.owner.uuid, (ownerUUID, homeNames) -> {
homeNames.remove(home.meta.name);
return homeNames;
});
cache.privateHomeLists.remove(home.owner.username);
cache.publicHomeLists.clear();
plugin.getMapHook().ifPresent(hook -> hook.removeHome(home));
return true;
}).join();
}).join();
}
return false;
});
}
public CompletableFuture<Integer> deleteAllHomes(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> plugin.getEventDispatcher().dispatchDeleteAllHomesEvent(user).join().isCancelled())
.thenApply(cancelled -> plugin.getDatabase().deleteAllHomes(user)
.thenApply(result -> {
final Cache cache = plugin.getCache();
cache.homes.remove(user.uuid);
cache.privateHomeLists.remove(user.username);
cache.publicHomeLists.clear();
plugin.getMapHook().ifPresent(hook -> hook.clearHomes(user));
return result;
}).join());
}
/**
* Tries to update an existing home with new metadata
*
* @param home the home to update
* @param newHomeMeta the new metadata for the home
* @return a future supplying the {@link SaveResult}; the result of updating the home
*/
public CompletableFuture<SaveResult> updateHomeMeta(@NotNull Home home, @NotNull PositionMeta newHomeMeta) {
return CompletableFuture.supplyAsync(() -> {
if (!home.meta.name.equals(newHomeMeta.name) && plugin.getDatabase().getHome(home.owner, newHomeMeta.name).join().isPresent()) {
return new SaveResult(SaveResult.ResultType.FAILED_DUPLICATE, Optional.empty());
}
final String existingHomeName = home.meta.name;
return validateMeta(newHomeMeta).map(resultType ->
new SaveResult(resultType, Optional.empty())).orElseGet(() -> {
home.meta = newHomeMeta;
return plugin.getEventDispatcher().dispatchHomeSaveEvent(home).thenApplyAsync(event -> {
if (event.isCancelled()) {
return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty());
}
final Cache cache = plugin.getCache();
if (!existingHomeName.equals(newHomeMeta.name)) {
cache.homes.get(home.owner.uuid).remove(existingHomeName);
cache.homes.get(home.owner.uuid).add(newHomeMeta.name);
}
cache.privateHomeLists.remove(home.owner.username);
cache.publicHomeLists.clear();
if (home.isPublic) {
plugin.getMapHook().ifPresent(hook -> hook.updateHome(home));
}
return plugin.getDatabase().saveHome(home).thenApplyAsync(value ->
new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(home))).join();
}).join();
});
});
}
/**
* Tries to update the position of a {@link User}'s home
*
* @param home the home to update
* @param newPosition the new position for the home
* @return a future supplying the {@link SaveResult}; the result of updating the home
*/
public CompletableFuture<Boolean> updateHomePosition(@NotNull Home home, @NotNull Position newPosition) {
home.update(newPosition);
return plugin.getEventDispatcher().dispatchHomeSaveEvent(home).thenApplyAsync(event -> {
if (event.isCancelled()) {
return false;
}
if (home.isPublic) {
plugin.getMapHook().ifPresent(hook -> hook.updateHome(home));
}
return plugin.getDatabase().saveHome(home).thenApplyAsync(ignored -> true).join();
});
}
/**
* Tries to change the privacy of a {@link User}'s home by given name
*
* @param home the home to update
* @param isHomePublic whether the home should be public or not
* @return a future supplying a boolean; {@code true} if the privacy was changed, otherwise {@code false}
*/
public CompletableFuture<Boolean> updateHomePrivacy(@NotNull Home home, final boolean isHomePublic) {
home.isPublic = isHomePublic;
return plugin.getEventDispatcher().dispatchHomeSaveEvent(home).thenApplyAsync(event -> {
if (event.isCancelled()) {
return false;
}
// Save the home to database and propagate updates to cache and map hook
return plugin.getDatabase().saveHome(home).thenApplyAsync(ignored -> {
final Cache cache = plugin.getCache();
if (home.isPublic) {
cache.publicHomes.putIfAbsent(home.owner.username, new ArrayList<>());
cache.publicHomes.get(home.owner.username).add(home.meta.name);
plugin.getMapHook().ifPresent(hook -> hook.updateHome(home));
} else {
if (cache.publicHomes.containsKey(home.owner.username)) {
cache.publicHomes.get(home.owner.username).remove(home.meta.name);
}
plugin.getMapHook().ifPresent(hook -> hook.removeHome(home));
}
cache.privateHomeLists.remove(home.owner.username);
cache.publicHomeLists.clear();
return true;
}).join();
});
}
/**
* Tries to create a server {@link Warp} at the specified {@link Position} from supplied
* {@link PositionMeta} data and add it to the database
*
* @param warpMeta metadata about the warp
* @param position where the warp should be set
* @return a future supplying the {@link SaveResult}; the result of setting the warp
*/
public CompletableFuture<SaveResult> setWarp(@NotNull PositionMeta warpMeta, @NotNull Position position) {
return plugin.getDatabase().getWarp(warpMeta.name).thenApplyAsync(optionalWarp ->
validateMeta(warpMeta).map(resultType -> new SaveResult(resultType, Optional.empty())).orElseGet(() -> {
if (optionalWarp.isEmpty()) {
// Handle setting new warps
final Warp warp = new Warp(position, warpMeta);
return plugin.getEventDispatcher().dispatchWarpSaveEvent(warp).thenApplyAsync(event -> {
if (event.isCancelled()) {
return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty());
}
final Cache cache = plugin.getCache();
cache.warps.add(warp.meta.name);
cache.warpLists.clear();
plugin.getMapHook().ifPresent(hook -> hook.updateWarp(warp));
return plugin.getDatabase().saveWarp(warp).thenApplyAsync(ignored ->
new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(warp))).join();
}).join();
} else if (plugin.getSettings().overwriteExistingHomesWarps) {
// Handle overwriting existing warps if the option is enabled
final Warp existingWarp = optionalWarp.get();
updateWarpPosition(existingWarp, position).thenApplyAsync(result -> {
if (result) {
plugin.getMapHook().ifPresent(hook -> hook.updateWarp(existingWarp));
return new SaveResult(SaveResult.ResultType.SUCCESS_OVERWRITTEN, Optional.of(existingWarp));
}
return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty());
}).join();
}
return new SaveResult(SaveResult.ResultType.FAILED_DUPLICATE, Optional.empty());
}));
}
/**
* Tries to delete a warp by given name
*
* @param warpName the name of the warp
* @return a future supplying a boolean; {@code true} if the warp was deleted, otherwise {@code false}
* if the warp name was invalid.
*/
public CompletableFuture<Boolean> deleteWarp(@NotNull String warpName) {
return plugin.getDatabase().getWarp(warpName).thenApplyAsync(optionalWarp -> {
if (optionalWarp.isPresent()) {
return plugin.getEventDispatcher().dispatchWarpDeleteEvent(optionalWarp.get()).thenApplyAsync(event -> {
if (event.isCancelled()) {
return false;
}
// Delete the warp from database and propagate updates to cache and map hook
final Warp warp = event.getWarp();
return plugin.getDatabase().deleteWarp(warp.uuid).thenApplyAsync(ignored -> {
final Cache cache = plugin.getCache();
cache.warps.remove(warp.meta.name);
cache.warpLists.clear();
plugin.getMapHook().ifPresent(hook -> hook.removeWarp(warp));
return true;
}).join();
}).join();
}
return false;
});
}
public CompletableFuture<Integer> deleteAllWarps() {
return CompletableFuture.supplyAsync(() -> plugin.getEventDispatcher().dispatchDeleteAllWarpsEvent().join().isCancelled())
.thenApply(cancelled -> plugin.getDatabase().deleteAllWarps()
.thenApply(result -> {
plugin.getCache().warps.clear();
plugin.getCache().warpLists.clear();
plugin.getMapHook().ifPresent(MapHook::clearWarps);
return result;
}).join());
}
/**
* Tries to update an existing warp with new metadata
*
* @param warp the warp to update
* @param newWarpMeta the new metadata for the home
* @return a future supplying the {@link SaveResult}; the result of updating the warp
*/
public CompletableFuture<SaveResult> updateWarpMeta(@NotNull Warp warp, @NotNull PositionMeta newWarpMeta) {
return CompletableFuture.supplyAsync(() -> {
if (!warp.meta.name.equals(newWarpMeta.name) && plugin.getDatabase().getWarp(newWarpMeta.name).join().isPresent()) {
return new SaveResult(SaveResult.ResultType.FAILED_DUPLICATE, Optional.empty());
}
final String existingWarpName = warp.meta.name;
return validateMeta(newWarpMeta).map(resultType ->
new SaveResult(resultType, Optional.empty())).orElseGet(() -> {
warp.meta = newWarpMeta;
return plugin.getEventDispatcher().dispatchWarpSaveEvent(warp).thenApplyAsync(event -> {
if (event.isCancelled()) {
return new SaveResult(SaveResult.ResultType.FAILED_EVENT_CANCELLED, Optional.empty());
}
final Cache cache = plugin.getCache();
if (!existingWarpName.equals(newWarpMeta.name)) {
cache.warps.remove(existingWarpName);
cache.warps.add(newWarpMeta.name);
}
cache.warpLists.clear();
plugin.getMapHook().ifPresent(hook -> hook.updateWarp(warp));
return plugin.getDatabase().saveWarp(warp).thenApplyAsync(value ->
new SaveResult(SaveResult.ResultType.SUCCESS, Optional.of(warp))).join();
}).join();
});
});
}
/**
* Tries to update the position of a warp
*
* @param warp the warp to update
* @param newPosition the new position for the warp
* @return a future supplying the {@link SaveResult}; the result of updating the warp
*/
public CompletableFuture<Boolean> updateWarpPosition(@NotNull Warp warp, @NotNull Position newPosition) {
warp.update(newPosition);
return plugin.getEventDispatcher().dispatchWarpSaveEvent(warp).thenApplyAsync(event -> {
if (event.isCancelled()) {
return false;
}
plugin.getMapHook().ifPresent(hook -> hook.updateWarp(warp));
return plugin.getDatabase().saveWarp(warp).thenApplyAsync(ignored -> true).join();
});
}
/**
* Validates {@link PositionMeta} to ensure it can be added to the database
*
* @param positionMeta the {@link PositionMeta} to validate
* @return An optional. If the {@link PositionMeta} is invalid, this will contain a {@link SaveResult.ResultType}
* identifying which constraint is violated by the metadata
*/
private Optional<SaveResult.ResultType> validateMeta(@NotNull PositionMeta positionMeta) {
if (positionMeta.name.length() > 16) {
return Optional.of(SaveResult.ResultType.FAILED_NAME_LENGTH);
}
if (!plugin.getSettings().allowUnicodeNames) {
if (!RegexUtil.NAME_PATTERN.matcher(positionMeta.name).matches()) {
return Optional.of(SaveResult.ResultType.FAILED_NAME_CHARACTERS);
}
}
if (positionMeta.name.contains(".")) {
return Optional.of(SaveResult.ResultType.FAILED_NAME_CHARACTERS);
}
if (positionMeta.description.length() > 255) {
return Optional.of(SaveResult.ResultType.FAILED_DESCRIPTION_LENGTH);
}
if (!plugin.getSettings().allowUnicodeDescriptions) {
if (!RegexUtil.DESCRIPTION_PATTERN.matcher(positionMeta.description).matches()) {
return Optional.of(SaveResult.ResultType.FAILED_DESCRIPTION_CHARACTERS);
}
}
return Optional.empty();
}
/**
* A record of information about the result of setting or updating a {@link SavedPosition} in the form of a warp or home
*
* @param resultType The {@link ResultType} of the result returned, indicating success
* @param savedPosition The {@link Position} of the saved position, if the result is {@link ResultType#SUCCESS}, otherwise {@link Optional#empty()}
*/
public record SaveResult(@NotNull ResultType resultType, @NotNull Optional<SavedPosition> savedPosition) {
/**
* Indicates the result of setting a warp or home
*/
public enum ResultType {
/**
* The home or warp was successfully set
*/
SUCCESS(true),
/**
* A home or warp was attempted to be set, but one already exists with the same name (for the user in the
* case of homes), so the existing position was updated instead.
* <p>
*
* @implNote This will only fire if the {@link Settings#overwriteExistingHomesWarps} config value is
* set to {@code true}
*/
SUCCESS_OVERWRITTEN(true),
/**
* The position was not set; one by this name has already been set (for the user in the case of homes)
* <p>
*
* @implNote This will only fire if the {@link Settings#overwriteExistingHomesWarps} config value is
* set to {@code false}
*/
FAILED_DUPLICATE(false),
/**
* The position was not set or updated; the name exceeds the maximum length
*/
FAILED_NAME_LENGTH(false),
/**
* The position was not set or updated; the description exceeds the maximum length
*/
FAILED_DESCRIPTION_LENGTH(false),
/**
* The position was not set or updated; the name uses illegal characters
*/
FAILED_NAME_CHARACTERS(false),
/**
* The position was not set or updated; the description uses illegal characters
*/
FAILED_DESCRIPTION_CHARACTERS(false),
/**
* The position was not set or updated; the save event was cancelled by a plugin
*/
FAILED_EVENT_CANCELLED(false);
public final boolean successful;
ResultType(final boolean successful) {
this.successful = successful;
}
}
}
}
@@ -22,10 +22,10 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
public NormalDistributionEngine(@NotNull HuskHomes implementor) { public NormalDistributionEngine(@NotNull HuskHomes implementor) {
super(implementor, "Normal Distribution"); super(implementor, "Normal Distribution");
this.radius = implementor.getSettings().rtpRadius; this.radius = implementor.getSettings().getRtpRadius();
this.spawnRadius = implementor.getSettings().rtpSpawnRadius; this.spawnRadius = implementor.getSettings().getRtpSpawnRadius();
this.mean = implementor.getSettings().rtpDistributionMean; this.mean = implementor.getSettings().getRtpDistributionMean();
this.standardDeviation = implementor.getSettings().rtpDistributionStandardDeviation; this.standardDeviation = implementor.getSettings().getRtpDistributionStandardDeviation();
} }
/** /**
@@ -85,7 +85,7 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
} }
@Override @Override
protected Optional<Position> generatePosition(@NotNull World world, @NotNull String[] args) { protected Optional<Position> getRandomPosition(@NotNull World world, @NotNull String[] args) {
Optional<Location> location = generateSafeLocation(world).join(); Optional<Location> location = generateSafeLocation(world).join();
int attempts = 0; int attempts = 0;
while (location.isEmpty()) { while (location.isEmpty()) {
@@ -7,7 +7,6 @@ import org.jetbrains.annotations.NotNull;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
/** /**
* Represents an engine for generating random position targets * Represents an engine for generating random position targets
@@ -64,23 +63,7 @@ public abstract class RandomTeleportEngine {
* @param args The arguments to pass to the random teleport engine * @param args The arguments to pass to the random teleport engine
* @return The position, optionally, which will be empty if the random teleport engine timed out after a * @return The position, optionally, which will be empty if the random teleport engine timed out after a
* {@link #randomTimeout configured number of attempts} * {@link #randomTimeout configured number of attempts}
* @implNote This is run asynchronously (i.e. not on the main server thread)
*/ */
protected abstract Optional<Position> generatePosition(@NotNull World world, @NotNull String[] args); public abstract Optional<Position> getRandomPosition(@NotNull World world, @NotNull String[] args);
/**
* Gets a random position in the {@link World}, supplying a future to be completed with the optional position
* is found, or empty if the operation times out after a number of attempts.
*
* @param world The world to find a random position in
* @param args The arguments to pass to the random teleport engine
* @return A {@link CompletableFuture} containing the random position, if one is found in
* {@link #randomTimeout configured number of attempts}, or if the operation times out after 10 seconds
*/
public CompletableFuture<Optional<Position>> getRandomPosition(@NotNull World world, @NotNull String[] args) {
return CompletableFuture.supplyAsync(() -> generatePosition(world, args))
.orTimeout(10, TimeUnit.SECONDS)
.exceptionally(e -> Optional.empty());
}
} }
@@ -25,10 +25,10 @@ public class RedisWorker {
public JedisPool jedisPool; public JedisPool jedisPool;
public RedisWorker(@NotNull Settings settings) { public RedisWorker(@NotNull Settings settings) {
this.host = settings.redisHost; this.host = settings.getRedisHost();
this.port = settings.redisPort; this.port = settings.getRedisPort();
this.password = settings.redisPassword != null ? settings.redisPassword : ""; this.password = settings.getRedisPassword() != null ? settings.getRedisPassword() : "";
this.ssl = settings.redisUseSsl && !(this.host.equalsIgnoreCase("localhost") this.ssl = settings.isRedisUseSsl() && !(this.host.equalsIgnoreCase("localhost")
|| this.host.equalsIgnoreCase("127.0.0.1")); || this.host.equalsIgnoreCase("127.0.0.1"));
} }
@@ -127,7 +127,7 @@ public class RequestManager {
public CompletableFuture<Optional<TeleportRequest>> sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser, public CompletableFuture<Optional<TeleportRequest>> sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser,
@NotNull TeleportRequest.RequestType requestType) { @NotNull TeleportRequest.RequestType requestType) {
final TeleportRequest request = new TeleportRequest(requester, requestType, final TeleportRequest request = new TeleportRequest(requester, requestType,
Instant.now().getEpochSecond() + plugin.getSettings().teleportRequestExpiryTime); Instant.now().getEpochSecond() + plugin.getSettings().getTeleportRequestExpiryTime());
final Optional<OnlineUser> localTarget = plugin.findOnlinePlayer(targetUser); final Optional<OnlineUser> localTarget = plugin.findOnlinePlayer(targetUser);
if (localTarget.isPresent()) { if (localTarget.isPresent()) {
if (localTarget.get().equals(requester)) { if (localTarget.get().equals(requester)) {
@@ -138,7 +138,7 @@ public class RequestManager {
} }
// If the player couldn't be found locally, send the request cross-server // If the player couldn't be found locally, send the request cross-server
if (plugin.getSettings().crossServer) { if (plugin.getSettings().isCrossServer()) {
// Find the matching networked target // Find the matching networked target
return plugin.getMessenger().findPlayer(requester, targetUser).thenApplyAsync(networkedTarget -> { return plugin.getMessenger().findPlayer(requester, targetUser).thenApplyAsync(networkedTarget -> {
if (networkedTarget.isEmpty()) { if (networkedTarget.isEmpty()) {
@@ -279,7 +279,7 @@ public class RequestManager {
final Optional<OnlineUser> localRequester = plugin.findOnlinePlayer(request.requesterName); final Optional<OnlineUser> localRequester = plugin.findOnlinePlayer(request.requesterName);
if (localRequester.isPresent()) { if (localRequester.isPresent()) {
handleLocalRequestResponse(localRequester.get(), request); handleLocalRequestResponse(localRequester.get(), request);
} else if (plugin.getSettings().crossServer) { } else if (plugin.getSettings().isCrossServer()) {
// Ensure the sender is still online // Ensure the sender is still online
plugin.getMessenger() plugin.getMessenger()
.findPlayer(recipient, request.requesterName) .findPlayer(recipient, request.requesterName)
@@ -313,7 +313,7 @@ public class RequestManager {
// If the request is a tpa here request, teleport the recipient to the sender // If the request is a tpa here request, teleport the recipient to the sender
if (accepted && request.type == TeleportRequest.RequestType.TPA_HERE) { if (accepted && request.type == TeleportRequest.RequestType.TPA_HERE) {
// Strict /tpahere requests will teleport to where the sender was when typing the command // Strict /tpahere requests will teleport to where the sender was when typing the command
if (plugin.getSettings().strictTpaHereRequests) { if (plugin.getSettings().isStrictTpaHereRequests()) {
Teleport.builder(plugin, recipient) Teleport.builder(plugin, recipient)
.setTarget(request.requesterPosition) .setTarget(request.requesterPosition)
.toTimedTeleport() .toTimedTeleport()
@@ -173,13 +173,13 @@ public class Teleport {
// Dispatch the teleport event and update the player's last position // Dispatch the teleport event and update the player's last position
plugin.getEventDispatcher().dispatchTeleportEvent(this); plugin.getEventDispatcher().dispatchTeleportEvent(this);
if (updateLastPosition && !plugin.getSettings().backCommandSaveOnTeleportEvent && type == TeleportType.TELEPORT) { if (updateLastPosition && !plugin.getSettings().isBackCommandSaveOnTeleportEvent() && type == TeleportType.TELEPORT) {
plugin.getDatabase().setLastPosition(teleporter, teleporter.getPosition()); plugin.getDatabase().setLastPosition(teleporter, teleporter.getPosition());
} }
// If the target position is local, finalize economy transactions and teleport the player // If the target position is local, finalize economy transactions and teleport the player
if (!plugin.getSettings().crossServer || target.server.equals(plugin.getServerName())) { if (!plugin.getSettings().isCrossServer() || target.server.equals(plugin.getServerName())) {
return teleporter.teleportLocally(target, plugin.getSettings().asynchronousTeleports); return teleporter.teleportLocally(target, plugin.getSettings().isAsynchronousTeleports());
} }
// If the target position is on another server, execute a cross-server teleport // If the target position is on another server, execute a cross-server teleport
@@ -89,7 +89,7 @@ public class TeleportBuilder {
.findOnlinePlayer(teleporterUsername) .findOnlinePlayer(teleporterUsername)
.map(onlineUser -> (User) onlineUser) .map(onlineUser -> (User) onlineUser)
.or(() -> { .or(() -> {
if (plugin.getSettings().crossServer) { if (plugin.getSettings().isCrossServer()) {
return plugin.getMessenger() return plugin.getMessenger()
.findPlayer(executor, teleporterUsername).join() .findPlayer(executor, teleporterUsername).join()
.map(username -> new User(UUID.randomUUID(), username)); .map(username -> new User(UUID.randomUUID(), username));
@@ -208,7 +208,7 @@ public class TeleportBuilder {
return CompletableFuture.supplyAsync(() -> { return CompletableFuture.supplyAsync(() -> {
final User teleporter = this.teleporter.join(); final User teleporter = this.teleporter.join();
final Position target = this.target.join(); final Position target = this.target.join();
final int warmupTime = plugin.getSettings().teleportWarmupTime; final int warmupTime = plugin.getSettings().getTeleportWarmupTime();
if (!(teleporter instanceof OnlineUser onlineUser)) { if (!(teleporter instanceof OnlineUser onlineUser)) {
throw new IllegalStateException("Timed teleports can only be executed for local users"); throw new IllegalStateException("Timed teleports can only be executed for local users");
@@ -232,7 +232,7 @@ public class TeleportBuilder {
if (localPlayer.isPresent()) { if (localPlayer.isPresent()) {
return CompletableFuture.supplyAsync(() -> Optional.of(localPlayer.get().getPosition())); return CompletableFuture.supplyAsync(() -> Optional.of(localPlayer.get().getPosition()));
} }
if (plugin.getSettings().crossServer) { if (plugin.getSettings().isCrossServer()) {
return plugin.getMessenger() return plugin.getMessenger()
.findPlayer(executor, playerName) .findPlayer(executor, playerName)
.thenApplyAsync(foundPlayer -> { .thenApplyAsync(foundPlayer -> {
@@ -180,7 +180,7 @@ public class TimedTeleport extends Teleport {
* @param message the message to send * @param message the message to send
*/ */
private void sendStatusMessage(@NotNull MineDown message) { private void sendStatusMessage(@NotNull MineDown message) {
switch (plugin.getSettings().teleportWarmupDisplay) { switch (plugin.getSettings().getTeleportWarmupDisplay()) {
case ACTION_BAR -> teleporter.sendActionBar(message); case ACTION_BAR -> teleporter.sendActionBar(message);
case SUBTITLE -> teleporter.sendTitle(message, true); case SUBTITLE -> teleporter.sendTitle(message, true);
case TITLE -> teleporter.sendTitle(message, false); case TITLE -> teleporter.sendTitle(message, false);
@@ -0,0 +1,16 @@
package net.william278.huskhomes.util;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public interface TaskRunner {
void runAsync(@NotNull Runnable runnable);
<T> CompletableFuture<T> supplyAsync(@NotNull Supplier<T> supplier);
void runSync(@NotNull Runnable runnable);
@NotNull
HuskHomes getPlugin();
}
@@ -0,0 +1,51 @@
package net.william278.huskhomes.util;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
public class Validator {
public static final int MAX_NAME_LENGTH = 16;
public static final int MIN_NAME_LENGTH = 1;
public static final int MAX_DESCRIPTION_LENGTH = 256;
private final HuskHomes plugin;
public Validator(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
/**
* Check if a name is valid
*
* @param name The name to check
* @return True if the name is valid as per the plugin settings, false otherwise
*/
public boolean isValidName(@NotNull String name) {
return (isAsciiOnly(name) || plugin.getSettings().isAllowUnicodeNames())
&& !containsWhitespace(name)
&& name.length() <= MAX_NAME_LENGTH && name.length() >= MIN_NAME_LENGTH;
}
/**
* Validate home and warp descriptions
*
* @param meta The meta to validate
* @return Whether the meta is valid against the plugin settings
*/
public boolean isValidDescription(@NotNull String meta) {
return (isAsciiOnly(meta) || plugin.getSettings().isAllowUnicodeDescriptions())
&& meta.length() <= MAX_DESCRIPTION_LENGTH;
}
// Check if a string contains only ASCII characters
private static boolean isAsciiOnly(@NotNull String string) {
return string.matches("\\A\\p{ASCII}*\\z");
}
// Check if a string contains whitespace
private static boolean containsWhitespace(@NotNull String string) {
return string.matches(".*\\s.*");
}
}