mirror of
https://github.com/darksaid98/HuskHomes.git
synced 2026-12-02 22:17:17 +00:00
Refactor bootstrap procedure, use enum for command loading
This commit is contained in:
1 parent
eff21a16d5
commit
ec1c0b744f
42 files changed
+982
-718
No files matched your search
@@ -0,0 +1,412 @@
|
||||
package net.william278.huskhomes.database;
|
||||
|
||||
import net.william278.huskhomes.config.Settings;
|
||||
import net.william278.huskhomes.player.User;
|
||||
import net.william278.huskhomes.player.UserData;
|
||||
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.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 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 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>
|
||||
* <li>last_position - References positions table; where the user was when they last teleported</li>
|
||||
* <li>offline_position - References positions table; the user's last online position. Updated on disconnect</li>
|
||||
* <li>respawn_position - References positions table; where the user last updated their spawn point</li>
|
||||
* <li>home_slots - An integer; the number of home slots this user has consumed (bought)</li>
|
||||
* <li>ignoring_requests - A boolean; whether or not this user is ignoring teleport requests</li>
|
||||
* <li>rtp_cooldown - A datetime timestamp; representing when this user can randomly teleport again</li>
|
||||
* </ol>
|
||||
*/
|
||||
protected final String playerTableName;
|
||||
|
||||
/**
|
||||
* Stores data about {@link Position}s
|
||||
* <ol>
|
||||
* <li>id - Primary key, auto-increment; the id representing the position</li>
|
||||
* <li>x - The double-precision x-coordinate of the position</li>
|
||||
* <li>y - The double-precision y-coordinate of the position</li>
|
||||
* <li>z - The double-precision z-coordinate of the position</li>
|
||||
* <li>yaw - The float-precision yaw facing directional value of the position</li>
|
||||
* <li>pitch - The float-precision pitch facing directional value of the position</li>
|
||||
* <li>world_name - String file name of the world the position is on</li>
|
||||
* <li>world_uuid - String uuid of the world the position is on</li>
|
||||
* <li>server_name - String name of the server the position world is on</li>
|
||||
* </ol>
|
||||
*/
|
||||
protected final String positionsTableName;
|
||||
|
||||
/**
|
||||
* Stores {@link SavedPosition}s, including metadata about them
|
||||
* <ol>
|
||||
* <li>id - Primary key, auto-increment; The id representing the position meta</li>
|
||||
* <li>position_id - References the positions table; the position location data of this saved position</li>
|
||||
* <li>name - The name string of the position represented by this metadata</li>
|
||||
* <li>description - A description string of the position represented by this metadata</li>
|
||||
* <li>timestamp - A datetime timestamp representing when the position this represents was created</li>
|
||||
* </ol>
|
||||
*/
|
||||
protected final String savedPositionsTableName;
|
||||
|
||||
/**
|
||||
* Stores {@link Home} data
|
||||
* <ol>
|
||||
* <li>uuid - Primary key, unique; The unique id of the home</li>
|
||||
* <li>saved_position id - References the saved position table; The id of the home saved position data</li>
|
||||
* <li>owner_uuid - References the players table; the uuid of the person who set the home</li>
|
||||
* <li>is_public - Boolean value; represents if the home is set to public</li>
|
||||
* </ol>
|
||||
*/
|
||||
protected final String homesTableName;
|
||||
|
||||
/**
|
||||
* Stores {@link Warp} data
|
||||
* <ol>
|
||||
* <li>uuid - Primary key, unique; The unique id of the warp</li>
|
||||
* <li>saved_position id - References the saved position table; The id of the warp saved position data</li>
|
||||
* </ol>
|
||||
*/
|
||||
protected final String warpsTableName;
|
||||
|
||||
/**
|
||||
* 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>
|
||||
* </ol>
|
||||
*/
|
||||
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("%saved_positions_table%", savedPositionsTableName)
|
||||
.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, @NotNull Logger logger, @NotNull ResourceReader resourceReader) {
|
||||
this.playerTableName = settings.
|
||||
getStringValue(Settings.ConfigOption.DATABASE_PLAYER_TABLE_NAME);
|
||||
this.positionsTableName = settings.
|
||||
getStringValue(Settings.ConfigOption.DATABASE_POSITIONS_TABLE_NAME);
|
||||
this.savedPositionsTableName = settings.
|
||||
getStringValue(Settings.ConfigOption.DATABASE_SAVED_POSITIONS_TABLE_NAME);
|
||||
this.homesTableName = settings.
|
||||
getStringValue(Settings.ConfigOption.DATABASE_HOMES_TABLE_NAME);
|
||||
this.warpsTableName = settings.
|
||||
getStringValue(Settings.ConfigOption.DATABASE_WARPS_TABLE_NAME);
|
||||
this.teleportsTableName = settings.
|
||||
getStringValue(Settings.ConfigOption.DATABASE_TELEPORTS_TABLE_NAME);
|
||||
this.logger = logger;
|
||||
this.resourceReader = resourceReader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the database and ensure tables are present; create tables if they do not exist.
|
||||
*
|
||||
* @return A future returning void when complete
|
||||
*/
|
||||
public abstract boolean initialize();
|
||||
|
||||
/**
|
||||
* <b>(Internal use only)</b> - Sets a position to the position table in the database
|
||||
*
|
||||
* @param position The {@link Position} to set
|
||||
* @param connection SQL connection
|
||||
* @return The newly inserted row ID
|
||||
* @throws SQLException if an SQL exception occurs doing this
|
||||
*/
|
||||
protected abstract int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException;
|
||||
|
||||
/**
|
||||
* <b>(Internal use only)</b> - Updates position data
|
||||
*
|
||||
* @param positionId ID of the position to update
|
||||
* @param position the new position
|
||||
* @param connection SQL connection
|
||||
* @throws SQLException if an SQL exception occurs doing this
|
||||
*/
|
||||
protected abstract void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException;
|
||||
|
||||
/**
|
||||
* <b>(Internal use only)</b> - Sets a {@link SavedPosition} to the database
|
||||
*
|
||||
* @param position The {@link SavedPosition} to set
|
||||
* @param connection SQL connection
|
||||
* @return The newly inserted row ID
|
||||
* @throws SQLException if an SQL exception occurs doing this
|
||||
*/
|
||||
protected abstract int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException;
|
||||
|
||||
/**
|
||||
* <b>(Internal use only)</b> - Updates a saved position metadata
|
||||
*
|
||||
* @param savedPositionId ID of the metadata to update
|
||||
* @param savedPosition the new saved position
|
||||
* @param connection SQL connection
|
||||
* @throws SQLException if an SQL exception occurs doing this
|
||||
*/
|
||||
protected abstract void updateSavedPosition(int savedPositionId, @NotNull SavedPosition savedPosition, @NotNull Connection connection) throws SQLException;
|
||||
|
||||
/**
|
||||
* Ensure a {@link User} has a {@link UserData} entry in the database and that their username is up-to-date
|
||||
*
|
||||
* @param user The {@link User} to ensure
|
||||
* @return A future returning void when complete
|
||||
*/
|
||||
public abstract CompletableFuture<Void> ensureUser(@NotNull User user);
|
||||
|
||||
/**
|
||||
* Get a user by their username (<i>case-insensitive</i>)
|
||||
*
|
||||
* @param name Username of the {@link UserData} to get (<i>case-insensitive</i>)
|
||||
* @return A future returning an optional with the {@link UserData} present if they exist
|
||||
*/
|
||||
public abstract CompletableFuture<Optional<UserData>> getUserByName(@NotNull String name);
|
||||
|
||||
/**
|
||||
* Get a player by their Minecraft account {@link UUID}
|
||||
*
|
||||
* @param uuid Minecraft account {@link UUID} of the {@link UserData} to get
|
||||
* @return A future returning an optional with the {@link UserData} present if they exist
|
||||
*/
|
||||
public abstract CompletableFuture<Optional<UserData>> getUser(@NotNull UUID uuid);
|
||||
|
||||
|
||||
/**
|
||||
* Get a list of {@link Home}s set by a {@link User}
|
||||
*
|
||||
* @param user {@link User} to get the homes of
|
||||
* @return A future returning void when complete
|
||||
*/
|
||||
public abstract CompletableFuture<List<Home>> getHomes(@NotNull User user);
|
||||
|
||||
/**
|
||||
* Get a list of all {@link Warp}s that have been set
|
||||
*
|
||||
* @return A future returning a list containing all {@link Warp}s
|
||||
*/
|
||||
public abstract CompletableFuture<List<Warp>> getWarps();
|
||||
|
||||
/**
|
||||
* Get a list of all publicly-set {@link Home}s
|
||||
*
|
||||
* @return A future returning a list containing all publicly-set {@link Home}s
|
||||
*/
|
||||
public abstract CompletableFuture<List<Home>> getPublicHomes();
|
||||
|
||||
/**
|
||||
* Get a {@link Home} set by a {@link User}
|
||||
*
|
||||
* @param user 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 User user, @NotNull String homeName);
|
||||
|
||||
/**
|
||||
* Get a {@link Home} by its unique id
|
||||
*
|
||||
* @param uuid the {@link UUID} 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 UUID uuid);
|
||||
|
||||
/**
|
||||
* Get a {@link Warp} with the given name (<i>case-insensitive</i>)
|
||||
*
|
||||
* @param warpName The <i>case-insensitive</i> name of the warp to get
|
||||
* @return A future returning an optional with the {@link Warp} present if it exists
|
||||
*/
|
||||
public abstract CompletableFuture<Optional<Warp>> getWarp(@NotNull String warpName);
|
||||
|
||||
/**
|
||||
* Get a {@link Warp} by its unique id
|
||||
*
|
||||
* @param uuid the {@link UUID} of the warp to get
|
||||
* @return A future returning an optional with the {@link Warp} present if it exists
|
||||
*/
|
||||
public abstract CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID uuid);
|
||||
|
||||
/**
|
||||
* Get the current {@link Teleport} being executed by the specified {@link User}
|
||||
*
|
||||
* @param user 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 User user);
|
||||
|
||||
/**
|
||||
* Updates a user in the database with new {@link UserData}
|
||||
*
|
||||
* @param userData The {@link UserData} to update
|
||||
* @return A future returning void when complete
|
||||
*/
|
||||
public abstract CompletableFuture<Void> updateUserData(@NotNull UserData userData);
|
||||
|
||||
/**
|
||||
* Sets or clears the current {@link Teleport} being executed by a {@link User}
|
||||
*
|
||||
* @param user 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 User user, @Nullable Teleport teleport);
|
||||
|
||||
/**
|
||||
* Get the last teleport {@link Position} of a specified {@link User}
|
||||
*
|
||||
* @param user 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 User user);
|
||||
|
||||
/**
|
||||
* Sets the last teleport {@link Position} of a {@link User}
|
||||
*
|
||||
* @param user 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 User user, @NotNull Position position);
|
||||
|
||||
/**
|
||||
* Get the offline {@link Position} of a specified {@link User}
|
||||
*
|
||||
* @param user 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 User user);
|
||||
|
||||
/**
|
||||
* Sets the offline {@link Position} of a {@link User}
|
||||
*
|
||||
* @param user 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 User user, @NotNull Position position);
|
||||
|
||||
/**
|
||||
* Get the respawn {@link Position} of a specified {@link User}
|
||||
*
|
||||
* @param user 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 User user);
|
||||
|
||||
/**
|
||||
* Sets or clears the respawn {@link Position} of a {@link User}
|
||||
*
|
||||
* @param user 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 User user, @Nullable Position position);
|
||||
|
||||
/**
|
||||
* Sets or updates a {@link Home} into the home data table on the database.
|
||||
*
|
||||
* @param home The {@link Home} to set - or update - in the database.
|
||||
* @return A future returning void when complete
|
||||
*/
|
||||
public abstract CompletableFuture<Void> setHome(@NotNull Home home);
|
||||
|
||||
/**
|
||||
* Sets or updates a {@link Warp} into the warp data table on the database.
|
||||
*
|
||||
* @param warp The {@link Warp} to set - or update - in the database.
|
||||
* @return A future returning void when complete
|
||||
*/
|
||||
public abstract CompletableFuture<Void> setWarp(@NotNull Warp warp);
|
||||
|
||||
/**
|
||||
* Deletes a {@link Home} by the given unique id from the home table on the database.
|
||||
*
|
||||
* @param uuid {@link UUID} of the home to delete
|
||||
* @return A future returning void when complete
|
||||
*/
|
||||
public abstract CompletableFuture<Void> deleteHome(@NotNull UUID uuid);
|
||||
|
||||
/**
|
||||
* Deletes a {@link Warp} by the given unique id from the warp table on the database.
|
||||
*
|
||||
* @param uuid {@link UUID} of the warp to delete
|
||||
* @return A future returning void when complete
|
||||
*/
|
||||
public abstract CompletableFuture<Void> deleteWarp(@NotNull UUID uuid);
|
||||
|
||||
/**
|
||||
* Close any remaining connection to the database source
|
||||
*/
|
||||
public abstract void terminate();
|
||||
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,991 @@
|
||||
package net.william278.huskhomes.database;
|
||||
|
||||
import net.william278.huskhomes.config.Settings;
|
||||
import net.william278.huskhomes.player.OnlineUser;
|
||||
import net.william278.huskhomes.player.User;
|
||||
import net.william278.huskhomes.player.UserData;
|
||||
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 org.sqlite.SQLiteConfig;
|
||||
|
||||
import java.io.File;
|
||||
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;
|
||||
|
||||
/**
|
||||
* An SQLite implementation of the plugin {@link Database}
|
||||
*/
|
||||
@SuppressWarnings("DuplicatedCode")
|
||||
public class SqLiteDatabase extends Database {
|
||||
|
||||
/**
|
||||
* Path to the SQLite HuskHomesData.db file
|
||||
*/
|
||||
private final File databaseFile;
|
||||
|
||||
/**
|
||||
* The name of the database file
|
||||
*/
|
||||
private static final String DATABASE_FILE_NAME = "HuskHomesData.db";
|
||||
|
||||
/**
|
||||
* The persistent SQLite database connection
|
||||
*/
|
||||
private Connection connection;
|
||||
|
||||
|
||||
public SqLiteDatabase(@NotNull Settings settings, @NotNull Logger logger, @NotNull ResourceReader resourceReader) {
|
||||
super(settings, logger, resourceReader);
|
||||
this.databaseFile = new File(resourceReader.getDataFolder(), DATABASE_FILE_NAME);
|
||||
}
|
||||
|
||||
private Connection getConnection() throws SQLException {
|
||||
if (connection == null) {
|
||||
setConnection();
|
||||
} else if (connection.isClosed()) {
|
||||
setConnection();
|
||||
}
|
||||
return connection;
|
||||
}
|
||||
|
||||
private void setConnection() {
|
||||
try {
|
||||
// Ensure that the database file exists
|
||||
if (databaseFile.createNewFile()) {
|
||||
getLogger().log(Level.INFO, "Created the SQLite database file");
|
||||
}
|
||||
|
||||
// Specify use of the JDBC SQLite driver
|
||||
Class.forName("org.sqlite.JDBC");
|
||||
|
||||
// Set SQLite database properties
|
||||
SQLiteConfig config = new SQLiteConfig();
|
||||
config.enforceForeignKeys(true);
|
||||
config.setEncoding(SQLiteConfig.Encoding.UTF8);
|
||||
config.setSynchronous(SQLiteConfig.SynchronousMode.FULL);
|
||||
|
||||
// Establish the connection
|
||||
connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath(), config.toProperties());
|
||||
} catch (IOException e) {
|
||||
getLogger().log(Level.SEVERE, "An exception occurred creating the database file", e);
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "An SQL exception occurred initializing the SQLite database", e);
|
||||
} catch (ClassNotFoundException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to load the necessary SQLite driver", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean initialize() {
|
||||
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) {
|
||||
getLogger().log(Level.SEVERE, "An error occurred creating tables on the SQLite database: ", e);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
getLogger().log(Level.SEVERE, "An unhandled exception occurred during database setup!", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
|
||||
try (PreparedStatement statement = getConnection().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 void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException {
|
||||
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
|
||||
UPDATE `%positions_table%`
|
||||
SET `x`=?,
|
||||
`y`=?,
|
||||
`z`=?,
|
||||
`yaw`=?,
|
||||
`pitch`=?,
|
||||
`world_uuid`=?,
|
||||
`world_name`=?,
|
||||
`server_name`=?
|
||||
WHERE `id`=?"""))) {
|
||||
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.uuid.toString());
|
||||
statement.setString(7, position.world.name);
|
||||
statement.setString(8, position.server.name);
|
||||
statement.setDouble(9, positionId);
|
||||
statement.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException {
|
||||
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
|
||||
INSERT INTO `%saved_positions_table%` (`position_id`, `name`, `description`, `timestamp`)
|
||||
VALUES (?,?,?,?);"""),
|
||||
Statement.RETURN_GENERATED_KEYS)) {
|
||||
|
||||
statement.setInt(1, setPosition(position, connection));
|
||||
statement.setString(2, position.meta.name);
|
||||
statement.setString(3, position.meta.description);
|
||||
statement.setTimestamp(4, new Timestamp(Instant.ofEpochSecond(position.meta.timestamp).toEpochMilli()));
|
||||
statement.executeUpdate();
|
||||
|
||||
return statement.getGeneratedKeys().getInt(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position, @NotNull Connection connection) throws SQLException {
|
||||
try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables("""
|
||||
SELECT `position_id`
|
||||
FROM `%saved_positions_table%`
|
||||
WHERE `id`=?;"""))) {
|
||||
selectStatement.setInt(1, savedPositionId);
|
||||
|
||||
final ResultSet resultSet = selectStatement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
final int positionId = resultSet.getInt("position_id");
|
||||
updatePosition(positionId, position, connection);
|
||||
|
||||
try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
|
||||
UPDATE `%saved_positions_table%`
|
||||
SET `name`=?,
|
||||
`description`=?
|
||||
WHERE `id`=?;"""))) {
|
||||
updateStatement.setString(1, position.meta.name);
|
||||
updateStatement.setString(2, position.meta.description);
|
||||
updateStatement.setInt(3, savedPositionId);
|
||||
updateStatement.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> ensureUser(@NotNull User onlineUser) {
|
||||
return CompletableFuture.runAsync(() -> getUser(onlineUser.uuid).thenAccept(optionalUser ->
|
||||
optionalUser.ifPresentOrElse(existingUser -> {
|
||||
if (!existingUser.username.equals(onlineUser.username)) {
|
||||
// Update a player's name if it has changed in the database
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%players_table%`
|
||||
SET `username`=?
|
||||
WHERE `uuid`=?"""))) {
|
||||
|
||||
statement.setString(1, onlineUser.username);
|
||||
statement.setString(2, existingUser.uuid.toString());
|
||||
statement.executeUpdate();
|
||||
}
|
||||
getLogger().log(Level.INFO, "Updated " + onlineUser.username + "'s name in the database (" + existingUser.username + " -> " + onlineUser.username + ")");
|
||||
} 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 {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
INSERT INTO `%players_table%` (`uuid`,`username`)
|
||||
VALUES (?,?);"""))) {
|
||||
|
||||
statement.setString(1, onlineUser.uuid.toString());
|
||||
statement.setString(2, onlineUser.username);
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to insert a player into the database", e);
|
||||
}
|
||||
})));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<UserData>> getUserByName(@NotNull String name) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
|
||||
FROM `%players_table%`
|
||||
WHERE `username`=?"""))) {
|
||||
statement.setString(1, name);
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new UserData(
|
||||
UUID.fromString(resultSet.getString("uuid")),
|
||||
resultSet.getString("username"),
|
||||
resultSet.getInt("home_slots"),
|
||||
resultSet.getBoolean("ignoring_requests"),
|
||||
resultSet.getTimestamp("rtp_cooldown").toInstant().getEpochSecond()));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to fetch a player by name from the database", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<UserData>> getUser(@NotNull UUID uuid) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`, `rtp_cooldown`
|
||||
FROM `%players_table%`
|
||||
WHERE `uuid`=?"""))) {
|
||||
|
||||
statement.setString(1, uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new UserData(
|
||||
UUID.fromString(resultSet.getString("uuid")),
|
||||
resultSet.getString("username"),
|
||||
resultSet.getInt("home_slots"),
|
||||
resultSet.getBoolean("ignoring_requests"),
|
||||
resultSet.getTimestamp("rtp_cooldown").toInstant().getEpochSecond()));
|
||||
}
|
||||
}
|
||||
} 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 {
|
||||
try (PreparedStatement statement = getConnection().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 `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
|
||||
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
|
||||
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 CompletableFuture.supplyAsync(() -> {
|
||||
final List<Warp> warps = new ArrayList<>();
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().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 `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
|
||||
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_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 CompletableFuture.supplyAsync(() -> {
|
||||
final List<Home> userHomes = new ArrayList<>();
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().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 `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
|
||||
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
|
||||
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 User user, @NotNull String homeName) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().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 `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
|
||||
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
|
||||
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 CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().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 `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
|
||||
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
|
||||
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
|
||||
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 CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().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 `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
|
||||
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_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 {
|
||||
try (PreparedStatement statement = getConnection().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 `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
|
||||
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_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 user) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
|
||||
FROM `%teleports_table%`
|
||||
INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id`
|
||||
WHERE `player_uuid`=?"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Teleport(user,
|
||||
new Position(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")))));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query the current teleport of " + user.username, e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> updateUserData(@NotNull UserData userData) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%players_table%`
|
||||
SET `home_slots`=?, `ignoring_requests`=?, `rtp_cooldown`=?
|
||||
WHERE `uuid`=?"""))) {
|
||||
|
||||
statement.setInt(1, userData.homeSlots);
|
||||
statement.setBoolean(2, userData.isIgnoringTeleports);
|
||||
statement.setLong(3, userData.rtpCooldown);
|
||||
statement.setString(4, userData.uuid.toString());
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to update user data for " + userData.username + " on the database", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
// Clear the user's current teleport
|
||||
try {
|
||||
try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables("""
|
||||
DELETE FROM `%positions_table%`
|
||||
WHERE `id`=(
|
||||
SELECT `destination_id`
|
||||
FROM `%teleports_table%`
|
||||
WHERE `%teleports_table%`.`player_uuid`=?
|
||||
);"""))) {
|
||||
deleteStatement.setString(1, user.uuid.toString());
|
||||
deleteStatement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to clear the current teleport of " + user.username, e);
|
||||
}
|
||||
|
||||
// Set the user's teleport into the database (if it's not null)
|
||||
if (teleport != null) {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`)
|
||||
VALUES (?,?);"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
statement.setInt(2, setPosition(teleport.target, connection));
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to set the current teleport of " + user.username, e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<Position>> getLastPosition(@NotNull User user) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
|
||||
FROM `%players_table%`
|
||||
INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id`
|
||||
WHERE `uuid`=?"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Position(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"))));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query the last teleport position of " + user.username, e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setLastPosition(@NotNull User user, @NotNull Position position) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `last_position` FROM `%players_table%`
|
||||
INNER JOIN `%positions_table%` ON `%players_table%`.last_position = "%positions_table%".id
|
||||
WHERE `uuid`=?;"""))) {
|
||||
queryStatement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = queryStatement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
// Update the last position
|
||||
updatePosition(resultSet.getInt("last_position"), position, connection);
|
||||
} else {
|
||||
// Set the last position
|
||||
try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%players_table%`
|
||||
SET `last_position`=?
|
||||
WHERE `uuid`=?;"""))) {
|
||||
updateStatement.setInt(1, setPosition(position, connection));
|
||||
updateStatement.setString(2, user.uuid.toString());
|
||||
updateStatement.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to set the last position of " + user.username, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<Position>> getOfflinePosition(@NotNull User user) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
|
||||
FROM `%players_table%`
|
||||
INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id`
|
||||
WHERE `uuid`=?"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Position(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"))));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query the offline position of " + user.username, e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setOfflinePosition(@NotNull User user, @NotNull Position position) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `offline_position` FROM `%players_table%`
|
||||
INNER JOIN `%positions_table%` ON `%players_table%`.offline_position = "%positions_table%".id
|
||||
WHERE `uuid`=?;"""))) {
|
||||
queryStatement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = queryStatement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
// Update the offline position
|
||||
updatePosition(resultSet.getInt("offline_position"), position, connection);
|
||||
} else {
|
||||
// Set the offline position
|
||||
try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%players_table%`
|
||||
SET `offline_position`=?
|
||||
WHERE `uuid`=?;"""))) {
|
||||
updateStatement.setInt(1, setPosition(position, connection));
|
||||
updateStatement.setString(2, user.uuid.toString());
|
||||
updateStatement.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to set the offline position of " + user.username, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Optional<Position>> getRespawnPosition(@NotNull User user) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
|
||||
FROM `%players_table%`
|
||||
INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id`
|
||||
WHERE `uuid`=?"""))) {
|
||||
statement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
return Optional.of(new Position(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"))));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to query the respawn position of " + user.username, e);
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setRespawnPosition(@NotNull User user, @Nullable Position position) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `respawn_position` FROM `%players_table%`
|
||||
INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = "%positions_table%".id
|
||||
WHERE `uuid`=?;"""))) {
|
||||
queryStatement.setString(1, user.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = queryStatement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
if (position == null) {
|
||||
// Delete a respawn position
|
||||
try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables("""
|
||||
DELETE FROM `%positions_table%`
|
||||
WHERE `id`=(
|
||||
SELECT `respawn_position`
|
||||
FROM `%players_table%`
|
||||
WHERE `%players_table%`.`uuid`=?
|
||||
);"""))) {
|
||||
deleteStatement.setString(1, user.uuid.toString());
|
||||
deleteStatement.executeUpdate();
|
||||
}
|
||||
} else {
|
||||
// Update the respawn position
|
||||
updatePosition(resultSet.getInt("respawn_position"), position, connection);
|
||||
}
|
||||
} else {
|
||||
if (position != null) {
|
||||
// Set a respawn position
|
||||
try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables("""
|
||||
UPDATE `%players_table%`
|
||||
SET `respawn_position`=?
|
||||
WHERE `uuid`=?;"""))) {
|
||||
updateStatement.setInt(1, setPosition(position, connection));
|
||||
updateStatement.setString(2, user.uuid.toString());
|
||||
updateStatement.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to set the respawn position of " + user.username, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setHome(@NotNull Home home) {
|
||||
return CompletableFuture.runAsync(() -> getHome(home.uuid)
|
||||
.thenAccept(existingHome -> existingHome.ifPresentOrElse(presentHome -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `saved_position_id` FROM `%homes_table%`
|
||||
WHERE `uuid`=?;"""))) {
|
||||
statement.setString(1, home.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
updateSavedPosition(resultSet.getInt("saved_position_id"), home, connection);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE,
|
||||
"Failed to update a home in the database for " + home.owner.username, e);
|
||||
}
|
||||
}, () -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
|
||||
VALUES (?,?,?,?);"""))) {
|
||||
statement.setString(1, home.uuid.toString());
|
||||
statement.setInt(2, setSavedPosition(home, connection));
|
||||
statement.setString(3, home.owner.uuid.toString());
|
||||
statement.setBoolean(4, home.isPublic);
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE,
|
||||
"Failed to set a home to the database for " + home.owner.username, e);
|
||||
}
|
||||
})));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> setWarp(@NotNull Warp warp) {
|
||||
return CompletableFuture.runAsync(() -> getWarp(warp.uuid)
|
||||
.thenAccept(existingHome -> existingHome.ifPresentOrElse(presentWarp -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
SELECT `saved_position_id` FROM `%warps_table%`
|
||||
WHERE `uuid`=?;"""))) {
|
||||
statement.setString(1, warp.uuid.toString());
|
||||
|
||||
final ResultSet resultSet = statement.executeQuery();
|
||||
if (resultSet.next()) {
|
||||
updateSavedPosition(resultSet.getInt("saved_position_id"), warp, connection);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to update a warp in the database", e);
|
||||
}
|
||||
}, () -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`)
|
||||
VALUES (?,?);"""))) {
|
||||
statement.setString(1, warp.uuid.toString());
|
||||
statement.setInt(2, setSavedPosition(warp, connection));
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to add a warp to the database", e);
|
||||
}
|
||||
})));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> deleteHome(@NotNull UUID uuid) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
DELETE FROM `%positions_table%`
|
||||
WHERE `%positions_table%`.`id`=(
|
||||
SELECT `position_id`
|
||||
FROM `%saved_positions_table%`
|
||||
WHERE `%saved_positions_table%`.`id`=(
|
||||
SELECT `saved_position_id`
|
||||
FROM `%homes_table%`
|
||||
WHERE `uuid`=?
|
||||
)
|
||||
);"""))) {
|
||||
statement.setString(1, uuid.toString());
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to delete a home from the database", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> deleteWarp(@NotNull UUID uuid) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
|
||||
DELETE FROM `%positions_table%`
|
||||
WHERE `%positions_table%`.`id`=(
|
||||
SELECT `position_id`
|
||||
FROM `%saved_positions_table%`
|
||||
WHERE `%saved_positions_table%`.`id`=(
|
||||
SELECT `saved_position_id`
|
||||
FROM `%warps_table%`
|
||||
WHERE `uuid`=?
|
||||
)
|
||||
);"""))) {
|
||||
statement.setString(1, uuid.toString());
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.SEVERE, "Failed to delete a warp from the database", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void terminate() {
|
||||
try {
|
||||
if (connection != null) {
|
||||
if (!connection.isClosed()) {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
getLogger().log(Level.WARNING, "Failed to properly close the SQLite connection");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user