diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index e52be106..1778fdaa 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -62,7 +62,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask private Settings settings; private Locales locales; private Database database; - private Cache cache; private Validator validator; private Manager manager; private EventListener eventListener; @@ -72,6 +71,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask private Set pluginHooks; private List commands; private Map> globalPlayerList; + private Set currentlyOnWarmup; private Server server; @Nullable private Broker broker; @@ -92,9 +92,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask public void onEnable() { // Create adventure audience this.audiences = BukkitAudiences.create(this); - this.validator = new Validator(this); - this.manager = new Manager(this); this.globalPlayerList = new HashMap<>(); + this.currentlyOnWarmup = new HashSet<>(); + this.validator = new Validator(this); // Load settings and locales initialize("plugin config & locale files", (plugin) -> { @@ -111,12 +111,12 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask case SQLITE -> new SqLiteDatabase(this); }; - if (!database.initialize()) { - throw new IllegalStateException("Failed to establish a connection to the database. " + - "Please check the supplied database credentials in the config file"); - } + database.initialize(); }); + // Initialize the manager + this.manager = new Manager(this); + // Initialize the network messenger if proxy mode is enabled if (getSettings().isCrossServer()) { initialize("message broker", (plugin) -> { @@ -128,7 +128,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask }); } - this.cache = new Cache(this); // todo remove setRandomTeleportEngine(new NormalDistributionEngine(this)); // Register plugin hooks (Economy, Maps, Plan) @@ -261,12 +260,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask return database; } - @NotNull - @Override - public Cache getCache() { - return cache; - } - @Override @NotNull public Validator getValidator() { @@ -375,6 +368,12 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask return globalPlayerList; } + @Override + @NotNull + public Set getCurrentlyOnWarmup() { + return currentlyOnWarmup; + } + @Override @NotNull public String getServerName() { diff --git a/common/src/main/java/net/william278/huskhomes/Cache.java b/common/src/main/java/net/william278/huskhomes/Cache.java deleted file mode 100644 index c3891b99..00000000 --- a/common/src/main/java/net/william278/huskhomes/Cache.java +++ /dev/null @@ -1,82 +0,0 @@ -package net.william278.huskhomes; - -import net.william278.huskhomes.database.Database; -import net.william278.huskhomes.teleport.TimedTeleport; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -/** - * A cache used to hold frequently accessed data (i.e. TAB-completed homes and warps) - */ -public class Cache { - - private final HuskHomes plugin; - private final Map> homes = new HashMap<>(); - private final Map> publicHomes = new HashMap<>(); - private final List warps = new ArrayList<>(); - private final Set currentlyOnWarmup = new HashSet<>(); - - /** - * Create a new cache - */ - public Cache(@NotNull HuskHomes plugin) { - this.plugin = plugin; - this.initialize(); - } - - /** - * Initialize the cache with public home and warp names - */ - public void initialize() { - final Database database = plugin.getDatabase(); - plugin.runAsync(() -> { - database.getPublicHomes().forEach(home -> { - this.getPublicHomes().putIfAbsent(home.getOwner().getUsername(), new ArrayList<>()); - this.getPublicHomes().get(home.getOwner().getUsername()).add(home.getMeta().getName()); - }); - database.getWarps().forEach(warp -> this.getWarps().add(warp.getMeta().getName())); - }); - } - - /** - * Returns if the given user is currently warming up to teleport to a home. - * - * @param userUuid The user to check. - * @return If the user is currently warming up. - * @since 3.1 - */ - public boolean isWarmingUp(@NotNull UUID userUuid) { - return this.getCurrentlyOnWarmup().contains(userUuid); - } - - - /** - * Cached home names - maps a {@link UUID} to a list of their homes - */ - public Map> getHomes() { - return homes; - } - - /** - * Cached home names - maps a username to a list of their public homes - */ - public Map> getPublicHomes() { - return publicHomes; - } - - /** - * Cached warp names - */ - public List getWarps() { - return warps; - } - - - /** - * Cached user UUIDs currently on warmup countdowns for {@link TimedTeleport}s - */ - public Set getCurrentlyOnWarmup() { - return currentlyOnWarmup; - } -} diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 48d8292b..568f9826 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -95,14 +95,6 @@ public interface HuskHomes extends TaskRunner, EventDispatcher { @NotNull Database getDatabase(); - /** - * The {@link Cache} that holds cached data - * - * @return the plugin {@link Cache} - */ - @NotNull - Cache getCache(); - /** * The {@link Validator} for validating thome names and descriptions * @@ -342,11 +334,25 @@ public interface HuskHomes extends TaskRunner, EventDispatcher { .toList(); } + @NotNull + Set getCurrentlyOnWarmup(); + + /** + * Returns if the given user is currently warming up to teleport to a home. + * + * @param userUuid The user to check. + * @return If the user is currently warming up. + */ + default boolean isWarmingUp(@NotNull UUID userUuid) { + return this.getCurrentlyOnWarmup().contains(userUuid); + } + /** * Reloads the {@link Settings} and {@link Locales} from their respective config files * - * @return a {@link CompletableFuture} that will be completed when the plugin reload is complete and if it was successful + * @return {@code true} if the reload was successful, {@code false} otherwise */ + @SuppressWarnings("BooleanMethodIsAlwaysInverted") boolean loadConfigs(); @NotNull diff --git a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java index de0b5424..2b856fec 100644 --- a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java +++ b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java @@ -110,7 +110,7 @@ public abstract class BaseHuskHomesAPI { * @since 3.0.2 */ public boolean isUserWarmingUp(@NotNull User user) { - return plugin.getCache().isWarmingUp(user.getUuid()); + return plugin.isWarmingUp(user.getUuid()); } /** diff --git a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java index 129ab0ac..8fe0de05 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java @@ -27,7 +27,7 @@ public class PublicHomeCommand extends HomeCommand { @NotNull public List suggest(@NotNull CommandUser executor, @NotNull String[] args) { if (args.length <= 2) { - return filter(reduceHomeList(plugin.getCache().getHomes()), args); + return filter(reduceHomeList(plugin.getManager().homes().getPublicHomes()), args); } return List.of(); } diff --git a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java index cf3186de..05b9333e 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java @@ -128,21 +128,21 @@ public abstract class SavedPositionCommand extends Comm case 0, 1 -> { if (args.length == 1 && args[0].contains(".")) { if (executor.hasPermission(getOtherPermission())) { - yield filter(reduceHomeList(plugin.getCache().getHomes()), args); + yield filter(reduceHomeList(plugin.getManager().homes().getUserHomes()), args); } - yield filter(reduceHomeList(plugin.getCache().getHomes()), args); + yield filter(reduceHomeList(plugin.getManager().homes().getUserHomes()), args); } if (executor instanceof OnlineUser user) { - yield filter(plugin.getCache().getHomes().get(user.getUsername()), args); + yield filter(plugin.getManager().homes().getUserHomes().get(user.getUsername()), args); } - yield filter(reduceHomeList(plugin.getCache().getHomes()), args); + yield filter(reduceHomeList(plugin.getManager().homes().getUserHomes()), args); } case 2 -> filter(arguments.stream().toList(), args); default -> List.of(); }; } else { return switch (args.length) { - case 0, 1 -> filter(plugin.getCache().getWarps(), args); + case 0, 1 -> filter(plugin.getManager().warps().getWarps(), args); case 2 -> filter(arguments.stream().toList(), args); default -> List.of(); }; diff --git a/common/src/main/java/net/william278/huskhomes/database/Database.java b/common/src/main/java/net/william278/huskhomes/database/Database.java index bb3212ac..7932633f 100644 --- a/common/src/main/java/net/william278/huskhomes/database/Database.java +++ b/common/src/main/java/net/william278/huskhomes/database/Database.java @@ -10,11 +10,13 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; -import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.SQLException; -import java.util.*; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; import java.util.stream.Collectors; /** @@ -24,84 +26,8 @@ import java.util.stream.Collectors; */ public abstract class Database { - /** - * Stores data about {@link User}s - *
    - *
  1. uuid - Primary key, unique; the user's minecraft account unique ID
  2. - *
  3. username - The user's username. Checked to be updated on login
  4. - *
  5. last_position - References positions table; where the user was when they last teleported
  6. - *
  7. offline_position - References positions table; the user's last online position. Updated on disconnect
  8. - *
  9. respawn_position - References positions table; where the user last updated their spawn point
  10. - *
  11. home_slots - An integer; the number of home slots this user has consumed (bought)
  12. - *
  13. ignoring_requests - A boolean; whether or not this user is ignoring teleport requests
  14. - *
  15. rtp_cooldown - A datetime timestamp; representing when this user can randomly teleport again
  16. - *
- */ - protected final String playerTableName; - - /** - * Stores data about {@link Position}s - *
    - *
  1. id - Primary key, auto-increment; the id representing the position
  2. - *
  3. x - The double-precision x-coordinate of the position
  4. - *
  5. y - The double-precision y-coordinate of the position
  6. - *
  7. z - The double-precision z-coordinate of the position
  8. - *
  9. yaw - The float-precision yaw facing directional value of the position
  10. - *
  11. pitch - The float-precision pitch facing directional value of the position
  12. - *
  13. world_name - String file name of the world the position is on
  14. - *
  15. world_uuid - String uuid of the world the position is on
  16. - *
  17. server_name - String name of the server the position world is on
  18. - *
- */ - protected final String positionsTableName; - - /** - * Stores {@link SavedPosition}s, including metadata about them - *
    - *
  1. id - Primary key, auto-increment; The id representing the position meta
  2. - *
  3. position_id - References the positions table; the position location data of this saved position
  4. - *
  5. name - The name string of the position represented by this metadata
  6. - *
  7. description - A description string of the position represented by this metadata
  8. - *
  9. timestamp - A datetime timestamp representing when the position this represents was created
  10. - *
- */ - protected final String savedPositionsTableName; - - /** - * Stores {@link Home} data - *
    - *
  1. uuid - Primary key, unique; The unique id of the home
  2. - *
  3. saved_position id - References the saved position table; The id of the home saved position data
  4. - *
  5. owner_uuid - References the players table; the uuid of the person who set the home
  6. - *
  7. is_public - Boolean value; represents if the home is set to public
  8. - *
- */ - protected final String homesTableName; - - /** - * Stores {@link Warp} data - *
    - *
  1. uuid - Primary key, unique; The unique id of the warp
  2. - *
  3. saved_position id - References the saved position table; The id of the warp saved position data
  4. - *
- */ - protected final String warpsTableName; - - /** - * Stores data about current cross-server teleports being executed by {@link User}s - *
    - *
  1. player_uuid - Primary key, unique, references player table; represents the unique id of a teleporting player
  2. - *
  3. destination_id - References positions table; the destination of the teleporting player
  4. - *
- */ - protected final String teleportsTableName; - - /** - * Instance of the implementing plugin - */ protected final HuskHomes plugin; - /** * Loads SQL table creation schema statements from a resource file as a string array * @@ -124,43 +50,27 @@ public abstract class Database { */ protected final String formatStatementTables(@NotNull String sql) { return sql - .replaceAll("%positions_table%", positionsTableName) - .replaceAll("%players_table%", playerTableName) - .replaceAll("%teleports_table%", teleportsTableName) - .replaceAll("%saved_positions_table%", savedPositionsTableName) - .replaceAll("%homes_table%", homesTableName) - .replaceAll("%warps_table%", warpsTableName); + .replaceAll("%positions_table%", plugin.getSettings().getTableName(Table.POSITION_DATA)) + .replaceAll("%players_table%", plugin.getSettings().getTableName(Table.PLAYER_DATA)) + .replaceAll("%teleports_table%", plugin.getSettings().getTableName(Table.TELEPORT_DATA)) + .replaceAll("%saved_positions_table%", plugin.getSettings().getTableName(Table.SAVED_POSITION_DATA)) + .replaceAll("%homes_table%", plugin.getSettings().getTableName(Table.HOME_DATA)) + .replaceAll("%warps_table%", plugin.getSettings().getTableName(Table.WARP_DATA)); } /** * Create a database instance, pulling table names from the plugin config * - * @param implementor the implementing plugin instance + * @param plugin the implementing plugin instance */ - protected Database(@NotNull HuskHomes implementor) { - this.plugin = implementor; - this.playerTableName = implementor.getSettings().getTableName(Table.PLAYER_DATA); - this.positionsTableName = implementor.getSettings().getTableName(Table.POSITION_DATA); - this.savedPositionsTableName = implementor.getSettings().getTableName(Table.SAVED_POSITION_DATA); - this.homesTableName = implementor.getSettings().getTableName(Table.HOME_DATA); - this.warpsTableName = implementor.getSettings().getTableName(Table.WARP_DATA); - this.teleportsTableName = implementor.getSettings().getTableName(Table.TELEPORT_DATA); + protected Database(@NotNull HuskHomes plugin) { + this.plugin = plugin; } /** * Initialize the database and ensure tables are present; create tables if they do not exist. - * - * @return {@code true} if done successfully */ - public abstract boolean initialize(); - - /** - * Execute a MySQL script file read as an InputStream - * - * @param inputStream The input stream to read the script from - */ - public abstract void runScript(@NotNull InputStream inputStream, - @NotNull Map replacements); + public abstract void initialize() throws IllegalStateException; /** * (Internal use only) - Sets a position to the position table in the database diff --git a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java index dcb13473..7764c82a 100644 --- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -11,8 +11,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.sql.*; import java.util.*; import java.util.logging.Level; @@ -23,35 +21,11 @@ import java.util.logging.Level; @SuppressWarnings("DuplicatedCode") public class MySqlDatabase extends Database { - public String host; - public int port; - public String database; - public String username; - public String password; - public String connectionParameters; - - public int connectionPoolSize; - public int connectionPoolIdle; - public long connectionPoolLifetime; - public long connectionPoolKeepAlive; - public long connectionPoolTimeout; - private static final String DATA_POOL_NAME = "HuskHomesHikariPool"; private HikariDataSource dataSource; public MySqlDatabase(@NotNull HuskHomes plugin) { super(plugin); - this.host = plugin.getSettings().getMySqlHost(); - this.port = plugin.getSettings().getMySqlPort(); - this.database = plugin.getSettings().getMySqlDatabase(); - this.username = plugin.getSettings().getMySqlUsername(); - this.password = plugin.getSettings().getMySqlPassword(); - this.connectionParameters = plugin.getSettings().getMySqlConnectionParameters(); - this.connectionPoolSize = plugin.getSettings().getMySqlConnectionPoolSize(); - this.connectionPoolIdle = plugin.getSettings().getMySqlConnectionPoolIdle(); - this.connectionPoolLifetime = plugin.getSettings().getMySqlConnectionPoolLifetime(); - this.connectionPoolKeepAlive = plugin.getSettings().getMySqlConnectionPoolKeepAlive(); - this.connectionPoolTimeout = plugin.getSettings().getMySqlConnectionPoolTimeout(); } /** @@ -65,75 +39,58 @@ public class MySqlDatabase extends Database { } @Override - public boolean initialize() { - try { - // Create jdbc driver connection url - final String jdbcUrl = "jdbc:mysql://" + host + ":" + port + "/" + database + connectionParameters; - dataSource = new HikariDataSource(); - dataSource.setJdbcUrl(jdbcUrl); + public void initialize() throws IllegalStateException { + // Initialize the Hikari pooled connection + dataSource = new HikariDataSource(); + dataSource.setJdbcUrl("jdbc:mysql://" + + plugin.getSettings().getMySqlHost() + + ":" + + plugin.getSettings().getMySqlPort() + + "/" + + plugin.getSettings().getMySqlDatabase() + + plugin.getSettings().getMySqlConnectionParameters()); - // Authenticate - dataSource.setUsername(username); - dataSource.setPassword(password); + // Authenticate with the database + dataSource.setUsername(plugin.getSettings().getMySqlUsername()); + dataSource.setPassword(plugin.getSettings().getMySqlPassword()); - // Set connection pool options - dataSource.setMaximumPoolSize(connectionPoolSize); - dataSource.setMinimumIdle(connectionPoolIdle); - dataSource.setMaxLifetime(connectionPoolLifetime); - dataSource.setKeepaliveTime(connectionPoolKeepAlive); - dataSource.setConnectionTimeout(connectionPoolTimeout); - dataSource.setPoolName(DATA_POOL_NAME); + // Set connection pool options + dataSource.setMaximumPoolSize(plugin.getSettings().getMySqlConnectionPoolSize()); + dataSource.setMinimumIdle(plugin.getSettings().getMySqlConnectionPoolIdle()); + dataSource.setMaxLifetime(plugin.getSettings().getMySqlConnectionPoolLifetime()); + dataSource.setKeepaliveTime(plugin.getSettings().getMySqlConnectionPoolKeepAlive()); + dataSource.setConnectionTimeout(plugin.getSettings().getMySqlConnectionPoolTimeout()); + dataSource.setPoolName(DATA_POOL_NAME); - // Set additional connection pool properties - dataSource.setDataSourceProperties(new Properties() {{ - put("cachePrepStmts", "true"); - put("prepStmtCacheSize", "250"); - put("prepStmtCacheSqlLimit", "2048"); - put("useServerPrepStmts", "true"); - put("useLocalSessionState", "true"); - put("useLocalTransactionState", "true"); - put("rewriteBatchedStatements", "true"); - put("cacheResultSetMetadata", "true"); - put("cacheServerConfiguration", "true"); - put("elideSetAutoCommits", "true"); - put("maintainTimeStats", "false"); - }}); + // Set additional connection pool properties + dataSource.setDataSourceProperties(new Properties() {{ + put("cachePrepStmts", "true"); + put("prepStmtCacheSize", "250"); + put("prepStmtCacheSqlLimit", "2048"); + put("useServerPrepStmts", "true"); + put("useLocalSessionState", "true"); + put("useLocalTransactionState", "true"); + put("rewriteBatchedStatements", "true"); + put("cacheResultSetMetadata", "true"); + put("cacheServerConfiguration", "true"); + put("elideSetAutoCommits", "true"); + put("maintainTimeStats", "false"); + }}); - // Prepare database schema; make tables if they don't exist - try (Connection connection = dataSource.getConnection()) { - // Load database schema CREATE statements from schema file - final String[] databaseSchema = getSchemaStatements("database/mysql_schema.sql"); - try (Statement statement = connection.createStatement()) { - for (String tableCreationStatement : databaseSchema) { - statement.execute(tableCreationStatement); - } - } - return true; - } catch (SQLException | IOException e) { - plugin.log(Level.SEVERE, "An error occurred creating tables on the MySQL database: ", e); - } - } catch (Exception e) { - plugin.log(Level.SEVERE, "An unhandled exception occurred during database setup!", e); - } - return false; - } - - @Override - public void runScript(@NotNull InputStream inputStream, @NotNull Map replacements) { - try (Connection connection = getConnection()) { - final String[] scriptString; - scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)}; - replacements.forEach((key, value) -> scriptString[0] = scriptString[0].replaceAll(key, value)); - connection.setAutoCommit(false); + // Prepare database schema; make tables if they don't exist + try (Connection connection = dataSource.getConnection()) { + final String[] databaseSchema = getSchemaStatements("database/mysql_schema.sql"); try (Statement statement = connection.createStatement()) { - for (String statementString : scriptString[0].split(";")) { - statement.addBatch(statementString); + for (String tableCreationStatement : databaseSchema) { + statement.execute(tableCreationStatement); } - statement.executeBatch(); + } catch (SQLException e) { + throw new IllegalStateException("Failed to create database tables. Please ensure you are running MySQL v8.0+ " + + "and that your connecting user account has privileges to create tables.", e); } - } catch (IOException | SQLException e) { - plugin.log(Level.SEVERE, "An error occurred running a script on the MySQL database: ", e); - throw new RuntimeException(e); + } catch (SQLException | IOException e) { + throw new IllegalStateException("Failed to establish a connection to the MySQL database. " + + "Please check the supplied database credentials in the config file", e); } } diff --git a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java index 98c5afd4..358090b4 100644 --- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -12,8 +12,6 @@ import org.sqlite.SQLiteConfig; import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.sql.*; import java.util.*; import java.util.logging.Level; @@ -82,50 +80,21 @@ public class SqLiteDatabase extends Database { } @Override - public boolean initialize() { + public void initialize() throws IllegalStateException { + // Set up the connection + setConnection(); + + // Prepare database schema; make tables if they don't exist try { - // Set up the connection - setConnection(); - - // Prepare database schema; make tables if they don't exist - try { - // Load database schema CREATE statements from schema file - final String[] databaseSchema = getSchemaStatements("database/sqlite_schema.sql"); - try (Statement statement = getConnection().createStatement()) { - for (String tableCreationStatement : databaseSchema) { - statement.execute(tableCreationStatement); - } - } - return true; - } catch (SQLException | IOException e) { - plugin.log(Level.SEVERE, "An error occurred creating tables on the SQLite database: ", e); - } - } catch (Exception e) { - plugin.log(Level.SEVERE, "An unhandled exception occurred during database setup!", e); - } - return false; - } - - @Override - public void runScript(@NotNull InputStream inputStream, @NotNull Map replacements) { - try { - final String[] scriptString; - scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)}; - replacements.forEach((key, value) -> scriptString[0] = scriptString[0].replaceAll(key, value)); - final boolean autoCommit = getConnection().getAutoCommit(); - - // Execute batched SQLite script - getConnection().setAutoCommit(false); + // Load database schema CREATE statements from schema file + final String[] databaseSchema = getSchemaStatements("database/sqlite_schema.sql"); try (Statement statement = getConnection().createStatement()) { - for (String statementString : scriptString[0].split(";")) { - statement.addBatch(statementString); + for (String tableCreationStatement : databaseSchema) { + statement.execute(tableCreationStatement); } - statement.executeBatch(); } - getConnection().setAutoCommit(autoCommit); - } catch (IOException | SQLException e) { - plugin.log(Level.SEVERE, "An exception occurred running script on the SQLite database", e); - throw new RuntimeException(e); + } catch (SQLException | IOException e) { + throw new IllegalStateException("Failed to initialize the SQLite database", e); } } diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java index 4bdb6256..fe9cc26a 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java @@ -5,7 +5,6 @@ import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.network.Broker; import net.william278.huskhomes.network.Message; import net.william278.huskhomes.network.Payload; -import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.user.OnlineUser; @@ -58,6 +57,9 @@ public class EventListener { }, plugin.getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE ? 40L : 0L); } + // Cache this user's homes + plugin.getManager().homes().cacheUserHomes(onlineUser); + // Set their ignoring requests state plugin.getDatabase().getUserData(onlineUser.getUuid()).ifPresent(userData -> { final boolean ignoringRequests = userData.isIgnoringTeleports(); @@ -70,12 +72,6 @@ public class EventListener { .orElse("")).ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale))); } }); - - // Cache this user's homes - plugin.getCache().getHomes().put(onlineUser.getUsername(), plugin.getDatabase() - .getHomes(onlineUser).stream() - .map(Home::getName) - .toList()); }); } @@ -115,12 +111,12 @@ public class EventListener { * @param onlineUser the leaving {@link OnlineUser} */ protected final void handlePlayerLeave(@NotNull OnlineUser onlineUser) { - // Remove this user's home cache - plugin.getCache().getHomes().remove(onlineUser.getUsername()); - // Set offline position plugin.getDatabase().setOfflinePosition(onlineUser, onlineUser.getPosition()); + // Remove this user's home cache + plugin.getManager().homes().removeUserHomes(onlineUser); + // Update global lists if (plugin.getSettings().isCrossServer()) { plugin.getOnlineUsers().stream() diff --git a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java index a36c4279..23ffe796 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java @@ -11,13 +11,48 @@ import net.william278.huskhomes.user.User; import net.william278.huskhomes.util.ValidationException; import org.jetbrains.annotations.NotNull; -import java.util.Optional; +import java.util.*; public class HomesManager { + private final HuskHomes plugin; + private final List publicHomes; + private final Map> userHomes; protected HomesManager(@NotNull HuskHomes plugin) { this.plugin = plugin; + this.publicHomes = plugin.getDatabase().getPublicHomes(); + this.userHomes = new HashMap<>(); + plugin.runAsync(() -> plugin.getOnlineUsers() + .forEach(this::cacheUserHomes)); + } + + /** + * Cached user homes - maps a username to a list of their homes + */ + @NotNull + public Map> getUserHomes() { + return userHomes.entrySet().stream() + .collect(HashMap::new, (m, e) -> m.put(e.getKey(), e.getValue().stream().map(Home::getName).toList()), + HashMap::putAll); + } + + public void cacheUserHomes(@NotNull User user) { + userHomes.put(user.getUuid().toString(), plugin.getDatabase().getHomes(user)); + } + + public void removeUserHomes(@NotNull User user) { + userHomes.remove(user.getUuid().toString()); + } + + /** + * Cached public homes - maps a username to a list of their public homes + */ + @NotNull + public Map> getPublicHomes() { + return publicHomes.stream() + .collect(HashMap::new, (m, e) -> m.put(e.getOwner().getUsername(), List.of(e.getName())), + HashMap::putAll); } public void createHome(@NotNull User owner, @NotNull String name, @NotNull Position position, diff --git a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java index ac2d02ad..b935ed2b 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java @@ -18,21 +18,15 @@ import java.util.*; */ public class RequestsManager { - @NotNull private final HuskHomes plugin; - /** - * Map of user UUIDs to a queue of received teleport requests - */ + // Map of user UUIDs to a queue of received teleport requests private final Map> requests; - - /** - * Set of users who are ignoring tpa requests - */ + // Set of users who are ignoring tpa requests private final Set ignoringRequests; - public RequestsManager(@NotNull HuskHomes implementation) { - this.plugin = implementation; + public RequestsManager(@NotNull HuskHomes plugin) { + this.plugin = plugin; this.requests = new HashMap<>(); this.ignoringRequests = new HashSet<>(); } @@ -173,8 +167,6 @@ public class RequestsManager { * * @param request The {@link TeleportRequest} to send * @param recipient The online recipient of the request - * @return the {@link TeleportRequest} that was sent if it could be sent, otherwise an empty optional if it was not - * sent because the recipient is ignoring requests or is vanished ({@link OnlineUser#isVanished()}) */ public void sendLocalTeleportRequest(@NotNull TeleportRequest request, @NotNull OnlineUser recipient) { request.setRecipientName(recipient.getUsername()); @@ -196,7 +188,7 @@ public class RequestsManager { // Add the request and display a message to the recipient addTeleportRequest(request, recipient); plugin.getLocales().getLocale((request.getType() == TeleportRequest.Type.TPA ? "tpa" : "tpahere") - + "_request_received", request.getRequesterName()) + + "_request_received", request.getRequesterName()) .ifPresent(recipient::sendMessage); plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName()) .ifPresent(recipient::sendMessage); diff --git a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java index 5da08b35..884ad9b2 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java @@ -7,13 +7,24 @@ import net.william278.huskhomes.position.Warp; import net.william278.huskhomes.util.ValidationException; import org.jetbrains.annotations.NotNull; +import java.util.List; import java.util.Optional; public class WarpsManager { private final HuskHomes plugin; + private final List warps; protected WarpsManager(@NotNull HuskHomes plugin) { this.plugin = plugin; + this.warps = plugin.getDatabase().getWarps(); + } + + /** + * Cached warp names + */ + @NotNull + public List getWarps() { + return warps.stream().map(Warp::getName).toList(); } public void createWarp(@NotNull String name, @NotNull Position position, boolean overwrite) throws ValidationException { diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java index 203ba486..b07f87b2 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TimedTeleport.java @@ -38,7 +38,7 @@ public class TimedTeleport extends Teleport { } // Check if the teleporter is already warming up to teleport - if (plugin.getCache().getCurrentlyOnWarmup().contains(teleporter.getUuid())) { + if (plugin.isWarmingUp(teleporter.getUuid())) { throw new TeleportationException(TeleportationException.Type.ALREADY_WARMING_UP); } @@ -57,7 +57,7 @@ public class TimedTeleport extends Teleport { // Execute the warmup, fire the event, then execute the teleport if warmup completes normally private void process() { plugin.fireEvent(plugin.getTeleportWarmupEvent(this, timeLeft), (event) -> { - plugin.getCache().getCurrentlyOnWarmup().add(teleporter.getUuid()); + plugin.getCurrentlyOnWarmup().add(teleporter.getUuid()); plugin.getLocales().getLocale("teleporting_warmup_start", Integer.toString(timeLeft)) .ifPresent(teleporter::sendMessage); @@ -78,7 +78,7 @@ public class TimedTeleport extends Teleport { // Tick (decrement) the timed teleport timer and end it if done if (tickAndGetIfDone()) { - plugin.getCache().getCurrentlyOnWarmup().remove(teleporter.getUuid()); + plugin.getCurrentlyOnWarmup().remove(teleporter.getUuid()); plugin.cancelTask(warmupTaskId.get()); } });