Use Annotaml instead of BoostedYaml for config loading

This commit is contained in:
William committed 2022-08-15 00:56:00 +01:00
1 parent 979d57e7b2
commit c1df905b41
14 files changed
+268 -381

No files matched your search

+3 -1
View File
@@ -9,7 +9,8 @@ dependencies {
compileOnly 'commons-io:commons-io:2.11.0' compileOnly 'commons-io:commons-io:2.11.0'
compileOnly 'com.google.guava:guava:31.1-jre' compileOnly 'com.google.guava:guava:31.1-jre'
compileOnly 'de.themoep:minedown:1.7.1-SNAPSHOT' compileOnly 'de.themoep:minedown:1.7.1-SNAPSHOT'
compileOnly 'dev.dejvokep:boosted-yaml:1.3' compileOnly 'org.jetbrains:annotations:23.0.0'
compileOnly 'net.william278:Annotaml:1.0.1'
} }
shadowJar { shadowJar {
@@ -18,6 +19,7 @@ shadowJar {
relocate 'org.jetbrains', 'net.william278.huskhomes.libraries' relocate 'org.jetbrains', 'net.william278.huskhomes.libraries'
relocate 'org.intellij', 'net.william278.huskhomes.libraries' relocate 'org.intellij', 'net.william278.huskhomes.libraries'
relocate 'com.zaxxer', 'net.william278.huskhomes.libraries' relocate 'com.zaxxer', 'net.william278.huskhomes.libraries'
relocate 'net.william278.annotaml', 'net.william278.huskhomes.libraries.annotaml'
relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson' relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson'
relocate 'io.papermc.lib', 'net.william278.huskhomes.libraries.paperlib' relocate 'io.papermc.lib', 'net.william278.huskhomes.libraries.paperlib'
@@ -1,13 +1,10 @@
package net.william278.huskhomes; package net.william278.huskhomes;
import dev.dejvokep.boostedyaml.YamlDocument; import net.william278.annotaml.Annotaml;
import dev.dejvokep.boostedyaml.dvs.versioning.BasicVersioning; import net.william278.annotaml.AnnotamlException;
import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings;
import dev.dejvokep.boostedyaml.settings.general.GeneralSettings;
import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings;
import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings;
import net.william278.huskhomes.cache.Cache; import net.william278.huskhomes.cache.Cache;
import net.william278.huskhomes.command.*; import net.william278.huskhomes.command.BukkitCommand;
import net.william278.huskhomes.command.BukkitCommandType;
import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.database.Database; import net.william278.huskhomes.database.Database;
@@ -18,11 +15,11 @@ import net.william278.huskhomes.listener.EventListener;
import net.william278.huskhomes.messenger.NetworkMessenger; import net.william278.huskhomes.messenger.NetworkMessenger;
import net.william278.huskhomes.messenger.PluginMessenger; import net.william278.huskhomes.messenger.PluginMessenger;
import net.william278.huskhomes.messenger.RedisMessenger; import net.william278.huskhomes.messenger.RedisMessenger;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.BukkitPlayer; import net.william278.huskhomes.player.BukkitPlayer;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.position.SavedPositionManager; import net.william278.huskhomes.position.SavedPositionManager;
import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.teleport.BukkitTeleportManager; import net.william278.huskhomes.teleport.BukkitTeleportManager;
import net.william278.huskhomes.teleport.TeleportManager; import net.william278.huskhomes.teleport.TeleportManager;
import net.william278.huskhomes.util.*; import net.william278.huskhomes.util.*;
@@ -37,7 +34,6 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -79,7 +75,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
if (server != null) { if (server != null) {
return CompletableFuture.supplyAsync(() -> server); return CompletableFuture.supplyAsync(() -> server);
} }
if (!getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { if (!getSettings().crossServer) {
server = new Server("server"); server = new Server("server");
return CompletableFuture.supplyAsync(() -> server); return CompletableFuture.supplyAsync(() -> server);
} }
@@ -116,7 +112,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().join()); initialized.set(reload().join());
if (initialized.get()) { if (initialized.get()) {
logger.showDebugLogs(settings.getBooleanValue(Settings.ConfigOption.DEBUG_LOGGING)); logger.showDebugLogs(settings.debugLogging);
getLoggingAdapter().log(Level.INFO, "Successfully loaded plugin configuration settings & locales"); getLoggingAdapter().log(Level.INFO, "Successfully loaded plugin configuration settings & locales");
} else { } else {
throw new HuskHomesInitializationException("Failed to load plugin configuration settings and/or locales"); throw new HuskHomesInitializationException("Failed to load plugin configuration settings and/or locales");
@@ -124,16 +120,11 @@ 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 String databaseType = settings.getStringValue(Settings.ConfigOption.DATA_STORAGE_TYPE); final Settings.DatabaseType databaseType = settings.databaseType;
this.database = switch (databaseType == null ? "MYSQL" : databaseType.toUpperCase()) { this.database = switch (databaseType == null ? Settings.DatabaseType.MYSQL : databaseType) {
case "MYSQL" -> new MySqlDatabase(settings, logger, resourceReader); case MYSQL -> new MySqlDatabase(settings, logger, resourceReader);
case "SQLITE" -> new SqLiteDatabase(settings, logger, resourceReader); case SQLITE -> new SqLiteDatabase(settings, logger, resourceReader);
default -> null;
}; };
if (database == null) {
throw new HuskHomesInitializationException("An invalid database type was specified. " +
"Please check the database type in the configuration file.");
}
initialized.set(this.database.initialize()); initialized.set(this.database.initialize());
if (initialized.get()) { if (initialized.get()) {
getLoggingAdapter().log(Level.INFO, "Successfully established a connection to the database"); getLoggingAdapter().log(Level.INFO, "Successfully established a connection to the database");
@@ -143,17 +134,12 @@ 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().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { if (getSettings().crossServer) {
getLoggingAdapter().log(Level.INFO, "Initializing the network messenger..."); getLoggingAdapter().log(Level.INFO, "Initializing the network messenger...");
networkMessenger = switch (settings.getStringValue(Settings.ConfigOption.MESSENGER_TYPE).toUpperCase()) { networkMessenger = switch (settings.messengerType) {
case "PLUGIN_MESSAGE", "PLUGINMESSAGE" -> new PluginMessenger(); case PLUGIN_MESSAGE -> new PluginMessenger();
case "REDIS", "JEDIS" -> new RedisMessenger(); case REDIS -> new RedisMessenger();
default -> null;
}; };
if (networkMessenger == null) {
throw new HuskHomesInitializationException("An invalid network messenger type was specified. " +
"Please check the network messenger type in the configuration file.");
}
networkMessenger.initialize(this); networkMessenger.initialize(this);
getLoggingAdapter().log(Level.INFO, "Successfully initialized the network messenger."); getLoggingAdapter().log(Level.INFO, "Successfully initialized the network messenger.");
} }
@@ -200,7 +186,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
} }
// Check for updates // Check for updates
if (settings.getBooleanValue(Settings.ConfigOption.CHECK_FOR_UPDATES)) { if (settings.checkForUpdates) {
getLoggingAdapter().log(Level.INFO, "Checking for updates..."); getLoggingAdapter().log(Level.INFO, "Checking for updates...");
CompletableFuture.runAsync(() -> new UpdateChecker(getPluginVersion(), getLoggingAdapter()).logToConsole()); CompletableFuture.runAsync(() -> new UpdateChecker(getPluginVersion(), getLoggingAdapter()).logToConsole());
} }
@@ -317,13 +303,19 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
public CompletableFuture<Boolean> reload() { public CompletableFuture<Boolean> reload() {
return CompletableFuture.supplyAsync(() -> { return CompletableFuture.supplyAsync(() -> {
try { try {
this.settings = Settings.load(YamlDocument.create(new File(getDataFolder(), "config.yml"), Objects.requireNonNull(resourceReader.getResource("config.yml")), GeneralSettings.builder().setUseDefaults(false).build(), LoaderSettings.builder().setAutoUpdate(true).build(), DumperSettings.builder().setEncoding(DumperSettings.Encoding.UNICODE).build(), UpdaterSettings.builder().setVersioning(new BasicVersioning("config_version")).build())); this.settings = Annotaml.reload(new File(getDataFolder(), "config.yml"),
new Settings(), Annotaml.LoaderOptions.builder().copyDefaults(true));
this.locales = Locales.load(YamlDocument.create(new File(getDataFolder(), "messages-" + settings.getStringValue(Settings.ConfigOption.LANGUAGE) + ".yml"), Objects.requireNonNull(resourceReader.getResource("locales/" + settings.getStringValue(Settings.ConfigOption.LANGUAGE) + ".yml")))); this.locales = Annotaml.reload(new File(getDataFolder(), "messages-" + settings.language + ".yml"),
Objects.requireNonNull(resourceReader.getResource("locales/" + settings.language + ".yml")),
Locales.class, Annotaml.LoaderOptions.builder().copyDefaults(true));
return true; return true;
} catch (IOException | NullPointerException e) { } catch (AnnotamlException e) {
getLoggingAdapter().log(Level.SEVERE, "Failed to load data from the config", e); getLoggingAdapter().log(Level.SEVERE, "Failed to load data from the config", e);
return false; return false;
} catch (NullPointerException e) {
getLoggingAdapter().log(Level.SEVERE, "An unsupported language code was supplied, could not load locales", e);
return false;
} }
}); });
} }
-1
View File
@@ -8,7 +8,6 @@ libraries:
- 'redis.clients:jedis:${jedis_version}' - 'redis.clients:jedis:${jedis_version}'
- 'mysql:mysql-connector-java:8.0.29' - 'mysql:mysql-connector-java:8.0.29'
- 'org.xerial:sqlite-jdbc:3.36.0.3' - 'org.xerial:sqlite-jdbc:3.36.0.3'
- 'dev.dejvokep:boosted-yaml:1.3'
- 'org.apache.commons:commons-text:1.9' - 'org.apache.commons:commons-text:1.9'
commands: commands:
+2 -1
View File
@@ -2,12 +2,12 @@ dependencies {
implementation 'commons-io:commons-io:2.11.0' implementation 'commons-io:commons-io:2.11.0'
implementation 'de.themoep:minedown:1.7.1-SNAPSHOT' implementation 'de.themoep:minedown:1.7.1-SNAPSHOT'
implementation 'com.google.code.gson:gson:2.9.0' implementation 'com.google.code.gson:gson:2.9.0'
implementation 'net.william278:Annotaml:1.0.1'
implementation('com.zaxxer:HikariCP:5.0.1') { implementation('com.zaxxer:HikariCP:5.0.1') {
exclude module: 'slf4j-api' exclude module: 'slf4j-api'
} }
compileOnly 'org.apache.commons:commons-text:1.9' compileOnly 'org.apache.commons:commons-text:1.9'
compileOnly 'dev.dejvokep:boosted-yaml:1.3'
compileOnly 'com.google.guava:guava:31.1-jre' compileOnly 'com.google.guava:guava:31.1-jre'
compileOnly 'redis.clients:jedis:' + jedis_version compileOnly 'redis.clients:jedis:' + jedis_version
compileOnly 'org.xerial:sqlite-jdbc:' + sqlite_driver_version compileOnly 'org.xerial:sqlite-jdbc:' + sqlite_driver_version
@@ -20,5 +20,6 @@ shadowJar {
relocate 'org.jetbrains', 'net.william278.huskhomes.libraries' relocate 'org.jetbrains', 'net.william278.huskhomes.libraries'
relocate 'org.intellij', 'net.william278.huskhomes.libraries' relocate 'org.intellij', 'net.william278.huskhomes.libraries'
relocate 'com.zaxxer', 'net.william278.huskhomes.libraries' relocate 'com.zaxxer', 'net.william278.huskhomes.libraries'
relocate 'net.william278.annotaml', 'net.william278.huskhomes.libraries.annotaml'
relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson' relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson'
} }
@@ -1,7 +1,6 @@
package net.william278.huskhomes.cache; package net.william278.huskhomes.cache;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.database.Database; import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.list.ChatList; import net.william278.huskhomes.list.ChatList;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
@@ -76,7 +75,7 @@ public class Cache {
* @param plugin the implementing plugin * @param plugin the implementing plugin
*/ */
public void updatePlayerList(@NotNull HuskHomes plugin, @NotNull OnlineUser requester) { public void updatePlayerList(@NotNull HuskHomes plugin, @NotNull OnlineUser requester) {
if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { if (plugin.getSettings().crossServer) {
assert plugin.getNetworkMessenger() != null; assert plugin.getNetworkMessenger() != null;
CompletableFuture.runAsync(() -> plugin.getNetworkMessenger(). CompletableFuture.runAsync(() -> plugin.getNetworkMessenger().
getOnlinePlayerNames(requester).thenAcceptAsync(returnedPlayerList -> { getOnlinePlayerNames(requester).thenAcceptAsync(returnedPlayerList -> {
@@ -37,7 +37,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
RegexUtil.matchDisambiguatedHomeIdentifier(homeName).ifPresentOrElse( RegexUtil.matchDisambiguatedHomeIdentifier(homeName).ifPresentOrElse(
homeIdentifier -> plugin.getDatabase().getUserDataByName(homeIdentifier.ownerName()) homeIdentifier -> plugin.getDatabase().getUserDataByName(homeIdentifier.ownerName())
.thenAccept(optionalUserData -> optionalUserData.ifPresentOrElse( .thenAccept(optionalUserData -> optionalUserData.ifPresentOrElse(
userData -> plugin.getTeleportManager().teleportToHome(onlineUser, userData.user(), homeIdentifier.ownerName()), userData -> plugin.getTeleportManager().teleportToHome(onlineUser, userData.user(), homeIdentifier.homeName()),
() -> plugin.getLocales().getLocale("error_home_invalid_other", homeIdentifier.ownerName(), homeIdentifier.homeName()) () -> plugin.getLocales().getLocale("error_home_invalid_other", homeIdentifier.ownerName(), homeIdentifier.homeName())
.ifPresent(onlineUser::sendMessage))), .ifPresent(onlineUser::sendMessage))),
() -> plugin.getTeleportManager().teleportToHome(onlineUser, onlineUser, homeName)); () -> plugin.getTeleportManager().teleportToHome(onlineUser, onlineUser, homeName));
@@ -1,27 +1,28 @@
package net.william278.huskhomes.config; package net.william278.huskhomes.config;
import de.themoep.minedown.MineDown; import de.themoep.minedown.MineDown;
import dev.dejvokep.boostedyaml.YamlDocument; import net.william278.annotaml.RootedMap;
import org.apache.commons.text.StringEscapeUtils; import net.william278.annotaml.YamlFile;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
/** /**
* Loaded locales used by the plugin to display various locales * Loaded locales used by the plugin to display various locales
*/ */
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes Locales ┃
┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ See plugin about menu for international locale credits
┣╸ Formatted in MineDown: https://github.com/Phoenix616/MineDown
┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/Translating-HuskHomes""")
public class Locales { public class Locales {
@NotNull @RootedMap
private final HashMap<String, String> rawLocales; public Map<String, String> rawLocales = new HashMap<>();
private Locales(@NotNull YamlDocument localesConfig) {
this.rawLocales = new HashMap<>();
for (String localeId : localesConfig.getRoutesAsStrings(false)) {
rawLocales.put(localeId, StringEscapeUtils.unescapeJava(localesConfig.getString(localeId)));
}
}
/** /**
* Returns an unformatted locale loaded from the locales file * Returns an unformatted locale loaded from the locales file
@@ -85,14 +86,8 @@ public class Locales {
return rawLocale; return rawLocale;
} }
/** @SuppressWarnings("unused")
* Load the locales from a BoostedYaml {@link YamlDocument} locales file public Locales() {
*
* @param localesConfig The loaded {@link YamlDocument} locales.yml file
* @return the loaded {@link Locales}
*/
public static Locales load(YamlDocument localesConfig) {
return new Locales(localesConfig);
} }
} }
@@ -1,282 +1,224 @@
package net.william278.huskhomes.config; package net.william278.huskhomes.config;
import dev.dejvokep.boostedyaml.YamlDocument; import net.william278.annotaml.EmbeddedYaml;
import net.william278.annotaml.KeyPath;
import net.william278.annotaml.YamlFile;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.Map;
import java.util.Optional;
/** /**
* Settings used for the plugin, as read from the config file * Plugin settings, read from config.yml
*/ */
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes Config ┃
┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ Information: https://william278.net/project/huskhomes
┗╸ Documentation: https://william278.net/docs/huskhomes""",
versionField = "config_version", versionNumber = 11)
public class Settings { public class Settings {
/** // Main settings
* Map of {@link ConfigOption}s read from the config file
*/
private final HashMap<ConfigOption, Object> configOptions;
// Load the settings from the document public String language = "en-gb";
private Settings(YamlDocument config) {
this.configOptions = new HashMap<>();
Arrays.stream(ConfigOption.values()).forEach(configOption -> configOptions
.put(configOption, switch (configOption.optionType) {
case BOOLEAN -> configOption.getBooleanValue(config);
case STRING -> configOption.getStringValue(config);
case DOUBLE -> configOption.getDoubleValue(config);
case FLOAT -> configOption.getFloatValue(config);
case INTEGER -> configOption.getIntValue(config);
case STRING_LIST -> configOption.getStringListValue(config);
}));
}
/** public boolean checkForUpdates = true;
* Get the value of the specified {@link ConfigOption}
*
* @param option the {@link ConfigOption} to check
* @return the value of the {@link ConfigOption} as a boolean
* @throws ClassCastException if the option is not a boolean
*/
public boolean getBooleanValue(ConfigOption option) throws ClassCastException {
return (Boolean) configOptions.get(option);
}
/** public boolean debugLogging = false;
* Get the value of the specified {@link ConfigOption}
*
* @param option the {@link ConfigOption} to check
* @return the value of the {@link ConfigOption} as a string
* @throws ClassCastException if the option is not a string
*/
public String getStringValue(ConfigOption option) throws ClassCastException {
return (String) configOptions.get(option);
}
/**
* Get the value of the specified {@link ConfigOption}
*
* @param option the {@link ConfigOption} to check
* @return the value of the {@link ConfigOption} as a double
* @throws ClassCastException if the option is not a double
*/
public double getDoubleValue(ConfigOption option) throws ClassCastException {
return (Double) configOptions.get(option);
}
/**
* Get the value of the specified {@link ConfigOption}
*
* @param option the {@link ConfigOption} to check
* @return the value of the {@link ConfigOption} as a float
* @throws ClassCastException if the option is not a float
*/
public double getFloatValue(ConfigOption option) throws ClassCastException {
return (Float) configOptions.get(option);
}
/**
* Get the value of the specified {@link ConfigOption}
*
* @param option the {@link ConfigOption} to check
* @return the value of the {@link ConfigOption} as an integer
* @throws ClassCastException if the option is not an integer
*/
public int getIntegerValue(ConfigOption option) throws ClassCastException {
return (Integer) configOptions.get(option);
}
/**
* Get the value of the specified {@link ConfigOption}
*
* @param option the {@link ConfigOption} to check
* @return the value of the {@link ConfigOption} as a string {@link List}
* @throws ClassCastException if the option is not a string list
*/
@SuppressWarnings("unchecked")
public List<String> getStringListValue(ConfigOption option) throws ClassCastException {
return (List<String>) configOptions.get(option);
}
/** // Database settings
* Load the settings from a BoostedYaml {@link YamlDocument} config file
*
* @param config The loaded {@link YamlDocument} config.yml file
* @return the loaded {@link Settings}
*/
public static Settings load(YamlDocument config) {
return new Settings(config);
}
/** @KeyPath("database.type")
* Represents an option stored by a path in config.yml public DatabaseType databaseType = DatabaseType.SQLITE;
*/
public enum ConfigOption {
LANGUAGE("language", OptionType.STRING, "en-gb"),
CHECK_FOR_UPDATES("check_for_updates", OptionType.BOOLEAN, true),
DEBUG_LOGGING("debug_logging", OptionType.BOOLEAN, false),
DATA_STORAGE_TYPE("data_storage_options.storage_type", OptionType.STRING, "SQLite"),
DATABASE_HOST("data_storage_options.mysql_credentials.host", OptionType.STRING, "localhost"),
DATABASE_PORT("data_storage_options.mysql_credentials.port", OptionType.INTEGER, 3306),
DATABASE_NAME("data_storage_options.mysql_credentials.database", OptionType.STRING, "HuskHomes"),
DATABASE_USERNAME("data_storage_options.mysql_credentials.username", OptionType.STRING, "root"),
DATABASE_PASSWORD("data_storage_options.mysql_credentials.password", OptionType.STRING, "pa55w0rd"),
DATABASE_CONNECTION_PARAMS("data_storage_options.mysql_credentials.params", OptionType.STRING, "?autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull"),
DATABASE_CONNECTION_POOL_MAX_SIZE("data_storage_options.connection_pool_options.maximum_pool_size", OptionType.INTEGER, 10), @KeyPath("database.mysql.credentials.host")
DATABASE_CONNECTION_POOL_MIN_IDLE("data_storage_options.connection_pool_options.minimum_idle", OptionType.INTEGER, 10), public String mySqlHost = "localhost";
DATABASE_CONNECTION_POOL_MAX_LIFETIME("data_storage_options.connection_pool_options.maximum_lifetime", OptionType.INTEGER, 1800000),
DATABASE_CONNECTION_POOL_KEEPALIVE("data_storage_options.connection_pool_options.keepalive_time", OptionType.INTEGER, 0),
DATABASE_CONNECTION_POOL_TIMEOUT("data_storage_options.connection_pool_options.connection_timeout", OptionType.INTEGER, 5000),
DATABASE_PLAYER_TABLE_NAME("data_storage_options.table_names.player_data", OptionType.STRING, "huskhomes_player_data"), @KeyPath("database.mysql.credentials.port")
DATABASE_POSITIONS_TABLE_NAME("data_storage_options.table_names.position_data", OptionType.STRING, "huskhomes_position_data"), public int mySqlPort = 3306;
DATABASE_SAVED_POSITIONS_TABLE_NAME("data_storage_options.table_names.saved_positions_data", OptionType.STRING, "huskhomes_saved_positions_data"),
DATABASE_HOMES_TABLE_NAME("data_storage_options.table_names.home_data", OptionType.STRING, "huskhomes_home_data"),
DATABASE_WARPS_TABLE_NAME("data_storage_options.table_names.warp_data", OptionType.STRING, "huskhomes_warp_data"),
DATABASE_TELEPORTS_TABLE_NAME("data_storage_options.table_names.teleport_data", OptionType.STRING, "huskhomes_teleport_data"),
@KeyPath("database.mysql.credentials.database")
public String mySqlDatabase = "HuskHomes";
MAX_HOMES("general.max_sethomes", OptionType.INTEGER, 10), @KeyPath("database.mysql.credentials.username")
AUTO_COMPLETE_PLAYER_NAMES("general.auto_complete_player_names", OptionType.BOOLEAN, true), public String mySqlUsername = "root";
HOME_LIMIT_PERMISSION_STACKING("general.home_limit_permission_stacking", OptionType.BOOLEAN, false),
TELEPORT_WARMUP_TIME("general.teleport_warmup_time", OptionType.INTEGER, 5),
TELEPORT_WARMUP_DISPLAY_SLOT("general.teleport_warmup_display", OptionType.STRING, "ACTION_BAR"),
TELEPORT_REQUEST_EXPIRY_TIME("general.teleport_request_expiry_time", OptionType.INTEGER, 60),
ALLOW_UNICODE_DESCRIPTIONS("general.allow_unicode_descriptions", OptionType.BOOLEAN, true),
USE_PAPERLIB_IF_AVAILABLE("general.use_paperlib_if_available", OptionType.BOOLEAN, true),
TELEPORT_COMPLETE_SOUND("general.sounds.teleportation_complete", OptionType.STRING, "ENTITY_ENDERMAN_TELEPORT"), @KeyPath("database.mysql.credentials.password")
TELEPORT_WARMUP_SOUND("general.sounds.teleportation_warmup", OptionType.STRING, "BLOCK_NOTE_BLOCK_BANJO"), public String mySqlPassword = "pa55w0rd";
TELEPORT_CANCELLED_SOUND("general.sounds.teleportation_cancelled", OptionType.STRING, "ENTITY_ITEM_BREAK"),
PRIVATE_HOME_LIST_ITEMS_PER_PAGE("general.lists.private_homes_per_page", OptionType.INTEGER, 10), @KeyPath("database.mysql.credentials.parameters")
PUBLIC_HOME_LIST_ITEMS_PER_PAGE("general.lists.public_homes_per_page", OptionType.INTEGER, 10), public String mySqlConnectionParameters = "?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
WARP_LIST_ITEMS_PER_PAGE("general.lists.warps_per_page", OptionType.INTEGER, 10),
HELP_MENU_HIDE_COMMANDS_WITHOUT_PERMISSION("general.help_menu.hide_commands_without_permission", OptionType.BOOLEAN, true), @KeyPath("database.mysql.connection_pool")
HELP_MENU_HIDE_HUSKHOMES_COMMAND("general.help_menu.hide_huskhomes_command", OptionType.BOOLEAN, false), public ConnectionPoolOptions mySqlPoolOptions = new ConnectionPoolOptions();
ENABLE_PROXY_MODE("proxy_options.enable_proxy_mode", OptionType.BOOLEAN, false), @KeyPath("database.table_names")
CLUSTER_ID("proxy_options.cluster_id", OptionType.STRING, ""), public Map<String, String> tableNames = Map.of(
MESSENGER_TYPE("proxy_options.messenger_type", OptionType.STRING, "PLUGIN_MESSAGE"), TableName.PLAYER_DATA.name().toLowerCase(), TableName.PLAYER_DATA.defaultName,
TableName.POSITION_DATA.name().toLowerCase(), TableName.POSITION_DATA.defaultName,
TableName.SAVED_POSITION_DATA.name().toLowerCase(), TableName.SAVED_POSITION_DATA.defaultName,
TableName.HOME_DATA.name().toLowerCase(), TableName.HOME_DATA.defaultName,
TableName.WARP_DATA.name().toLowerCase(), TableName.WARP_DATA.defaultName,
TableName.TELEPORT_DATA.name().toLowerCase(), TableName.TELEPORT_DATA.defaultName
);
REDIS_HOST("proxy_options.redis_credentials.host", OptionType.STRING, "localhost"),
REDIS_PORT("proxy_options.redis_credentials.port", OptionType.INTEGER, 6379),
REDIS_PASSWORD("proxy_options.redis_credentials.password", OptionType.STRING, ""),
REDIS_USE_SSL("proxy_options.redis_credentials.use_ssl", OptionType.BOOLEAN, false);
/**
* The path in the config.yml file to the value
*/
@NotNull @NotNull
public final String configPath; public String getTableName(@NotNull TableName tableName) {
return Optional.ofNullable(tableNames.get(tableName.name().toLowerCase())).orElse(tableName.defaultName);
/**
* The {@link OptionType} of this option
*/
@NotNull
public final OptionType optionType;
/**
* The default value of this option if not set in config
*/
@Nullable
private final Object defaultValue;
ConfigOption(@NotNull String configPath, @NotNull OptionType optionType, @Nullable Object defaultValue) {
this.configPath = configPath;
this.optionType = optionType;
this.defaultValue = defaultValue;
} }
ConfigOption(@NotNull String configPath, @NotNull OptionType optionType) {
this.configPath = configPath; // General settings
this.optionType = optionType;
this.defaultValue = null; @KeyPath("general.max_homes")
public int maxHomes = 10;
@KeyPath("general.max_public_homes")
public int maxPublicHomes = 10;
@KeyPath("general.teleport_warmup_time")
public int teleportWarmupTime = 5;
@KeyPath("general.teleport_warmup_display")
public MessageDisplayType teleportWarmupDisplay = MessageDisplayType.ACTION_BAR;
@KeyPath("general.teleport_request_expiry_time")
public int teleportRequestExpiryTime = 60;
@KeyPath("general.list_items_per_page")
public int listItemsPerPage = 10;
@KeyPath("general.allow_unicode_names")
public boolean allowUnicodeNames = false;
@KeyPath("general.allow_unicode_descriptions")
public boolean allowUnicodeDescriptions = true;
@KeyPath("general.handle_vanished_players")
public boolean handleVanishedPlayers = true;
@KeyPath("general.use_paper_lib")
public boolean usePaperLib = true;
@KeyPath("general.play_sound_effects")
public boolean playSoundEffects = true;
@KeyPath("general.sound_effects")
public Map<String, String> soundEffects = Map.of(
SoundEffectAction.TELEPORTATION_COMPLETE.name().toLowerCase(), SoundEffectAction.TELEPORTATION_COMPLETE.defaultSoundEffect,
SoundEffectAction.TELEPORTATION_WARMUP.name().toLowerCase(), SoundEffectAction.TELEPORTATION_WARMUP.defaultSoundEffect,
SoundEffectAction.TELEPORTATION_CANCELLED.name().toLowerCase(), SoundEffectAction.TELEPORTATION_CANCELLED.defaultSoundEffect
);
public Optional<String> getSoundEffect(@NotNull SoundEffectAction action) {
return Optional.ofNullable(soundEffects.get(action.name().toLowerCase()));
}
// Cross-server settings
@KeyPath("cross_server.enabled")
public boolean crossServer = false;
@KeyPath("cross_server.messenger_type")
public MessengerType messengerType = MessengerType.PLUGIN_MESSAGE;
@KeyPath("cross_server.cluster_id")
public String clusterId = "";
@KeyPath("cross_server.redis_credentials.host")
public String redisHost = "localhost";
@KeyPath("cross_server.redis_credentials.port")
public int redisPort = 6379;
@KeyPath("cross_server.redis_credentials.password")
public String redisPassword = "";
@KeyPath("cross_server.redis_credentials.use_ssl")
public boolean redisUseSsl = false;
@SuppressWarnings("unused")
public Settings() {
} }
/** /**
* Get the value at the path specified (or return default if set), as a string * Options for use in establishing pooled connections to a database
*
* @param config The {@link YamlDocument} config file
* @return the value defined in the config, as a string
*/ */
public String getStringValue(@NotNull YamlDocument config) { @EmbeddedYaml
return defaultValue != null public static class ConnectionPoolOptions {
? config.getString(configPath, (String) defaultValue)
: config.getString(configPath); public int size = 10;
public int idle = 10;
public long lifetime = 1800000;
public long keepalive = 0;
public long timeout = 5000;
@SuppressWarnings("unused")
public ConnectionPoolOptions() {
}
} }
/** /**
* Get the value at the path specified (or return default if set), as a boolean * Represents the names of tables in the database
*
* @param config The {@link YamlDocument} config file
* @return the value defined in the config, as a boolean
*/ */
public boolean getBooleanValue(@NotNull YamlDocument config) { public enum TableName {
return defaultValue != null PLAYER_DATA("huskhomes_player_data"),
? config.getBoolean(configPath, (Boolean) defaultValue) POSITION_DATA("huskhomes_position_data"),
: config.getBoolean(configPath); SAVED_POSITION_DATA("huskhomes_saved_position_data"),
HOME_DATA("huskhomes_home_data"),
WARP_DATA("huskhomes_warp_data"),
TELEPORT_DATA("huskhomes_teleport_data");
private final String defaultName;
TableName(@NotNull String defaultName) {
this.defaultName = defaultName;
}
} }
/** /**
* Get the value at the path specified (or return default if set), as a double * Represents where a chat message should display
*
* @param config The {@link YamlDocument} config file
* @return the value defined in the config, as a double
*/ */
public double getDoubleValue(@NotNull YamlDocument config) { public enum MessageDisplayType {
return defaultValue != null MESSAGE,
? config.getDouble(configPath, (Double) defaultValue) ACTION_BAR,
: config.getDouble(configPath); SUBTITLE
} }
/** /**
* Get the value at the path specified (or return default if set), as a float * Represents the sound effect to play when an action happens
*
* @param config The {@link YamlDocument} config file
* @return the value defined in the config, as a float
*/ */
public float getFloatValue(@NotNull YamlDocument config) { public enum SoundEffectAction {
return defaultValue != null TELEPORTATION_COMPLETE("entity_enderman_teleport"),
? config.getFloat(configPath, (Float) defaultValue) TELEPORTATION_WARMUP("block_note_block_banjo"),
: config.getFloat(configPath); TELEPORTATION_CANCELLED("entity_item_break");
private final String defaultSoundEffect;
SoundEffectAction(@NotNull String defaultSoundEffect) {
this.defaultSoundEffect = defaultSoundEffect;
}
} }
/** /**
* Get the value at the path specified (or return default if set), as an int * Identifies types of databases
*
* @param config The {@link YamlDocument} config file
* @return the value defined in the config, as an int
*/ */
public int getIntValue(@NotNull YamlDocument config) { public enum DatabaseType {
return defaultValue != null MYSQL,
? config.getInt(configPath, (Integer) defaultValue) SQLITE
: config.getInt(configPath);
} }
/** /**
* Get the value at the path specified (or return default if set), as a string {@link List} * Identifies types of network messenger
*
* @param config The {@link YamlDocument} config file
* @return the value defined in the config, as a string {@link List}
*/ */
public List<String> getStringListValue(@NotNull YamlDocument config) { public enum MessengerType {
return config.getStringList(configPath, new ArrayList<>()); PLUGIN_MESSAGE,
} REDIS
/**
* Represents the type of the object
*/
public enum OptionType {
BOOLEAN,
STRING,
DOUBLE,
FLOAT,
INTEGER,
STRING_LIST
}
} }
} }
@@ -150,18 +150,12 @@ public abstract class Database {
* @param settings {@link Settings} to fetch database configuration data from * @param settings {@link Settings} to fetch database configuration data from
*/ */
protected Database(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) { protected Database(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) {
this.playerTableName = settings. this.playerTableName = settings.getTableName(Settings.TableName.PLAYER_DATA);
getStringValue(Settings.ConfigOption.DATABASE_PLAYER_TABLE_NAME); this.positionsTableName = settings.getTableName(Settings.TableName.POSITION_DATA);
this.positionsTableName = settings. this.savedPositionsTableName = settings.getTableName(Settings.TableName.SAVED_POSITION_DATA);
getStringValue(Settings.ConfigOption.DATABASE_POSITIONS_TABLE_NAME); this.homesTableName = settings.getTableName(Settings.TableName.HOME_DATA);
this.savedPositionsTableName = settings. this.warpsTableName = settings.getTableName(Settings.TableName.WARP_DATA);
getStringValue(Settings.ConfigOption.DATABASE_SAVED_POSITIONS_TABLE_NAME); this.teleportsTableName = settings.getTableName(Settings.TableName.TELEPORT_DATA);
this.homesTableName = settings.
getStringValue(Settings.ConfigOption.DATABASE_HOMES_TABLE_NAME);
this.warpsTableName = settings.
getStringValue(Settings.ConfigOption.DATABASE_WARPS_TABLE_NAME);
this.teleportsTableName = settings.
getStringValue(Settings.ConfigOption.DATABASE_TELEPORTS_TABLE_NAME);
this.logger = logger; this.logger = logger;
this.resourceReader = resourceReader; this.resourceReader = resourceReader;
} }
@@ -27,36 +27,14 @@ import java.util.logging.Level;
@SuppressWarnings("DuplicatedCode") @SuppressWarnings("DuplicatedCode")
public class MySqlDatabase extends Database { public class MySqlDatabase extends Database {
/** public String host;
* MySQL server hostname public int port;
*/ public String database;
private final String mySqlHost; public String username;
/** public String password;
* MySQL server port public String connectionParameters;
*/
private final int mySqlPort;
/**
* Database to use on the MySQL server
*/
private final String mySqlDatabaseName;
/**
* MySQL username for accessing the database
*/
private final String mySqlUsername;
/**
* MySQL password for accessing the database
*/
private final String mySqlPassword;
/**
* Additional connection parameters, formatted as a jdbc connection string
*/
private final String mySqlConnectionParameters;
private final int hikariMaximumPoolSize; private final Settings.ConnectionPoolOptions poolOptions;
private final int hikariMinimumIdle;
private final int hikariMaximumLifetime;
private final int hikariKeepAliveTime;
private final int hikariConnectionTimeOut;
private static final String DATA_POOL_NAME = "HuskHomesHikariPool"; private static final String DATA_POOL_NAME = "HuskHomesHikariPool";
@@ -64,18 +42,13 @@ public class MySqlDatabase extends Database {
public MySqlDatabase(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) { public MySqlDatabase(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) {
super(settings, logger, resourceReader); super(settings, logger, resourceReader);
this.mySqlHost = settings.getStringValue(Settings.ConfigOption.DATABASE_HOST); this.host = settings.mySqlHost;
this.mySqlPort = settings.getIntegerValue(Settings.ConfigOption.DATABASE_PORT); this.port = settings.mySqlPort;
this.mySqlDatabaseName = settings.getStringValue(Settings.ConfigOption.DATABASE_NAME); this.database = settings.mySqlDatabase;
this.mySqlUsername = settings.getStringValue(Settings.ConfigOption.DATABASE_USERNAME); this.username = settings.mySqlUsername;
this.mySqlPassword = settings.getStringValue(Settings.ConfigOption.DATABASE_PASSWORD); this.password = settings.mySqlPassword;
this.mySqlConnectionParameters = settings.getStringValue(Settings.ConfigOption.DATABASE_CONNECTION_PARAMS); this.connectionParameters = settings.mySqlConnectionParameters;
this.poolOptions = settings.mySqlPoolOptions;
this.hikariMaximumPoolSize = settings.getIntegerValue(Settings.ConfigOption.DATABASE_CONNECTION_POOL_MAX_SIZE);
this.hikariMinimumIdle = settings.getIntegerValue(Settings.ConfigOption.DATABASE_CONNECTION_POOL_MIN_IDLE);
this.hikariMaximumLifetime = settings.getIntegerValue(Settings.ConfigOption.DATABASE_CONNECTION_POOL_MAX_LIFETIME);
this.hikariKeepAliveTime = settings.getIntegerValue(Settings.ConfigOption.DATABASE_CONNECTION_POOL_KEEPALIVE);
this.hikariConnectionTimeOut = settings.getIntegerValue(Settings.ConfigOption.DATABASE_CONNECTION_POOL_TIMEOUT);
} }
/** /**
@@ -92,20 +65,20 @@ public class MySqlDatabase extends Database {
public boolean initialize() { public boolean initialize() {
try { try {
// Create jdbc driver connection url // Create jdbc driver connection url
final String jdbcUrl = "jdbc:mysql://" + mySqlHost + ":" + mySqlPort + "/" + mySqlDatabaseName + mySqlConnectionParameters; final String jdbcUrl = "jdbc:mysql://" + host + ":" + port + "/" + database + connectionParameters;
dataSource = new HikariDataSource(); dataSource = new HikariDataSource();
dataSource.setJdbcUrl(jdbcUrl); dataSource.setJdbcUrl(jdbcUrl);
// Authenticate // Authenticate
dataSource.setUsername(mySqlUsername); dataSource.setUsername(username);
dataSource.setPassword(mySqlPassword); dataSource.setPassword(password);
// Set various additional parameters // Set various additional parameters
dataSource.setMaximumPoolSize(hikariMaximumPoolSize); dataSource.setMaximumPoolSize(poolOptions.size);
dataSource.setMinimumIdle(hikariMinimumIdle); dataSource.setMinimumIdle(poolOptions.idle);
dataSource.setMaxLifetime(hikariMaximumLifetime); dataSource.setMaxLifetime(poolOptions.lifetime);
dataSource.setKeepaliveTime(hikariKeepAliveTime); dataSource.setKeepaliveTime(poolOptions.keepalive);
dataSource.setConnectionTimeout(hikariConnectionTimeOut); dataSource.setConnectionTimeout(poolOptions.timeout);
dataSource.setPoolName(DATA_POOL_NAME); dataSource.setPoolName(DATA_POOL_NAME);
// Prepare database schema; make tables if they don't exist // Prepare database schema; make tables if they don't exist
@@ -268,20 +241,15 @@ public class MySqlDatabase extends Database {
@Override @Override
public CompletableFuture<Optional<UserData>> getUserDataByName(@NotNull String name) { public CompletableFuture<Optional<UserData>> getUserDataByName(@NotNull String name) {
return CompletableFuture.supplyAsync(() -> { return CompletableFuture.supplyAsync(() -> {
getLogger().info("Getting user data by name for " + name);
try (Connection connection = getConnection()) { try (Connection connection = getConnection()) {
getLogger().info("Got connection");
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`
FROM `%players_table%` FROM `%players_table%`
WHERE `username`=?"""))) { WHERE `username`=?"""))) {
statement.setString(1, name); statement.setString(1, name);
getLogger().info("Set str");
final ResultSet resultSet = statement.executeQuery(); final ResultSet resultSet = statement.executeQuery();
getLogger().info("Got results");
if (resultSet.next()) { if (resultSet.next()) {
getLogger().info("resultset paged to next");
return Optional.of(new UserData( return Optional.of(new UserData(
new User(UUID.fromString(resultSet.getString("uuid")), new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")), resultSet.getString("username")),
@@ -1,7 +1,6 @@
package net.william278.huskhomes.listener; package net.william278.huskhomes.listener;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -47,7 +46,7 @@ public class EventListener {
// Ensure the player is present on the database first // Ensure the player is present on the database first
plugin.getDatabase().ensureUser(onlineUser).thenRun(() -> { plugin.getDatabase().ensureUser(onlineUser).thenRun(() -> {
// 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().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { if (plugin.getSettings().crossServer) {
plugin.getDatabase().getCurrentTeleport(onlineUser) plugin.getDatabase().getCurrentTeleport(onlineUser)
.thenAccept(teleport -> teleport.ifPresent(currentTeleport -> .thenAccept(teleport -> teleport.ifPresent(currentTeleport ->
// Teleport the player locally // Teleport the player locally
@@ -87,7 +86,7 @@ public class EventListener {
plugin.getCache().homes.remove(onlineUser.uuid); plugin.getCache().homes.remove(onlineUser.uuid);
// Update the player list // Update the player list
if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { if (plugin.getSettings().crossServer) {
assert plugin.getNetworkMessenger() != null; assert plugin.getNetworkMessenger() != null;
plugin.getOnlinePlayers().stream().filter( plugin.getOnlinePlayers().stream().filter(
onlinePlayer -> !onlinePlayer.uuid.equals(onlineUser.uuid)) onlinePlayer -> !onlinePlayer.uuid.equals(onlineUser.uuid))
@@ -1,7 +1,6 @@
package net.william278.huskhomes.messenger; package net.william278.huskhomes.messenger;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Server; import net.william278.huskhomes.position.Server;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -50,7 +49,7 @@ public abstract class NetworkMessenger {
*/ */
public void initialize(@NotNull HuskHomes implementor) { public void initialize(@NotNull HuskHomes implementor) {
this.processingMessages = new HashMap<>(); this.processingMessages = new HashMap<>();
this.clusterId = implementor.getSettings().getStringValue(Settings.ConfigOption.CLUSTER_ID); this.clusterId = implementor.getSettings().clusterId;
} }
/** /**
@@ -129,9 +128,7 @@ public abstract class NetworkMessenger {
case TP_REQUEST -> { case TP_REQUEST -> {
} }
case POSITION_REQUEST -> { case POSITION_REQUEST -> message.payload = receiver.getPosition().join().toJson();
message.payload = receiver.getPosition().join().toJson();
}
} }
// Prepare reply message // Prepare reply message
@@ -4,7 +4,6 @@ import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.messenger.Message; import net.william278.huskhomes.messenger.Message;
import net.william278.huskhomes.messenger.NetworkMessenger; import net.william278.huskhomes.messenger.NetworkMessenger;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import redis.clients.jedis.Jedis; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisPoolConfig;
@@ -16,29 +15,31 @@ import java.util.concurrent.CompletableFuture;
*/ */
public class RedisWorker { public class RedisWorker {
@NotNull public String host;
private final String redisHost;
private final int redisPort; public int port;
@Nullable
private final String redisPassword; public String password;
private final boolean redisSsl;
public boolean ssl;
public JedisPool jedisPool; public JedisPool jedisPool;
public RedisWorker(@NotNull Settings settings) { public RedisWorker(@NotNull Settings settings) {
this.redisHost = settings.getStringValue(Settings.ConfigOption.REDIS_HOST); this.host = settings.redisHost;
this.redisPort = settings.getIntegerValue(Settings.ConfigOption.REDIS_PORT); this.port = settings.redisPort;
this.redisPassword = settings.getStringValue(Settings.ConfigOption.REDIS_PASSWORD).isEmpty() ? null : settings.getStringValue(Settings.ConfigOption.REDIS_PASSWORD); this.password = settings.redisPassword != null ? settings.redisPassword : "";
this.redisSsl = !redisHost.equalsIgnoreCase("localhost") && !redisHost.equalsIgnoreCase("127.0.0.1") && settings.getBooleanValue(Settings.ConfigOption.REDIS_USE_SSL); this.ssl = settings.redisUseSsl && !(this.host.equalsIgnoreCase("localhost")
|| this.host.equalsIgnoreCase("127.0.0.1"));
} }
/** /**
* Initialize the JedisPool connection * Initialize the JedisPool connection
*/ */
public void initialize() { public void initialize() {
if (redisPassword == null) { if (password.isEmpty()) {
jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort, 0, redisSsl); jedisPool = new JedisPool(new JedisPoolConfig(), host, port, 0, ssl);
} else { } else {
jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort, 0, redisPassword, redisSsl); jedisPool = new JedisPool(new JedisPoolConfig(), host, port, 0, password, ssl);
} }
} }
@@ -1,7 +1,6 @@
package net.william278.huskhomes.teleport; package net.william278.huskhomes.teleport;
import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.messenger.EmptyPayload; import net.william278.huskhomes.messenger.EmptyPayload;
import net.william278.huskhomes.messenger.Message; import net.william278.huskhomes.messenger.Message;
import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.OnlineUser;
@@ -15,7 +14,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.logging.Level;
/** /**
* Cross-platform teleportation manager * Cross-platform teleportation manager
@@ -104,7 +102,7 @@ public abstract class TeleportManager {
if (localPlayer.isPresent()) { if (localPlayer.isPresent()) {
return localPlayer.get().getPosition().thenApply(Optional::of).join(); return localPlayer.get().getPosition().thenApply(Optional::of).join();
} }
if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) { if (plugin.getSettings().crossServer) {
assert plugin.getNetworkMessenger() != null; assert plugin.getNetworkMessenger() != null;
return plugin.getNetworkMessenger().sendMessage(requester, return plugin.getNetworkMessenger().sendMessage(requester,
new Message(Message.MessageType.POSITION_REQUEST, new Message(Message.MessageType.POSITION_REQUEST,
@@ -112,7 +110,7 @@ public abstract class TeleportManager {
playerName, playerName,
new EmptyPayload(), new EmptyPayload(),
Message.MessageKind.MESSAGE, Message.MessageKind.MESSAGE,
plugin.getSettings().getStringValue(Settings.ConfigOption.CLUSTER_ID))) plugin.getSettings().clusterId))
.thenApply(reply -> Optional.of(Position.fromJson(reply.payload))).join(); .thenApply(reply -> Optional.of(Position.fromJson(reply.payload))).join();
} }
return Optional.empty(); return Optional.empty();
@@ -127,7 +125,7 @@ public abstract class TeleportManager {
*/ */
public CompletableFuture<TeleportResult> teleport(@NotNull OnlineUser onlineUser, @NotNull Position position) { public CompletableFuture<TeleportResult> teleport(@NotNull OnlineUser onlineUser, @NotNull Position position) {
return CompletableFuture.supplyAsync(() -> { return CompletableFuture.supplyAsync(() -> {
final int teleportWarmupTime = plugin.getSettings().getIntegerValue(Settings.ConfigOption.TELEPORT_WARMUP_TIME); final int teleportWarmupTime = plugin.getSettings().teleportWarmupTime;
if (!onlineUser.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node) && teleportWarmupTime > 0) { if (!onlineUser.hasPermission(Permission.BYPASS_TELEPORT_WARMUP.node) && teleportWarmupTime > 0) {
return processTimedTeleport(new TimedTeleport(onlineUser, position, teleportWarmupTime)) return processTimedTeleport(new TimedTeleport(onlineUser, position, teleportWarmupTime))
.thenApply(teleport -> { .thenApply(teleport -> {