Move to Annotaml v2, fixes to config handling

This commit is contained in:
William committed 2022-10-01 18:10:12 +01:00
1 parent 128dc990cb
commit 089642f5de
8 files changed
+137 -109

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ dependencies {
compileOnly 'redis.clients:jedis:' + jedis_version
compileOnly 'commons-io:commons-io:2.11.0'
compileOnly 'com.google.guava:guava:31.1-jre'
compileOnly 'net.william278:Annotaml:1.0.3'
compileOnly 'net.william278:Annotaml:7e8a910576'
compileOnly 'net.william278:DesertWell:1.1'
compileOnly 'com.github.MilkBowl:VaultAPI:1.7.1'
compileOnly 'us.dynmap:dynmap-api:3.1'
@@ -49,6 +49,8 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
@@ -66,7 +68,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
private Settings settings;
private Locales locales;
private BukkitLogger logger;
private BukkitResourceReader resourceReader;
private Database database;
private Cache cache;
private TeleportManager teleportManager;
@@ -110,7 +111,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
try {
// Set the logging and resource reading adapter
this.logger = new BukkitLogger(getLogger());
this.resourceReader = new BukkitResourceReader(this);
// Create adventure audience
this.audiences = BukkitAudiences.create(this);
@@ -134,6 +134,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
// Initialize the database
getLoggingAdapter().log(Level.INFO, "Attempting to establish connection to the database...");
final Settings.DatabaseType databaseType = settings.databaseType;
final BukkitResourceReader resourceReader = new BukkitResourceReader(this);
this.database = switch (databaseType == null ? Settings.DatabaseType.MYSQL : databaseType) {
case MYSQL -> new MySqlDatabase(settings, logger, resourceReader);
case SQLITE -> new SqLiteDatabase(settings, logger, resourceReader);
@@ -414,7 +415,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
public void setServerSpawn(@NotNull Location location) {
final CachedSpawn newSpawn = new CachedSpawn(location);
this.serverSpawn = newSpawn;
Annotaml.save(newSpawn, new File(getDataFolder(), "spawn.yml"));
try {
Annotaml.create(new File(getDataFolder(), "spawn.yml"), newSpawn);
} catch (IOException e) {
getLoggingAdapter().log(Level.WARNING, "Failed to save server spawn to disk", e);
}
// Update the world spawn location, too
BukkitAdapter.adaptLocation(location).ifPresent(bukkitLocation -> {
@@ -489,7 +494,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
getLoggingAdapter().log(Level.INFO, "Successfully fetched server information from the proxy (name: "
+ serverName + ", attempts: " + attempts.get() + ")");
server = new Server(serverName);
Annotaml.save(new CachedServer(serverName), new File(getDataFolder(), "server.yml"));
try {
Annotaml.create(new File(getDataFolder(), "server.yml"), new CachedServer(serverName));
} catch (IOException e) {
throw new HuskHomesException("Failed to save server information", e);
}
})
.orTimeout(5, TimeUnit.SECONDS)
.exceptionally(throwable -> {
@@ -508,27 +517,33 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes {
@Override
public CompletableFuture<Boolean> reload() {
return CompletableFuture.supplyAsync(() -> {
// Load settings and locales
this.settings = Annotaml.reload(new File(getDataFolder(), "config.yml"),
new Settings(), Annotaml.LoaderOptions.builder().copyDefaults(true));
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));
try {
// Load settings
this.settings = Annotaml.create(new File(getDataFolder(), "config.yml"), new Settings()).get();
// Load cached server from file
if (settings.crossServer) {
final File serverFile = new File(getDataFolder(), "server.yml");
if (serverFile.exists()) {
this.server = Annotaml.load(serverFile, CachedServer.class).getServer();
// Load locales from language preset default
final Locales languagePresets = Annotaml.create(Locales.class,
Objects.requireNonNull(getResource("locales/" + settings.language + ".yml"))).get();
this.locales = Annotaml.create(new File(getDataFolder(), "messages_" + settings.language + ".yml"),
languagePresets).get();
// Load cached server from file
if (settings.crossServer) {
final File serverFile = new File(getDataFolder(), "server.yml");
if (serverFile.exists()) {
this.server = Annotaml.create(serverFile, CachedServer.class).get().getServer();
}
} else {
this.server = new Server("server");
}
} else {
this.server = new Server("server");
}
// Load spawn location from file
final File spawnFile = new File(getDataFolder(), "spawn.yml");
if (spawnFile.exists()) {
this.serverSpawn = Annotaml.load(spawnFile, CachedSpawn.class);
// Load spawn location from file
final File spawnFile = new File(getDataFolder(), "spawn.yml");
if (spawnFile.exists()) {
this.serverSpawn = Annotaml.create(spawnFile, CachedSpawn.class).get();
}
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new HuskHomesException("Failed to load config data", e);
}
return true;
}).exceptionally(throwable -> {
@@ -7,6 +7,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
/**
@@ -66,7 +67,11 @@ public class BukkitUpgradeUtil {
settings.mySqlUsername = mySqlUsername;
settings.mySqlPassword = mySqlPassword;
settings.mySqlConnectionParameters = mySqlParams;
Annotaml.save(settings, new File(plugin.getDataFolder(), "config.yml"));
try {
Annotaml.create(new File(plugin.getDataFolder(), "config.yml"), settings);
} catch (IOException e) {
plugin.getLogger().log(Level.SEVERE, "Failed to upgrade HuskHomes settings from a legacy version", e);
}
}
@Nullable
+2 -1
View File
@@ -2,9 +2,10 @@ dependencies {
implementation 'commons-io:commons-io:2.11.0'
implementation 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT'
implementation 'com.google.code.gson:gson:2.9.1'
implementation 'net.william278:Annotaml:1.0.3'
implementation 'net.william278:Annotaml:7e8a910576'
implementation 'net.william278:PagineDown:1.1'
implementation 'net.william278:DesertWell:1.1'
implementation 'dev.dejvokep:boosted-yaml:1.3'
implementation('com.zaxxer:HikariCP:5.0.1') {
exclude module: 'slf4j-api'
}
@@ -1,7 +1,6 @@
package net.william278.huskhomes.config;
import de.themoep.minedown.adventure.MineDown;
import net.william278.annotaml.RootedMap;
import net.william278.annotaml.YamlFile;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.commons.text.WordUtils;
@@ -15,7 +14,7 @@ import java.util.Optional;
/**
* Loaded locales used by the plugin to display styled messages
*/
@YamlFile(header = """
@YamlFile(rootedMap = true, header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ HuskHomes Locales ┃
┃ Developed by William278 ┃
@@ -25,7 +24,9 @@ import java.util.Optional;
┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/Translations""")
public class Locales {
@RootedMap
/**
* The raw set of locales loaded from yaml
*/
public Map<String, String> rawLocales = new HashMap<>();
/**
@@ -1,8 +1,7 @@
package net.william278.huskhomes.config;
import net.william278.annotaml.EmbeddedYaml;
import net.william278.annotaml.KeyPath;
import net.william278.annotaml.YamlFile;
import net.william278.annotaml.YamlKey;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
@@ -35,31 +34,43 @@ public class Settings {
// Database settings
@KeyPath("database.type")
@YamlKey("database.type")
public DatabaseType databaseType = DatabaseType.SQLITE;
@KeyPath("database.mysql.credentials.host")
@YamlKey("database.mysql.credentials.host")
public String mySqlHost = "localhost";
@KeyPath("database.mysql.credentials.port")
@YamlKey("database.mysql.credentials.port")
public int mySqlPort = 3306;
@KeyPath("database.mysql.credentials.database")
@YamlKey("database.mysql.credentials.database")
public String mySqlDatabase = "HuskHomes";
@KeyPath("database.mysql.credentials.username")
@YamlKey("database.mysql.credentials.username")
public String mySqlUsername = "root";
@KeyPath("database.mysql.credentials.password")
@YamlKey("database.mysql.credentials.password")
public String mySqlPassword = "pa55w0rd";
@KeyPath("database.mysql.credentials.parameters")
@YamlKey("database.mysql.credentials.parameters")
public String mySqlConnectionParameters = "?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8";
@KeyPath("database.mysql.connection_pool")
public ConnectionPoolOptions mySqlPoolOptions = new ConnectionPoolOptions();
@YamlKey("database.mysql.connection_pool.size")
public int mySqlConnectionPoolSize = 12;
@KeyPath("database.table_names")
@YamlKey("database.mysql.connection_pool.idle")
public int mySqlConnectionPoolIdle = 12;
@YamlKey("database.mysql.connection_pool.lifetime")
public long mySqlConnectionPoolLifetime = 1800000;
@YamlKey("database.mysql.connection_pool.keepalive")
public long mySqlConnectionPoolKeepAlive = 0;
@YamlKey("database.mysql.connection_pool.timeout")
public long mySqlConnectionPoolTimeout = 20000;
@YamlKey("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,
@@ -77,51 +88,51 @@ public class Settings {
// General settings
@KeyPath("general.max_homes")
@YamlKey("general.max_homes")
public int maxHomes = 10;
@KeyPath("general.max_public_homes")
@YamlKey("general.max_public_homes")
public int maxPublicHomes = 10;
@KeyPath("general.stack_permission_limits")
@YamlKey("general.stack_permission_limits")
public boolean stackPermissionLimits = true;
@KeyPath("general.permission_restrict_warps")
@YamlKey("general.permission_restrict_warps")
public boolean permissionRestrictWarps = false;
@KeyPath("general.teleport_warmup_time")
@YamlKey("general.teleport_warmup_time")
public int teleportWarmupTime = 5;
@KeyPath("general.teleport_warmup_display")
@YamlKey("general.teleport_warmup_display")
public MessageDisplayType teleportWarmupDisplay = MessageDisplayType.ACTION_BAR;
@KeyPath("general.teleport_request_expiry_time")
@YamlKey("general.teleport_request_expiry_time")
public int teleportRequestExpiryTime = 60;
@KeyPath("general.strict_tpa_here_requests")
@YamlKey("general.strict_tpa_here_requests")
public boolean strictTpaHereRequests = true;
@KeyPath("general.allow_unicode_names")
@YamlKey("general.allow_unicode_names")
public boolean allowUnicodeNames = false;
@KeyPath("general.allow_unicode_descriptions")
@YamlKey("general.allow_unicode_descriptions")
public boolean allowUnicodeDescriptions = true;
@KeyPath("general.back_command_return_by_death")
@YamlKey("general.back_command_return_by_death")
public boolean backCommandReturnByDeath = true;
@KeyPath("general.back_command_save_teleport_event")
@YamlKey("general.back_command_save_teleport_event")
public boolean backCommandSaveOnTeleportEvent = false;
@KeyPath("general.list_items_per_page")
@YamlKey("general.list_items_per_page")
public int listItemsPerPage = 12;
@KeyPath("general.asynchronous_teleports")
@YamlKey("general.asynchronous_teleports")
public boolean asynchronousTeleports = true;
@KeyPath("general.play_sound_effects")
@YamlKey("general.play_sound_effects")
public boolean playSoundEffects = true;
@KeyPath("general.sound_effects")
@YamlKey("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,
@@ -137,68 +148,68 @@ public class Settings {
// Cross-server settings
@KeyPath("cross_server.enabled")
@YamlKey("cross_server.enabled")
public boolean crossServer = false;
@KeyPath("cross_server.messenger_type")
@YamlKey("cross_server.messenger_type")
public MessengerType messengerType = MessengerType.PLUGIN_MESSAGE;
@KeyPath("cross_server.cluster_id")
@YamlKey("cross_server.cluster_id")
public String clusterId = "";
@KeyPath("cross_server.global_spawn.enabled")
@YamlKey("cross_server.global_spawn.enabled")
public boolean globalSpawn = false;
@KeyPath("cross_server.global_spawn.warp_name")
@YamlKey("cross_server.global_spawn.warp_name")
public String globalSpawnName = "Spawn";
@KeyPath("cross_server.global_respawning")
@YamlKey("cross_server.global_respawning")
public boolean globalRespawning = false;
@KeyPath("cross_server.redis_credentials.host")
@YamlKey("cross_server.redis_credentials.host")
public String redisHost = "localhost";
@KeyPath("cross_server.redis_credentials.port")
@YamlKey("cross_server.redis_credentials.port")
public int redisPort = 6379;
@KeyPath("cross_server.redis_credentials.password")
@YamlKey("cross_server.redis_credentials.password")
public String redisPassword = "";
@KeyPath("cross_server.redis_credentials.use_ssl")
@YamlKey("cross_server.redis_credentials.use_ssl")
public boolean redisUseSsl = false;
// Rtp command settings
@KeyPath("rtp.cooldown_length")
@YamlKey("rtp.cooldown_length")
public int rtpCooldownLength = 10;
@KeyPath("rtp.radius")
@YamlKey("rtp.radius")
public int rtpRadius = 5000;
@KeyPath("rtp.spawn_radius")
@YamlKey("rtp.spawn_radius")
public int rtpSpawnRadius = 500;
@KeyPath("rtp.distribution_mean")
@YamlKey("rtp.distribution_mean")
public float rtpDistributionMean = 0.75f;
@KeyPath("rtp.distribution_deviation")
@YamlKey("rtp.distribution_deviation")
public float rtpDistributionStandardDeviation = 2f;
@KeyPath("rtp.location_cache_size")
@YamlKey("rtp.location_cache_size")
public int rtpLocationCacheSize = 10;
@KeyPath("rtp.restricted_worlds")
@YamlKey("rtp.restricted_worlds")
public List<String> rtpRestrictedWorlds = List.of("world_nether", "world_the_end");
// Economy settings
@KeyPath("economy.enabled")
@YamlKey("economy.enabled")
public boolean economy = false;
@KeyPath("economy.free_home_slots")
@YamlKey("economy.free_home_slots")
public int freeHomeSlots = 5;
@KeyPath("economy.costs")
@YamlKey("economy.costs")
public Map<String, Double> economyCosts = Map.of(
EconomyAction.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyAction.ADDITIONAL_HOME_SLOT.defaultCost,
EconomyAction.MAKE_HOME_PUBLIC.name().toLowerCase(), EconomyAction.MAKE_HOME_PUBLIC.defaultCost,
@@ -218,45 +229,27 @@ public class Settings {
}
// Mapping plugins
@KeyPath("map_hook.enabled")
@YamlKey("map_hook.enabled")
public boolean doMapHook = false;
@KeyPath("map_hook.map_plugin")
@YamlKey("map_hook.map_plugin")
public MappingPlugin mappingPlugin = MappingPlugin.DYNMAP;
@KeyPath("map_hook.show_public_homes")
@YamlKey("map_hook.show_public_homes")
public boolean publicHomesOnMap = true;
@KeyPath("map_hook.show_warps")
@YamlKey("map_hook.show_warps")
public boolean warpsOnMap = true;
// Disabled commands
@KeyPath("disabled_commands")
@YamlKey("disabled_commands")
public List<String> disabledCommands = Collections.emptyList();
@SuppressWarnings("unused")
public Settings() {
}
/**
* Options for use in establishing pooled connections to a database
*/
@EmbeddedYaml
public static class ConnectionPoolOptions {
public int size = 12;
public int idle = 12;
public long lifetime = 1800000;
public long keepalive = 0;
public long timeout = 20000;
@SuppressWarnings("unused")
public ConnectionPoolOptions() {
}
}
/**
* Represents the names of tables in the database
*/
@@ -33,7 +33,15 @@ public class MySqlDatabase extends Database {
public String password;
public String connectionParameters;
private final Settings.ConnectionPoolOptions poolOptions;
public int connectionPoolSize;
public int connectionPoolIdle;
public long connectionPoolLifetime;
public long connectionPoolKeepAlive;
public long connectionPoolTimeout;
private static final String DATA_POOL_NAME = "HuskHomesHikariPool";
@@ -47,7 +55,11 @@ public class MySqlDatabase extends Database {
this.username = settings.mySqlUsername;
this.password = settings.mySqlPassword;
this.connectionParameters = settings.mySqlConnectionParameters;
this.poolOptions = settings.mySqlPoolOptions;
this.connectionPoolSize = settings.mySqlConnectionPoolSize;
this.connectionPoolIdle = settings.mySqlConnectionPoolIdle;
this.connectionPoolLifetime = settings.mySqlConnectionPoolLifetime;
this.connectionPoolKeepAlive = settings.mySqlConnectionPoolKeepAlive;
this.connectionPoolTimeout = settings.mySqlConnectionPoolTimeout;
}
/**
@@ -73,11 +85,11 @@ public class MySqlDatabase extends Database {
dataSource.setPassword(password);
// Set connection pool options
dataSource.setMaximumPoolSize(poolOptions.size);
dataSource.setMinimumIdle(poolOptions.idle);
dataSource.setMaxLifetime(poolOptions.lifetime);
dataSource.setKeepaliveTime(poolOptions.keepalive);
dataSource.setConnectionTimeout(poolOptions.timeout);
dataSource.setMaximumPoolSize(connectionPoolSize);
dataSource.setMinimumIdle(connectionPoolIdle);
dataSource.setMaxLifetime(connectionPoolLifetime);
dataSource.setKeepaliveTime(connectionPoolKeepAlive);
dataSource.setConnectionTimeout(connectionPoolTimeout);
dataSource.setPoolName(DATA_POOL_NAME);
// Set additional connection pool properties
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Objects;
import java.util.Set;
@@ -18,7 +19,7 @@ public class LocalesTests {
// Load locales/en-gb.yml as an InputStream
try (InputStream localeStream = LocalesTests.class.getClassLoader().getResourceAsStream("locales/en-gb.yml")) {
Assertions.assertNotNull(localeStream, "en-gb.yml is missing from the locales folder");
final Locales englishLocales = Annotaml.load(localeStream, Locales.class);
final Locales englishLocales = Annotaml.create(Locales.class, localeStream).get();
final Set<String> keys = englishLocales.rawLocales.keySet();
// Iterate through every locale file in the locales folder
@@ -27,11 +28,11 @@ public class LocalesTests {
for (File file : Objects.requireNonNull(new File(url.getPath()).listFiles(file -> file.getName().endsWith("yml")
&& !file.getName().equals("en-gb.yml")))) {
final Set<String> fileKeys = Annotaml.load(file, Locales.class).rawLocales.keySet();
final Set<String> fileKeys = Annotaml.create(file, Locales.class).get().rawLocales.keySet();
keys.forEach(key -> Assertions.assertTrue(fileKeys.contains(key),
"Locale key " + key + " is missing from " + file.getName()));
}
} catch (IOException e) {
} catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}