More bukkit adapter stuff, load SQL schema from file, start work on MySQL implementation, start event processing

This commit is contained in:
William committed 2022-05-22 03:03:23 +01:00
1 parent 8e7d5e74a0
commit bd52c99d4d
18 files changed
+973 -101

No files matched your search

@@ -38,7 +38,8 @@ public class Messages {
/**
* Returns an unformatted message loaded from the messages file, with replacements applied
*
* @param messageId String identifier of the message, corresponding to a key in the file
* @param messageId String identifier of the message, corresponding to a key in the file
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} containing the replacement-applied message corresponding to the id, if it exists
*/
public Optional<String> getRawMessage(String messageId, String... replacements) {
@@ -58,7 +59,8 @@ public class Messages {
/**
* Returns a MineDown-formatted message from the messages file, with replacements applied
*
* @param messageId String identifier of the message, corresponding to a key in the file
* @param messageId String identifier of the message, corresponding to a key in the file
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} containing the replacement-applied, formatted message corresponding to the id, if it exists
*/
public Optional<MineDown> getMessage(String messageId, String... replacements) {
@@ -69,7 +71,7 @@ public class Messages {
* Apply placeholder replacements to a raw message
*
* @param rawMessage The raw, unparsed message
* @param replacements Ordered list of placeholder replacement Strings
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return the raw message, with inserted placeholders
*/
private String applyReplacements(String rawMessage, String... replacements) {
@@ -2,25 +2,35 @@ package net.william278.huskhomes.data;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.ResourceReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* An abstract representation of the plugin database, storing home, warp & player data.
* An abstract representation of the plugin database, storing home, warp and player data.
* <p>
* Implemented by different database platforms - MySQL, SQLite, etc. - as configured by the administrator.
*/
public abstract class Database {
/**
* Stores data about {@link Player}s
* Stores data about {@link User}s
* <ol>
* <li>uuid - Primary key, unique; the user's minecraft account unique ID</li>
* <li>username - The user's username. Checked to be updated on login</li>
@@ -84,7 +94,7 @@ public abstract class Database {
protected final String warpsTableName;
/**
* Stores data about current cross-server teleports being executed by {@link Player}s
* Stores data about current cross-server teleports being executed by {@link User}s
* <ol>
* <li>player_uuid - Primary key, unique, references player table; represents the unique id of a teleporting player</li>
* <li>destination_id - References positions table; the destination of the teleporting player</li>
@@ -92,12 +102,58 @@ public abstract class Database {
*/
protected final String teleportsTableName;
/**
* Logger instance used for database error logging
*/
private final Logger logger;
/**
* Returns the {@link Logger} used to log database errors
*
* @return the {@link Logger} instance
*/
protected Logger getLogger() {
return logger;
}
private final ResourceReader resourceReader;
/**
* Loads SQL table creation schema statements from a resource file as a string array
*
* @param schemaFileName database script resource file to load from
* @return Array of string-formatted table creation schema statements
* @throws IOException if the resource could not be read
*/
protected final String[] getSchemaStatements(@NotNull String schemaFileName) throws IOException {
return formatStatementTables(
new String(resourceReader.getResource(schemaFileName)
.readAllBytes(), StandardCharsets.UTF_8))
.split(";");
}
/**
* Format all table name placeholder strings in a SQL statement
*
* @param sql the SQL statement with unformatted table name placeholders
* @return the formatted statement, with table placeholders replaced with the correct names
*/
protected final String formatStatementTables(@NotNull String sql) {
return sql
.replaceAll("%positions_table%", positionsTableName)
.replaceAll("%players_table%", playerTableName)
.replaceAll("%teleports_table%", teleportsTableName)
.replaceAll("%position_metadata_table%", positionMetadataTableName)
.replaceAll("%homes_table%", homesTableName)
.replaceAll("%warps_table%", warpsTableName);
}
/**
* Create a database instance with specified table data {@link Settings}
*
* @param settings {@link Settings} to fetch database configuration data from
*/
protected Database(@NotNull Settings settings) {
protected Database(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) {
this.playerTableName = settings.
getStringValue(Settings.ConfigOption.DATABASE_PLAYER_TABLE_NAME);
this.positionsTableName = settings.
@@ -110,6 +166,8 @@ public abstract class Database {
getStringValue(Settings.ConfigOption.DATABASE_WARPS_TABLE_NAME);
this.teleportsTableName = settings.
getStringValue(Settings.ConfigOption.DATABASE_TELEPORTS_TABLE_NAME);
this.logger = logger;
this.resourceReader = resourceReader;
}
/**
@@ -123,20 +181,20 @@ public abstract class Database {
* <b>(Internal use only)</b> - Sets a position to the position table in the database
*
* @param position The {@link Position} to set
* @return A future returning the inserted row ID when the operation has completed.
* @return The newly inserted row ID
*/
protected abstract CompletableFuture<Integer> setPosition(@NotNull Position position);
protected abstract int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException;
/**
* <b>(Internal use only)</b> - Sets position meta to the position metadata table in the database
*
* @param meta The {@link PositionMeta} to set
* @return A future returning the inserted row ID when the operation has completed.
* @return The newly inserted row ID
*/
protected abstract CompletableFuture<Integer> setPositionMeta(@NotNull PositionMeta meta);
protected abstract int setPositionMeta(@NotNull PositionMeta meta, @NotNull Connection connection) throws SQLException;
/**
* Ensure a {@link Player} has an entry in the database and that their username is up-to-date
* Ensure a {@link Player} has a {@link User} entry in the database and that their username is up-to-date
*
* @param player The {@link Player} to ensure
* @return A future returning void when complete
@@ -146,18 +204,27 @@ public abstract class Database {
/**
* Get a player by their username (<i>case-insensitive</i>)
*
* @param name Username of the {@link Player} to get (<i>case-insensitive</i>)
* @return A future returning an optional with the {@link Player} present if they exist
* @param name Username of the {@link User} to get (<i>case-insensitive</i>)
* @return A future returning an optional with the {@link User} present if they exist
*/
public abstract CompletableFuture<Optional<Player>> getPlayerByName(@NotNull String name);
public abstract CompletableFuture<Optional<User>> getUserByName(@NotNull String name);
/**
* Get a list of {@link Home}s set by a {@link Player}
* Get a player by their Minecraft account {@link UUID}
*
* @param player {@link Player} to get the homes of
* @param uuid Minecraft account {@link UUID} of the {@link User} to get
* @return A future returning an optional with the {@link User} present if they exist
*/
public abstract CompletableFuture<Optional<User>> getUser(@NotNull UUID uuid);
/**
* Get a list of {@link Home}s set by a {@link User}
*
* @param player {@link User} to get the homes of
* @return A future returning void when complete
*/
public abstract CompletableFuture<List<Home>> getHomes(@NotNull Player player);
public abstract CompletableFuture<List<Home>> getHomes(@NotNull User player);
/**
* Get a list of all {@link Warp}s that have been set
@@ -174,13 +241,13 @@ public abstract class Database {
public abstract CompletableFuture<List<Home>> getPublicHomes();
/**
* Get a {@link Home} set by a {@link Player}
* Get a {@link Home} set by a {@link User}
*
* @param player The {@link Player} who set the home
* @param player The {@link User} who set the home
* @param homeName The <i>case-insensitive</i> name of the home to get
* @return A future returning an optional with the {@link Home} present if it exists
*/
public abstract CompletableFuture<Optional<Home>> getHome(@NotNull Player player, @NotNull String homeName);
public abstract CompletableFuture<Optional<Home>> getHome(@NotNull User player, @NotNull String homeName);
/**
* Get a {@link Home} by its unique id
@@ -207,74 +274,74 @@ public abstract class Database {
public abstract CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID uuid);
/**
* Get the current {@link Teleport} being executed by the specified {@link Player}
* Get the current {@link Teleport} being executed by the specified {@link User}
*
* @param player The {@link Player} to check
* @param player The {@link User} to check
* @return A future returning an optional with the {@link Teleport} present if they are teleporting cross-server
*/
public abstract CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull Player player);
public abstract CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull User player);
/**
* Sets or clears the current {@link Teleport} being executed by a {@link Player}
* Sets or clears the current {@link Teleport} being executed by a {@link User}
*
* @param player The {@link Player} to set the current teleport of.
* @param player The {@link User} to set the current teleport of.
* Pass as {@code null} to clear the player's current teleport.<p>
* @param teleport The {@link Teleport} to set as their current cross-server teleport
* @return A future returning void when complete
*/
public abstract CompletableFuture<Void> setCurrentTeleport(@NotNull Player player, @Nullable Teleport teleport);
public abstract CompletableFuture<Void> setCurrentTeleport(@NotNull User player, @Nullable Teleport teleport);
/**
* Get the last teleport {@link Position} of a specified {@link Player}
* Get the last teleport {@link Position} of a specified {@link User}
*
* @param player The {@link Player} to check
* @param player The {@link User} to check
* @return A future returning an optional with the {@link Position} present if it has been set
*/
public abstract CompletableFuture<Optional<Position>> getLastPosition(@NotNull Player player);
public abstract CompletableFuture<Optional<Position>> getLastPosition(@NotNull User player);
/**
* Sets the last teleport {@link Position} of a {@link Player}
* Sets the last teleport {@link Position} of a {@link User}
*
* @param player The {@link Player} to set the last position of
* @param player The {@link User} to set the last position of
* @param position The {@link Position} to set as their last position
* @return A future returning void when complete
*/
public abstract CompletableFuture<Void> setLastPosition(@NotNull Player player, @NotNull Position position);
public abstract CompletableFuture<Void> setLastPosition(@NotNull User player, @NotNull Position position);
/**
* Get the offline {@link Position} of a specified {@link Player}
* Get the offline {@link Position} of a specified {@link User}
*
* @param player The {@link Player} to check
* @param player The {@link User} to check
* @return A future returning an optional with the {@link Position} present if it has been set
*/
public abstract CompletableFuture<Optional<Position>> getOfflinePosition(@NotNull Player player);
public abstract CompletableFuture<Optional<Position>> getOfflinePosition(@NotNull User player);
/**
* Sets the offline {@link Position} of a {@link Player}
* Sets the offline {@link Position} of a {@link User}
*
* @param player The {@link Player} to set the offline position of
* @param player The {@link User} to set the offline position of
* @param position The {@link Position} to set as their offline position
* @return A future returning void when complete
*/
public abstract CompletableFuture<Void> setOfflinePosition(@NotNull Player player, @NotNull Position position);
public abstract CompletableFuture<Void> setOfflinePosition(@NotNull User player, @NotNull Position position);
/**
* Get the respawn {@link Position} of a specified {@link Player}
* Get the respawn {@link Position} of a specified {@link User}
*
* @param player The {@link Player} to check
* @param player The {@link User} to check
* @return A future returning an optional with the {@link Position} present if it has been set
*/
public abstract CompletableFuture<Optional<Position>> getRespawnPosition(@NotNull Player player);
public abstract CompletableFuture<Optional<Position>> getRespawnPosition(@NotNull User player);
/**
* Sets or clears the respawn {@link Position} of a {@link Player}
* Sets or clears the respawn {@link Position} of a {@link User}
*
* @param player The {@link Player} to set the respawn position of
* @param player The {@link User} to set the respawn position of
* @param position The {@link Position} to set as their respawn position
* Pass as {@code null} to clear the player's current respawn position.<p>
* @return A future returning void when complete
*/
public abstract CompletableFuture<Void> setRespawnPosition(@NotNull Player player, @Nullable Position position);
public abstract CompletableFuture<Void> setRespawnPosition(@NotNull User player, @Nullable Position position);
/**
* Sets or updates a {@link Home} into the home data table on the database.
@@ -308,4 +375,55 @@ public abstract class Database {
*/
public abstract CompletableFuture<Void> deleteWarp(@NotNull Warp uuid);
/**
* Get the rtp cooldown time of a specified {@link User}
*
* @param player The {@link User} to check
* @return A future returning the epoch time of their current cooldown
*/
public abstract CompletableFuture<Long> getRtpCooldown(@NotNull User player);
/**
* Sets the rtp cooldown time of a {@link User}
*
* @param player The {@link User} to update
* @param position The epoch time of when the user can use rtp again.
* @return A future returning void when complete
*/
public abstract CompletableFuture<Void> setRtpCooldown(@NotNull User player, long position);
/**
* Get the number of home slots a {@link User} has consumed (bought)
*
* @param player The {@link User} to check
* @return A future returning the number of home slots
*/
public abstract CompletableFuture<Integer> getHomeSlots(@NotNull User player);
/**
* Sets the number of home slots a {@link User} has consumed (bought)
*
* @param player The {@link User} to update
* @param homeSlots The number of home slots to set the user as having consumed.
* @return A future returning void when complete
*/
public abstract CompletableFuture<Void> setHomeSlots(@NotNull User player, int homeSlots);
/**
* Get if a {@link User} is ignoring tp requests
*
* @param player The {@link User} to check
* @return A future returning if the player is ignoring tp requests
*/
public abstract CompletableFuture<Boolean> getIsIgnoringTeleports(@NotNull User player);
/**
* Sets if a {@link User} is ignoring tp requests
*
* @param player The {@link User} to update
* @param ignoringTeleports If the player is ignoring tp requests
* @return A future returning void when complete
*/
public abstract CompletableFuture<Void> setIgnoringTeleports(@NotNull User player, boolean ignoringTeleports);
}
@@ -1,124 +1,556 @@
package net.william278.huskhomes.data;
import com.zaxxer.hikari.HikariDataSource;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.*;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.util.Logger;
import net.william278.huskhomes.util.ResourceReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.sql.*;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
//todo write (hikari for this; direct driver for SQLite probably)
/**
* A MySQL implementation of the plugin {@link Database}
*/
@SuppressWarnings("DuplicatedCode")
public class MySqlDatabase extends Database {
public MySqlDatabase(@NotNull Settings settings) {
super(settings);
/**
* 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;
private final int hikariMaximumPoolSize;
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 HikariDataSource dataSource;
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);
}
/**
* Fetch the auto-closeable connection from the hikariDataSource
*
* @return The {@link Connection} to the MySQL database
* @throws SQLException if the connection fails for some reason
*/
private Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
@Override
public CompletableFuture<Void> initialize() {
return null;
return CompletableFuture.runAsync(() -> {
// Create jdbc driver connection url
final String jdbcUrl = "jdbc:mysql://" + mySqlHost + ":" + mySqlPort + "/" + mySqlDatabaseName + mySqlConnectionParameters;
dataSource = new HikariDataSource();
dataSource.setJdbcUrl(jdbcUrl);
// Authenticate
dataSource.setUsername(mySqlUsername);
dataSource.setPassword(mySqlPassword);
// Set various additional parameters
dataSource.setMaximumPoolSize(hikariMaximumPoolSize);
dataSource.setMinimumIdle(hikariMinimumIdle);
dataSource.setMaxLifetime(hikariMaximumLifetime);
dataSource.setKeepaliveTime(hikariKeepAliveTime);
dataSource.setConnectionTimeout(hikariConnectionTimeOut);
dataSource.setPoolName(DATA_POOL_NAME);
// 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);
}
}
} catch (SQLException | IOException e) {
getLogger().log(Level.SEVERE, "An error occurred creating tables on the MySQL database: ", e);
}
});
}
@Override
protected CompletableFuture<Integer> setPosition(@NotNull Position position) {
return null;
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%positions_table%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES (?,?,?,?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) {
statement.setDouble(1, position.x);
statement.setDouble(2, position.y);
statement.setDouble(3, position.z);
statement.setFloat(4, position.yaw);
statement.setFloat(5, position.pitch);
statement.setString(6, position.world.name);
statement.setString(7, position.world.uuid.toString());
statement.setString(8, position.server.name);
statement.executeUpdate();
return statement.getGeneratedKeys().getInt(1);
}
}
@Override
protected CompletableFuture<Integer> setPositionMeta(@NotNull PositionMeta meta) {
return null;
protected int setPositionMeta(@NotNull PositionMeta meta, @NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%position_metadata_table%` (`name`, `description`, `timestamp`)
VALUES (?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, meta.name);
statement.setString(2, meta.description);
statement.setTimestamp(3, new Timestamp(Instant.ofEpochSecond(meta.timestamp).toEpochMilli()));
statement.executeUpdate();
return statement.getGeneratedKeys().getInt(1);
}
}
@Override
public CompletableFuture<Void> ensurePlayer(@NotNull Player player) {
return null;
return CompletableFuture.runAsync(() -> getUser(player.getUuid()).thenAccept(optionalUser ->
optionalUser.ifPresentOrElse(existingUser -> {
if (!existingUser.username().equals(player.getName())) {
// Update a player's name if it has changed in the database
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
UPDATE `%players_table%`
SET `username`=?
WHERE `uuid`=?"""))) {
statement.setString(1, player.getName());
statement.setString(2, existingUser.uuid().toString());
statement.executeUpdate();
}
getLogger().log(Level.INFO, "Updated " + player.getName() + "'s name in the database (" + existingUser.username() + " -> " + player.getName() + ")");
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
}
},
() -> {
// Insert new player data into the database
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%players_table%` (`uuid`,`username`)
VALUES (?,?);"""))) {
statement.setString(1, player.getUuid().toString());
statement.setString(2, player.getName());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e);
}
})));
}
@Override
public CompletableFuture<Optional<Player>> getPlayerByName(@NotNull String name) {
return null;
public CompletableFuture<Optional<User>> getUserByName(@NotNull String name) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`
FROM `%players_table%`
WHERE `username`=?"""))) {
statement.setString(1, name);
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<List<Home>> getHomes(@NotNull Player player) {
return null;
public CompletableFuture<Optional<User>> getUser(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `uuid`, `username`
FROM `%players_table%`
WHERE `uuid`=?"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new User(UUID.fromString(resultSet.getString("uuid")),
resultSet.getString("username")));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<List<Home>> getHomes(@NotNull User user) {
return CompletableFuture.supplyAsync(() -> {
final List<Home> userHomes = new ArrayList<>();
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id`
WHERE `owner_uuid`=?
ORDER BY `name`;"""))) {
statement.setString(1, user.uuid().toString());
final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
userHomes.add(new Home(resultSet.getDouble("x"),
resultSet.getDouble("y"),
resultSet.getDouble("z"),
resultSet.getFloat("yaw"),
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")),
new PositionMeta(resultSet.getString("name"),
resultSet.getString("description"),
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
UUID.fromString(resultSet.getString("home_uuid")),
user,
resultSet.getBoolean("public")));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the database for home data for:" + user.username());
}
return userHomes;
});
}
@Override
public CompletableFuture<List<Warp>> getWarps() {
return null;
return CompletableFuture.supplyAsync(() -> {
final List<Warp> warps = new ArrayList<>();
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%positions_table%` ON `%warps_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%position_metadata_table%` ON `%warps_table%`.`metadata_id`=`%position_metadata_table%`.`id`
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
warps.add(new Warp(resultSet.getDouble("x"),
resultSet.getDouble("y"),
resultSet.getDouble("z"),
resultSet.getFloat("yaw"),
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")),
new PositionMeta(resultSet.getString("name"),
resultSet.getString("description"),
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
UUID.fromString(resultSet.getString("warp_uuid"))));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the database for warp data.");
}
return warps;
});
}
@Override
public CompletableFuture<List<Home>> getPublicHomes() {
return null;
return CompletableFuture.supplyAsync(() -> {
final List<Home> userHomes = new ArrayList<>();
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id`
WHERE `public`=true
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
userHomes.add(new Home(resultSet.getDouble("x"),
resultSet.getDouble("y"),
resultSet.getDouble("z"),
resultSet.getFloat("yaw"),
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")),
new PositionMeta(resultSet.getString("name"),
resultSet.getString("description"),
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
UUID.fromString(resultSet.getString("home_uuid")),
new User(UUID.fromString(resultSet.getString("owner_uuid")),
resultSet.getString("owner_username")),
resultSet.getBoolean("public")));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query the database for public home data");
}
return userHomes;
});
}
@Override
public CompletableFuture<Optional<Home>> getHome(@NotNull Player player, @NotNull String homeName) {
return null;
public CompletableFuture<Optional<Home>> getHome(@NotNull User user, @NotNull String homeName) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id`
WHERE `owner_uuid`=?
AND `name`=?;"""))) {
statement.setString(1, user.uuid().toString());
statement.setString(2, homeName);
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new Home(resultSet.getDouble("x"),
resultSet.getDouble("y"),
resultSet.getDouble("z"),
resultSet.getFloat("yaw"),
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")),
new PositionMeta(resultSet.getString("name"),
resultSet.getString("description"),
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
UUID.fromString(resultSet.getString("home_uuid")),
new User(UUID.fromString(resultSet.getString("owner_uuid")),
resultSet.getString("owner_username")),
resultSet.getBoolean("public")));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query a player's home", e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<Optional<Home>> getHome(@NotNull UUID uuid) {
return null;
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%positions_table%` ON `%homes_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%position_metadata_table%` ON `%homes_table%`.`metadata_id`=`%position_metadata_table%`.`id`
WHERE `%homes_table%`.`uuid`=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new Home(resultSet.getDouble("x"),
resultSet.getDouble("y"),
resultSet.getDouble("z"),
resultSet.getFloat("yaw"),
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")),
new PositionMeta(resultSet.getString("name"),
resultSet.getString("description"),
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
UUID.fromString(resultSet.getString("home_uuid")),
new User(UUID.fromString(resultSet.getString("owner_uuid")),
resultSet.getString("owner_username")),
resultSet.getBoolean("public")));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query a player's home by UUID", e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<Optional<Warp>> getWarp(@NotNull String warpName) {
return null;
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%positions_table%` ON `%warps_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%position_metadata_table%` ON `%warps_table%`.`metadata_id`=`%position_metadata_table%`.`id`
WHERE `name`=?;"""))) {
statement.setString(1, warpName);
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new Warp(resultSet.getDouble("x"),
resultSet.getDouble("y"),
resultSet.getDouble("z"),
resultSet.getFloat("yaw"),
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")),
new PositionMeta(resultSet.getString("name"),
resultSet.getString("description"),
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
UUID.fromString(resultSet.getString("warp_uuid"))));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query a server warp", e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%positions_table%` ON `%warps_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%position_metadata_table%` ON `%warps_table%`.`metadata_id`=`%position_metadata_table%`.`id`
WHERE `%warps_table%`.uuid=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return Optional.of(new Warp(resultSet.getDouble("x"),
resultSet.getDouble("y"),
resultSet.getDouble("z"),
resultSet.getFloat("yaw"),
resultSet.getFloat("pitch"),
new World(resultSet.getString("world_name"),
UUID.fromString(resultSet.getString("world_uuid"))),
new Server(resultSet.getString("server_name")),
new PositionMeta(resultSet.getString("name"),
resultSet.getString("description"),
resultSet.getTimestamp("timestamp").toInstant().getEpochSecond()),
UUID.fromString(resultSet.getString("warp_uuid"))));
}
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Failed to query a server warp", e);
}
return Optional.empty();
});
}
@Override
public CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull User player) {
return null;
}
@Override
public CompletableFuture<Optional<Teleport>> getCurrentTeleport(@NotNull Player player) {
public CompletableFuture<Void> setCurrentTeleport(@NotNull User player, @Nullable Teleport teleport) {
return null;
}
@Override
public CompletableFuture<Void> setCurrentTeleport(@NotNull Player player, @Nullable Teleport teleport) {
public CompletableFuture<Optional<Position>> getLastPosition(@NotNull User player) {
return null;
}
@Override
public CompletableFuture<Optional<Position>> getLastPosition(@NotNull Player player) {
public CompletableFuture<Void> setLastPosition(@NotNull User player, @NotNull Position position) {
return null;
}
@Override
public CompletableFuture<Void> setLastPosition(@NotNull Player player, @NotNull Position position) {
public CompletableFuture<Optional<Position>> getOfflinePosition(@NotNull User player) {
return null;
}
@Override
public CompletableFuture<Optional<Position>> getOfflinePosition(@NotNull Player player) {
public CompletableFuture<Void> setOfflinePosition(@NotNull User player, @NotNull Position position) {
return null;
}
@Override
public CompletableFuture<Void> setOfflinePosition(@NotNull Player player, @NotNull Position position) {
public CompletableFuture<Optional<Position>> getRespawnPosition(@NotNull User player) {
return null;
}
@Override
public CompletableFuture<Optional<Position>> getRespawnPosition(@NotNull Player player) {
return null;
}
@Override
public CompletableFuture<Void> setRespawnPosition(@NotNull Player player, @Nullable Position position) {
public CompletableFuture<Void> setRespawnPosition(@NotNull User player, @Nullable Position position) {
return null;
}
@@ -141,4 +573,35 @@ public class MySqlDatabase extends Database {
public CompletableFuture<Void> deleteWarp(@NotNull Warp uuid) {
return null;
}
}
@Override
public CompletableFuture<Long> getRtpCooldown(@NotNull User player) {
return null;
}
@Override
public CompletableFuture<Void> setRtpCooldown(@NotNull User player, long position) {
return null;
}
@Override
public CompletableFuture<Integer> getHomeSlots(@NotNull User player) {
return null;
}
@Override
public CompletableFuture<Void> setHomeSlots(@NotNull User player, int homeSlots) {
return null;
}
@Override
public CompletableFuture<Boolean> getIsIgnoringTeleports(@NotNull User player) {
return null;
}
@Override
public CompletableFuture<Void> setIgnoringTeleports(@NotNull User player, boolean ignoringTeleports) {
return null;
}
}
@@ -0,0 +1,45 @@
package net.william278.huskhomes.listener;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.User;
import org.jetbrains.annotations.NotNull;
/**
* A handler for when events take place
*/
public class EventProcessor {
@NotNull
private final HuskHomes implementor;
public EventProcessor(@NotNull HuskHomes implementor) {
this.implementor = implementor;
}
/**
* Handle when a {@link Player} joins the server
*
* @param player the joining {@link Player}
*/
public void onPlayerJoin(@NotNull Player player) {
// Ensure the player is present on the database first
implementor.getDatabase().ensurePlayer(player).thenRun(() -> {
// If the server is in proxy mode, check if the player is teleporting cross-server
if (implementor.getSettings().getBooleanValue(Settings.ConfigOption.ENABLE_PROXY_MODE)) {
implementor.getDatabase().getCurrentTeleport(new User(player.getUuid(), player.getName()))
.thenAccept(teleport -> teleport.ifPresent(currentTeleport ->
player.teleport(currentTeleport.target).thenAccept(teleportResult -> {
if (!teleportResult.successful) {
//todo error handling if the teleport was not successful on arrival
return;
} else {
//todo display teleport complete ^-^
}
})));
}
});
}
}
@@ -0,0 +1,16 @@
package net.william278.huskhomes.player;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Represents persistently stored {@link User} data about a {@link Player}; uuid and username
* A {@link Player} may be retrieved from a user by the platform implementing classes
*
* @param uuid
* @param username {@see {@link Player}} - an online player representation
*/
public record User(@NotNull UUID uuid, @NotNull String username) {
}
@@ -1,20 +1,21 @@
package net.william278.huskhomes.position;
import net.william278.huskhomes.player.Player;
import net.william278.huskhomes.player.User;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Represents a home set by a {@link Player}
* Represents a home set by a {@link User}
*/
public class Home extends SavedPosition {
/**
* The {@link Player} who owns this home
* The {@link User} who owns this home
*/
@NotNull
public final Player owner;
public final User owner;
/**
* {@code true} if this home is public
@@ -24,13 +25,13 @@ public class Home extends SavedPosition {
public Home(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull Server server,
@NotNull PositionMeta positionMeta, @NotNull UUID uuid,
@NotNull Player owner, boolean isPublic) {
@NotNull User owner, boolean isPublic) {
super(x, y, z, yaw, pitch, world, server, positionMeta, uuid);
this.owner = owner;
this.isPublic = isPublic;
}
public Home(Position position, PositionMeta meta, @NotNull Player owner) {
public Home(Position position, PositionMeta meta, @NotNull User owner) {
super(position, meta);
this.owner = owner;
this.isPublic = false;
@@ -2,6 +2,9 @@ package net.william278.huskhomes.position;
import org.jetbrains.annotations.NotNull;
/**
* Represents a local position on this server
*/
public class Location {
/**
@@ -2,8 +2,6 @@ package net.william278.huskhomes.position;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Represents a position - a location somewhere on the proxy network or server
*/
@@ -8,20 +8,20 @@ import org.jetbrains.annotations.NotNull;
public class Server {
/**
* Proxy-defined identifier of this server
* Proxy-defined name of this server
*/
@NotNull
public String id;
public String name;
public Server(@NotNull String id) {
this.id = id;
public Server(@NotNull String name) {
this.name = name;
}
@Override
public boolean equals(Object other) {
if (other instanceof Server server) {
// If the id of this server matches another, the servers are the same.
return server.id.equalsIgnoreCase(this.id);
// If the name of this server matches another, the servers are the same.
return server.name.equalsIgnoreCase(this.name);
}
return super.equals(other);
}
@@ -23,8 +23,9 @@ public class TeleportManager {
}
/**
* Teleport the player to a specified {@link Position}
* Teleport a {@link Player} to a specified {@link Position}
*
* @param player the {@link Player} to teleport
* @param position the target {@link Position} to teleport to
*/
public CompletableFuture<TeleportResult> teleport(Player player, Position position) {
@@ -38,7 +39,7 @@ public class TeleportManager {
private CompletableFuture<TeleportResult> teleportCrossServer(Teleport teleport) {
return CompletableFuture.supplyAsync(() -> {
//todo
return TeleportResult.COMPLETED_CROSS_SERVER;
});
}
@@ -0,0 +1,18 @@
package net.william278.huskhomes.util;
import java.io.InputStream;
/**
* Abstract representation of a reader that reads internal resource files by name
*/
public interface ResourceReader {
/**
* Gets the resource with given filename and reads it as an {@link InputStream}
*
* @param fileName Name of the resource file to read
* @return The resource, read as an {@link InputStream}
*/
InputStream getResource(String fileName);
}