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
+283 -396

No files matched your search

@@ -1,7 +1,6 @@
package net.william278.huskhomes.cache;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.list.ChatList;
import net.william278.huskhomes.player.OnlineUser;
@@ -76,7 +75,7 @@ public class Cache {
* @param plugin the implementing plugin
*/
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;
CompletableFuture.runAsync(() -> plugin.getNetworkMessenger().
getOnlinePlayerNames(requester).thenAcceptAsync(returnedPlayerList -> {
@@ -37,7 +37,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
RegexUtil.matchDisambiguatedHomeIdentifier(homeName).ifPresentOrElse(
homeIdentifier -> plugin.getDatabase().getUserDataByName(homeIdentifier.ownerName())
.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())
.ifPresent(onlineUser::sendMessage))),
() -> plugin.getTeleportManager().teleportToHome(onlineUser, onlineUser, homeName));
@@ -1,27 +1,28 @@
package net.william278.huskhomes.config;
import de.themoep.minedown.MineDown;
import dev.dejvokep.boostedyaml.YamlDocument;
import org.apache.commons.text.StringEscapeUtils;
import org.jetbrains.annotations.NotNull;
import net.william278.annotaml.RootedMap;
import net.william278.annotaml.YamlFile;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* 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 {
@NotNull
private final HashMap<String, String> rawLocales;
private Locales(@NotNull YamlDocument localesConfig) {
this.rawLocales = new HashMap<>();
for (String localeId : localesConfig.getRoutesAsStrings(false)) {
rawLocales.put(localeId, StringEscapeUtils.unescapeJava(localesConfig.getString(localeId)));
}
}
@RootedMap
public Map<String, String> rawLocales = new HashMap<>();
/**
* Returns an unformatted locale loaded from the locales file
@@ -85,14 +86,8 @@ public class Locales {
return rawLocale;
}
/**
* Load the locales from a BoostedYaml {@link YamlDocument} locales file
*
* @param localesConfig The loaded {@link YamlDocument} locales.yml file
* @return the loaded {@link Locales}
*/
public static Locales load(YamlDocument localesConfig) {
return new Locales(localesConfig);
@SuppressWarnings("unused")
public Locales() {
}
}
@@ -1,282 +1,224 @@
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.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 {
/**
* Map of {@link ConfigOption}s read from the config file
*/
private final HashMap<ConfigOption, Object> configOptions;
// Main settings
// Load the settings from the document
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 String language = "en-gb";
/**
* 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 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 string
* @throws ClassCastException if the option is not a string
*/
public String getStringValue(ConfigOption option) throws ClassCastException {
return (String) 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 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);
}
// Database settings
/**
* 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);
}
@KeyPath("database.type")
public DatabaseType databaseType = DatabaseType.SQLITE;
/**
* 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);
@KeyPath("database.mysql.credentials.host")
public String mySqlHost = "localhost";
@KeyPath("database.mysql.credentials.port")
public int mySqlPort = 3306;
@KeyPath("database.mysql.credentials.database")
public String mySqlDatabase = "HuskHomes";
@KeyPath("database.mysql.credentials.username")
public String mySqlUsername = "root";
@KeyPath("database.mysql.credentials.password")
public String mySqlPassword = "pa55w0rd";
@KeyPath("database.mysql.credentials.parameters")
public String mySqlConnectionParameters = "?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
@KeyPath("database.mysql.connection_pool")
public ConnectionPoolOptions mySqlPoolOptions = new ConnectionPoolOptions();
@KeyPath("database.table_names")
public Map<String, String> tableNames = Map.of(
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
);
@NotNull
public String getTableName(@NotNull TableName tableName) {
return Optional.ofNullable(tableNames.get(tableName.name().toLowerCase())).orElse(tableName.defaultName);
}
/**
* 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);
// General settings
@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() {
}
/**
* Represents an option stored by a path in config.yml
* Options for use in establishing pooled connections to a database
*/
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"),
@EmbeddedYaml
public static class ConnectionPoolOptions {
DATABASE_CONNECTION_POOL_MAX_SIZE("data_storage_options.connection_pool_options.maximum_pool_size", OptionType.INTEGER, 10),
DATABASE_CONNECTION_POOL_MIN_IDLE("data_storage_options.connection_pool_options.minimum_idle", OptionType.INTEGER, 10),
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),
public int size = 10;
public int idle = 10;
public long lifetime = 1800000;
public long keepalive = 0;
public long timeout = 5000;
DATABASE_PLAYER_TABLE_NAME("data_storage_options.table_names.player_data", OptionType.STRING, "huskhomes_player_data"),
DATABASE_POSITIONS_TABLE_NAME("data_storage_options.table_names.position_data", OptionType.STRING, "huskhomes_position_data"),
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"),
MAX_HOMES("general.max_sethomes", OptionType.INTEGER, 10),
AUTO_COMPLETE_PLAYER_NAMES("general.auto_complete_player_names", OptionType.BOOLEAN, true),
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"),
TELEPORT_WARMUP_SOUND("general.sounds.teleportation_warmup", OptionType.STRING, "BLOCK_NOTE_BLOCK_BANJO"),
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),
PUBLIC_HOME_LIST_ITEMS_PER_PAGE("general.lists.public_homes_per_page", OptionType.INTEGER, 10),
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),
HELP_MENU_HIDE_HUSKHOMES_COMMAND("general.help_menu.hide_huskhomes_command", OptionType.BOOLEAN, false),
ENABLE_PROXY_MODE("proxy_options.enable_proxy_mode", OptionType.BOOLEAN, false),
CLUSTER_ID("proxy_options.cluster_id", OptionType.STRING, ""),
MESSENGER_TYPE("proxy_options.messenger_type", OptionType.STRING, "PLUGIN_MESSAGE"),
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
public final String configPath;
/**
* 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;
@SuppressWarnings("unused")
public ConnectionPoolOptions() {
}
}
ConfigOption(@NotNull String configPath, @NotNull OptionType optionType) {
this.configPath = configPath;
this.optionType = optionType;
this.defaultValue = null;
}
/**
* Represents the names of tables in the database
*/
public enum TableName {
PLAYER_DATA("huskhomes_player_data"),
POSITION_DATA("huskhomes_position_data"),
SAVED_POSITION_DATA("huskhomes_saved_position_data"),
HOME_DATA("huskhomes_home_data"),
WARP_DATA("huskhomes_warp_data"),
TELEPORT_DATA("huskhomes_teleport_data");
/**
* Get the value at the path specified (or return default if set), as a string
*
* @param config The {@link YamlDocument} config file
* @return the value defined in the config, as a string
*/
public String getStringValue(@NotNull YamlDocument config) {
return defaultValue != null
? config.getString(configPath, (String) defaultValue)
: config.getString(configPath);
}
private final String defaultName;
/**
* Get the value at the path specified (or return default if set), as a boolean
*
* @param config The {@link YamlDocument} config file
* @return the value defined in the config, as a boolean
*/
public boolean getBooleanValue(@NotNull YamlDocument config) {
return defaultValue != null
? config.getBoolean(configPath, (Boolean) defaultValue)
: config.getBoolean(configPath);
TableName(@NotNull String defaultName) {
this.defaultName = defaultName;
}
}
/**
* Get the value at the path specified (or return default if set), as a double
*
* @param config The {@link YamlDocument} config file
* @return the value defined in the config, as a double
*/
public double getDoubleValue(@NotNull YamlDocument config) {
return defaultValue != null
? config.getDouble(configPath, (Double) defaultValue)
: config.getDouble(configPath);
}
/**
* Represents where a chat message should display
*/
public enum MessageDisplayType {
MESSAGE,
ACTION_BAR,
SUBTITLE
}
/**
* Get the value at the path specified (or return default if set), as a float
*
* @param config The {@link YamlDocument} config file
* @return the value defined in the config, as a float
*/
public float getFloatValue(@NotNull YamlDocument config) {
return defaultValue != null
? config.getFloat(configPath, (Float) defaultValue)
: config.getFloat(configPath);
}
/**
* Represents the sound effect to play when an action happens
*/
public enum SoundEffectAction {
TELEPORTATION_COMPLETE("entity_enderman_teleport"),
TELEPORTATION_WARMUP("block_note_block_banjo"),
TELEPORTATION_CANCELLED("entity_item_break");
private final String defaultSoundEffect;
/**
* Get the value at the path specified (or return default if set), as an int
*
* @param config The {@link YamlDocument} config file
* @return the value defined in the config, as an int
*/
public int getIntValue(@NotNull YamlDocument config) {
return defaultValue != null
? config.getInt(configPath, (Integer) defaultValue)
: config.getInt(configPath);
SoundEffectAction(@NotNull String defaultSoundEffect) {
this.defaultSoundEffect = defaultSoundEffect;
}
}
/**
* Get the value at the path specified (or return default if set), as a string {@link List}
*
* @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) {
return config.getStringList(configPath, new ArrayList<>());
}
/**
* Identifies types of databases
*/
public enum DatabaseType {
MYSQL,
SQLITE
}
/**
* Represents the type of the object
*/
public enum OptionType {
BOOLEAN,
STRING,
DOUBLE,
FLOAT,
INTEGER,
STRING_LIST
}
/**
* Identifies types of network messenger
*/
public enum MessengerType {
PLUGIN_MESSAGE,
REDIS
}
}
@@ -150,18 +150,12 @@ public abstract class Database {
* @param settings {@link Settings} to fetch database configuration data from
*/
protected Database(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) {
this.playerTableName = settings.
getStringValue(Settings.ConfigOption.DATABASE_PLAYER_TABLE_NAME);
this.positionsTableName = settings.
getStringValue(Settings.ConfigOption.DATABASE_POSITIONS_TABLE_NAME);
this.savedPositionsTableName = settings.
getStringValue(Settings.ConfigOption.DATABASE_SAVED_POSITIONS_TABLE_NAME);
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.playerTableName = settings.getTableName(Settings.TableName.PLAYER_DATA);
this.positionsTableName = settings.getTableName(Settings.TableName.POSITION_DATA);
this.savedPositionsTableName = settings.getTableName(Settings.TableName.SAVED_POSITION_DATA);
this.homesTableName = settings.getTableName(Settings.TableName.HOME_DATA);
this.warpsTableName = settings.getTableName(Settings.TableName.WARP_DATA);
this.teleportsTableName = settings.getTableName(Settings.TableName.TELEPORT_DATA);
this.logger = logger;
this.resourceReader = resourceReader;
}
@@ -27,36 +27,14 @@ import java.util.logging.Level;
@SuppressWarnings("DuplicatedCode")
public class MySqlDatabase extends Database {
/**
* MySQL server hostname
*/
private final String mySqlHost;
/**
* MySQL server port
*/
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;
public String host;
public int port;
public String database;
public String username;
public String password;
public String connectionParameters;
private final int hikariMaximumPoolSize;
private final int hikariMinimumIdle;
private final int hikariMaximumLifetime;
private final int hikariKeepAliveTime;
private final int hikariConnectionTimeOut;
private final Settings.ConnectionPoolOptions poolOptions;
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) {
super(settings, logger, resourceReader);
this.mySqlHost = settings.getStringValue(Settings.ConfigOption.DATABASE_HOST);
this.mySqlPort = settings.getIntegerValue(Settings.ConfigOption.DATABASE_PORT);
this.mySqlDatabaseName = settings.getStringValue(Settings.ConfigOption.DATABASE_NAME);
this.mySqlUsername = settings.getStringValue(Settings.ConfigOption.DATABASE_USERNAME);
this.mySqlPassword = settings.getStringValue(Settings.ConfigOption.DATABASE_PASSWORD);
this.mySqlConnectionParameters = settings.getStringValue(Settings.ConfigOption.DATABASE_CONNECTION_PARAMS);
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);
this.host = settings.mySqlHost;
this.port = settings.mySqlPort;
this.database = settings.mySqlDatabase;
this.username = settings.mySqlUsername;
this.password = settings.mySqlPassword;
this.connectionParameters = settings.mySqlConnectionParameters;
this.poolOptions = settings.mySqlPoolOptions;
}
/**
@@ -92,20 +65,20 @@ public class MySqlDatabase extends Database {
public boolean initialize() {
try {
// 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.setJdbcUrl(jdbcUrl);
// Authenticate
dataSource.setUsername(mySqlUsername);
dataSource.setPassword(mySqlPassword);
dataSource.setUsername(username);
dataSource.setPassword(password);
// Set various additional parameters
dataSource.setMaximumPoolSize(hikariMaximumPoolSize);
dataSource.setMinimumIdle(hikariMinimumIdle);
dataSource.setMaxLifetime(hikariMaximumLifetime);
dataSource.setKeepaliveTime(hikariKeepAliveTime);
dataSource.setConnectionTimeout(hikariConnectionTimeOut);
dataSource.setMaximumPoolSize(poolOptions.size);
dataSource.setMinimumIdle(poolOptions.idle);
dataSource.setMaxLifetime(poolOptions.lifetime);
dataSource.setKeepaliveTime(poolOptions.keepalive);
dataSource.setConnectionTimeout(poolOptions.timeout);
dataSource.setPoolName(DATA_POOL_NAME);
// Prepare database schema; make tables if they don't exist
@@ -268,20 +241,15 @@ public class MySqlDatabase extends Database {
@Override
public CompletableFuture<Optional<UserData>> getUserDataByName(@NotNull String name) {
return CompletableFuture.supplyAsync(() -> {
getLogger().info("Getting user data by name for " + name);
try (Connection connection = getConnection()) {
getLogger().info("Got connection");
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
FROM `%players_table%`
WHERE `username`=?"""))) {
statement.setString(1, name);
getLogger().info("Set str");
final ResultSet resultSet = statement.executeQuery();
getLogger().info("Got results");
if (resultSet.next()) {
getLogger().info("resultset paged to next");
return Optional.of(new UserData(
new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")),
@@ -1,7 +1,6 @@
package net.william278.huskhomes.listener;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import org.jetbrains.annotations.NotNull;
@@ -47,7 +46,7 @@ public class EventListener {
// Ensure the player is present on the database first
plugin.getDatabase().ensureUser(onlineUser).thenRun(() -> {
// 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)
.thenAccept(teleport -> teleport.ifPresent(currentTeleport ->
// Teleport the player locally
@@ -87,7 +86,7 @@ public class EventListener {
plugin.getCache().homes.remove(onlineUser.uuid);
// Update the player list
if (plugin.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) {
if (plugin.getSettings().crossServer) {
assert plugin.getNetworkMessenger() != null;
plugin.getOnlinePlayers().stream().filter(
onlinePlayer -> !onlinePlayer.uuid.equals(onlineUser.uuid))
@@ -1,7 +1,6 @@
package net.william278.huskhomes.messenger;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Server;
import org.jetbrains.annotations.NotNull;
@@ -50,7 +49,7 @@ public abstract class NetworkMessenger {
*/
public void initialize(@NotNull HuskHomes implementor) {
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 POSITION_REQUEST -> {
message.payload = receiver.getPosition().join().toJson();
}
case POSITION_REQUEST -> message.payload = receiver.getPosition().join().toJson();
}
// Prepare reply message
@@ -4,7 +4,6 @@ import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.messenger.Message;
import net.william278.huskhomes.messenger.NetworkMessenger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@@ -16,29 +15,31 @@ import java.util.concurrent.CompletableFuture;
*/
public class RedisWorker {
@NotNull
private final String redisHost;
private final int redisPort;
@Nullable
private final String redisPassword;
private final boolean redisSsl;
public String host;
public int port;
public String password;
public boolean ssl;
public JedisPool jedisPool;
public RedisWorker(@NotNull Settings settings) {
this.redisHost = settings.getStringValue(Settings.ConfigOption.REDIS_HOST);
this.redisPort = settings.getIntegerValue(Settings.ConfigOption.REDIS_PORT);
this.redisPassword = settings.getStringValue(Settings.ConfigOption.REDIS_PASSWORD).isEmpty() ? null : settings.getStringValue(Settings.ConfigOption.REDIS_PASSWORD);
this.redisSsl = !redisHost.equalsIgnoreCase("localhost") && !redisHost.equalsIgnoreCase("127.0.0.1") && settings.getBooleanValue(Settings.ConfigOption.REDIS_USE_SSL);
this.host = settings.redisHost;
this.port = settings.redisPort;
this.password = settings.redisPassword != null ? settings.redisPassword : "";
this.ssl = settings.redisUseSsl && !(this.host.equalsIgnoreCase("localhost")
|| this.host.equalsIgnoreCase("127.0.0.1"));
}
/**
* Initialize the JedisPool connection
*/
public void initialize() {
if (redisPassword == null) {
jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort, 0, redisSsl);
if (password.isEmpty()) {
jedisPool = new JedisPool(new JedisPoolConfig(), host, port, 0, ssl);
} 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;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.messenger.EmptyPayload;
import net.william278.huskhomes.messenger.Message;
import net.william278.huskhomes.player.OnlineUser;
@@ -15,7 +14,6 @@ import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
/**
* Cross-platform teleportation manager
@@ -104,7 +102,7 @@ public abstract class TeleportManager {
if (localPlayer.isPresent()) {
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;
return plugin.getNetworkMessenger().sendMessage(requester,
new Message(Message.MessageType.POSITION_REQUEST,
@@ -112,7 +110,7 @@ public abstract class TeleportManager {
playerName,
new EmptyPayload(),
Message.MessageKind.MESSAGE,
plugin.getSettings().getStringValue(Settings.ConfigOption.CLUSTER_ID)))
plugin.getSettings().clusterId))
.thenApply(reply -> Optional.of(Position.fromJson(reply.payload))).join();
}
return Optional.empty();
@@ -127,7 +125,7 @@ public abstract class TeleportManager {
*/
public CompletableFuture<TeleportResult> teleport(@NotNull OnlineUser onlineUser, @NotNull Position position) {
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) {
return processTimedTeleport(new TimedTeleport(onlineUser, position, teleportWarmupTime))
.thenApply(teleport -> {