mirror of
https://github.com/darksaid98/HuskHomes.git
synced 2026-12-02 06:28:49 +00:00
Refactor cached data away from cache
This commit is contained in:
14 files changed
+166
-373
No files matched your search
@@ -62,7 +62,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
|
||||
private Settings settings;
|
||||
private Locales locales;
|
||||
private Database database;
|
||||
private Cache cache;
|
||||
private Validator validator;
|
||||
private Manager manager;
|
||||
private EventListener eventListener;
|
||||
@@ -72,6 +71,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
|
||||
private Set<PluginHook> pluginHooks;
|
||||
private List<Command> commands;
|
||||
private Map<String, List<String>> globalPlayerList;
|
||||
private Set<UUID> currentlyOnWarmup;
|
||||
private Server server;
|
||||
@Nullable
|
||||
private Broker broker;
|
||||
@@ -92,9 +92,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
|
||||
public void onEnable() {
|
||||
// Create adventure audience
|
||||
this.audiences = BukkitAudiences.create(this);
|
||||
this.validator = new Validator(this);
|
||||
this.manager = new Manager(this);
|
||||
this.globalPlayerList = new HashMap<>();
|
||||
this.currentlyOnWarmup = new HashSet<>();
|
||||
this.validator = new Validator(this);
|
||||
|
||||
// Load settings and locales
|
||||
initialize("plugin config & locale files", (plugin) -> {
|
||||
@@ -111,12 +111,12 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
|
||||
case SQLITE -> new SqLiteDatabase(this);
|
||||
};
|
||||
|
||||
if (!database.initialize()) {
|
||||
throw new IllegalStateException("Failed to establish a connection to the database. " +
|
||||
"Please check the supplied database credentials in the config file");
|
||||
}
|
||||
database.initialize();
|
||||
});
|
||||
|
||||
// Initialize the manager
|
||||
this.manager = new Manager(this);
|
||||
|
||||
// Initialize the network messenger if proxy mode is enabled
|
||||
if (getSettings().isCrossServer()) {
|
||||
initialize("message broker", (plugin) -> {
|
||||
@@ -128,7 +128,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
|
||||
});
|
||||
}
|
||||
|
||||
this.cache = new Cache(this); // todo remove
|
||||
setRandomTeleportEngine(new NormalDistributionEngine(this));
|
||||
|
||||
// Register plugin hooks (Economy, Maps, Plan)
|
||||
@@ -261,12 +260,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
|
||||
return database;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public Cache getCache() {
|
||||
return cache;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Validator getValidator() {
|
||||
@@ -375,6 +368,12 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
|
||||
return globalPlayerList;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Set<UUID> getCurrentlyOnWarmup() {
|
||||
return currentlyOnWarmup;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getServerName() {
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package net.william278.huskhomes;
|
||||
|
||||
import net.william278.huskhomes.database.Database;
|
||||
import net.william278.huskhomes.teleport.TimedTeleport;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* A cache used to hold frequently accessed data (i.e. TAB-completed homes and warps)
|
||||
*/
|
||||
public class Cache {
|
||||
|
||||
private final HuskHomes plugin;
|
||||
private final Map<String, List<String>> homes = new HashMap<>();
|
||||
private final Map<String, List<String>> publicHomes = new HashMap<>();
|
||||
private final List<String> warps = new ArrayList<>();
|
||||
private final Set<UUID> currentlyOnWarmup = new HashSet<>();
|
||||
|
||||
/**
|
||||
* Create a new cache
|
||||
*/
|
||||
public Cache(@NotNull HuskHomes plugin) {
|
||||
this.plugin = plugin;
|
||||
this.initialize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the cache with public home and warp names
|
||||
*/
|
||||
public void initialize() {
|
||||
final Database database = plugin.getDatabase();
|
||||
plugin.runAsync(() -> {
|
||||
database.getPublicHomes().forEach(home -> {
|
||||
this.getPublicHomes().putIfAbsent(home.getOwner().getUsername(), new ArrayList<>());
|
||||
this.getPublicHomes().get(home.getOwner().getUsername()).add(home.getMeta().getName());
|
||||
});
|
||||
database.getWarps().forEach(warp -> this.getWarps().add(warp.getMeta().getName()));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns if the given user is currently warming up to teleport to a home.
|
||||
*
|
||||
* @param userUuid The user to check.
|
||||
* @return If the user is currently warming up.
|
||||
* @since 3.1
|
||||
*/
|
||||
public boolean isWarmingUp(@NotNull UUID userUuid) {
|
||||
return this.getCurrentlyOnWarmup().contains(userUuid);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Cached home names - maps a {@link UUID} to a list of their homes
|
||||
*/
|
||||
public Map<String, List<String>> getHomes() {
|
||||
return homes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached home names - maps a username to a list of their public homes
|
||||
*/
|
||||
public Map<String, List<String>> getPublicHomes() {
|
||||
return publicHomes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached warp names
|
||||
*/
|
||||
public List<String> getWarps() {
|
||||
return warps;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Cached user UUIDs currently on warmup countdowns for {@link TimedTeleport}s
|
||||
*/
|
||||
public Set<UUID> getCurrentlyOnWarmup() {
|
||||
return currentlyOnWarmup;
|
||||
}
|
||||
}
|
||||
@@ -95,14 +95,6 @@ public interface HuskHomes extends TaskRunner, EventDispatcher {
|
||||
@NotNull
|
||||
Database getDatabase();
|
||||
|
||||
/**
|
||||
* The {@link Cache} that holds cached data
|
||||
*
|
||||
* @return the plugin {@link Cache}
|
||||
*/
|
||||
@NotNull
|
||||
Cache getCache();
|
||||
|
||||
/**
|
||||
* The {@link Validator} for validating thome names and descriptions
|
||||
*
|
||||
@@ -342,11 +334,25 @@ public interface HuskHomes extends TaskRunner, EventDispatcher {
|
||||
.toList();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
Set<UUID> getCurrentlyOnWarmup();
|
||||
|
||||
/**
|
||||
* Returns if the given user is currently warming up to teleport to a home.
|
||||
*
|
||||
* @param userUuid The user to check.
|
||||
* @return If the user is currently warming up.
|
||||
*/
|
||||
default boolean isWarmingUp(@NotNull UUID userUuid) {
|
||||
return this.getCurrentlyOnWarmup().contains(userUuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the {@link Settings} and {@link Locales} from their respective config files
|
||||
*
|
||||
* @return a {@link CompletableFuture} that will be completed when the plugin reload is complete and if it was successful
|
||||
* @return {@code true} if the reload was successful, {@code false} otherwise
|
||||
*/
|
||||
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
|
||||
boolean loadConfigs();
|
||||
|
||||
@NotNull
|
||||
|
||||
@@ -110,7 +110,7 @@ public abstract class BaseHuskHomesAPI {
|
||||
* @since 3.0.2
|
||||
*/
|
||||
public boolean isUserWarmingUp(@NotNull User user) {
|
||||
return plugin.getCache().isWarmingUp(user.getUuid());
|
||||
return plugin.isWarmingUp(user.getUuid());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -27,7 +27,7 @@ public class PublicHomeCommand extends HomeCommand {
|
||||
@NotNull
|
||||
public List<String> suggest(@NotNull CommandUser executor, @NotNull String[] args) {
|
||||
if (args.length <= 2) {
|
||||
return filter(reduceHomeList(plugin.getCache().getHomes()), args);
|
||||
return filter(reduceHomeList(plugin.getManager().homes().getPublicHomes()), args);
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@@ -128,21 +128,21 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
|
||||
case 0, 1 -> {
|
||||
if (args.length == 1 && args[0].contains(".")) {
|
||||
if (executor.hasPermission(getOtherPermission())) {
|
||||
yield filter(reduceHomeList(plugin.getCache().getHomes()), args);
|
||||
yield filter(reduceHomeList(plugin.getManager().homes().getUserHomes()), args);
|
||||
}
|
||||
yield filter(reduceHomeList(plugin.getCache().getHomes()), args);
|
||||
yield filter(reduceHomeList(plugin.getManager().homes().getUserHomes()), args);
|
||||
}
|
||||
if (executor instanceof OnlineUser user) {
|
||||
yield filter(plugin.getCache().getHomes().get(user.getUsername()), args);
|
||||
yield filter(plugin.getManager().homes().getUserHomes().get(user.getUsername()), args);
|
||||
}
|
||||
yield filter(reduceHomeList(plugin.getCache().getHomes()), args);
|
||||
yield filter(reduceHomeList(plugin.getManager().homes().getUserHomes()), args);
|
||||
}
|
||||
case 2 -> filter(arguments.stream().toList(), args);
|
||||
default -> List.of();
|
||||
};
|
||||
} else {
|
||||
return switch (args.length) {
|
||||
case 0, 1 -> filter(plugin.getCache().getWarps(), args);
|
||||
case 0, 1 -> filter(plugin.getManager().warps().getWarps(), args);
|
||||
case 2 -> filter(arguments.stream().toList(), args);
|
||||
default -> List.of();
|
||||
};
|
||||
|
||||
@@ -10,11 +10,13 @@ import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -24,84 +26,8 @@ import java.util.stream.Collectors;
|
||||
*/
|
||||
public abstract class Database {
|
||||
|
||||
/**
|
||||
* Stores data about {@link User}s
|
||||
* <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;
|
||||
|
||||
/**
|
||||
* Instance of the implementing plugin
|
||||
*/
|
||||
protected final HuskHomes plugin;
|
||||
|
||||
|
||||
/**
|
||||
* Loads SQL table creation schema statements from a resource file as a string array
|
||||
*
|
||||
@@ -124,43 +50,27 @@ public abstract class Database {
|
||||
*/
|
||||
protected final String formatStatementTables(@NotNull String sql) {
|
||||
return sql
|
||||
.replaceAll("%positions_table%", positionsTableName)
|
||||
.replaceAll("%players_table%", playerTableName)
|
||||
.replaceAll("%teleports_table%", teleportsTableName)
|
||||
.replaceAll("%saved_positions_table%", savedPositionsTableName)
|
||||
.replaceAll("%homes_table%", homesTableName)
|
||||
.replaceAll("%warps_table%", warpsTableName);
|
||||
.replaceAll("%positions_table%", plugin.getSettings().getTableName(Table.POSITION_DATA))
|
||||
.replaceAll("%players_table%", plugin.getSettings().getTableName(Table.PLAYER_DATA))
|
||||
.replaceAll("%teleports_table%", plugin.getSettings().getTableName(Table.TELEPORT_DATA))
|
||||
.replaceAll("%saved_positions_table%", plugin.getSettings().getTableName(Table.SAVED_POSITION_DATA))
|
||||
.replaceAll("%homes_table%", plugin.getSettings().getTableName(Table.HOME_DATA))
|
||||
.replaceAll("%warps_table%", plugin.getSettings().getTableName(Table.WARP_DATA));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a database instance, pulling table names from the plugin config
|
||||
*
|
||||
* @param implementor the implementing plugin instance
|
||||
* @param plugin the implementing plugin instance
|
||||
*/
|
||||
protected Database(@NotNull HuskHomes implementor) {
|
||||
this.plugin = implementor;
|
||||
this.playerTableName = implementor.getSettings().getTableName(Table.PLAYER_DATA);
|
||||
this.positionsTableName = implementor.getSettings().getTableName(Table.POSITION_DATA);
|
||||
this.savedPositionsTableName = implementor.getSettings().getTableName(Table.SAVED_POSITION_DATA);
|
||||
this.homesTableName = implementor.getSettings().getTableName(Table.HOME_DATA);
|
||||
this.warpsTableName = implementor.getSettings().getTableName(Table.WARP_DATA);
|
||||
this.teleportsTableName = implementor.getSettings().getTableName(Table.TELEPORT_DATA);
|
||||
protected Database(@NotNull HuskHomes plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the database and ensure tables are present; create tables if they do not exist.
|
||||
*
|
||||
* @return {@code true} if done successfully
|
||||
*/
|
||||
public abstract boolean initialize();
|
||||
|
||||
/**
|
||||
* Execute a MySQL script file read as an InputStream
|
||||
*
|
||||
* @param inputStream The input stream to read the script from
|
||||
*/
|
||||
public abstract void runScript(@NotNull InputStream inputStream,
|
||||
@NotNull Map<String, String> replacements);
|
||||
public abstract void initialize() throws IllegalStateException;
|
||||
|
||||
/**
|
||||
* <b>(Internal use only)</b> - Sets a position to the position table in the database
|
||||
|
||||
@@ -11,8 +11,6 @@ import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.util.logging.Level;
|
||||
@@ -23,35 +21,11 @@ import java.util.logging.Level;
|
||||
@SuppressWarnings("DuplicatedCode")
|
||||
public class MySqlDatabase extends Database {
|
||||
|
||||
public String host;
|
||||
public int port;
|
||||
public String database;
|
||||
public String username;
|
||||
public String password;
|
||||
public String connectionParameters;
|
||||
|
||||
public int connectionPoolSize;
|
||||
public int connectionPoolIdle;
|
||||
public long connectionPoolLifetime;
|
||||
public long connectionPoolKeepAlive;
|
||||
public long connectionPoolTimeout;
|
||||
|
||||
private static final String DATA_POOL_NAME = "HuskHomesHikariPool";
|
||||
private HikariDataSource dataSource;
|
||||
|
||||
public MySqlDatabase(@NotNull HuskHomes plugin) {
|
||||
super(plugin);
|
||||
this.host = plugin.getSettings().getMySqlHost();
|
||||
this.port = plugin.getSettings().getMySqlPort();
|
||||
this.database = plugin.getSettings().getMySqlDatabase();
|
||||
this.username = plugin.getSettings().getMySqlUsername();
|
||||
this.password = plugin.getSettings().getMySqlPassword();
|
||||
this.connectionParameters = plugin.getSettings().getMySqlConnectionParameters();
|
||||
this.connectionPoolSize = plugin.getSettings().getMySqlConnectionPoolSize();
|
||||
this.connectionPoolIdle = plugin.getSettings().getMySqlConnectionPoolIdle();
|
||||
this.connectionPoolLifetime = plugin.getSettings().getMySqlConnectionPoolLifetime();
|
||||
this.connectionPoolKeepAlive = plugin.getSettings().getMySqlConnectionPoolKeepAlive();
|
||||
this.connectionPoolTimeout = plugin.getSettings().getMySqlConnectionPoolTimeout();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -65,75 +39,58 @@ public class MySqlDatabase extends Database {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean initialize() {
|
||||
try {
|
||||
// Create jdbc driver connection url
|
||||
final String jdbcUrl = "jdbc:mysql://" + host + ":" + port + "/" + database + connectionParameters;
|
||||
dataSource = new HikariDataSource();
|
||||
dataSource.setJdbcUrl(jdbcUrl);
|
||||
public void initialize() throws IllegalStateException {
|
||||
// Initialize the Hikari pooled connection
|
||||
dataSource = new HikariDataSource();
|
||||
dataSource.setJdbcUrl("jdbc:mysql://" +
|
||||
plugin.getSettings().getMySqlHost() +
|
||||
":" +
|
||||
plugin.getSettings().getMySqlPort() +
|
||||
"/" +
|
||||
plugin.getSettings().getMySqlDatabase() +
|
||||
plugin.getSettings().getMySqlConnectionParameters());
|
||||
|
||||
// Authenticate
|
||||
dataSource.setUsername(username);
|
||||
dataSource.setPassword(password);
|
||||
// Authenticate with the database
|
||||
dataSource.setUsername(plugin.getSettings().getMySqlUsername());
|
||||
dataSource.setPassword(plugin.getSettings().getMySqlPassword());
|
||||
|
||||
// Set connection pool options
|
||||
dataSource.setMaximumPoolSize(connectionPoolSize);
|
||||
dataSource.setMinimumIdle(connectionPoolIdle);
|
||||
dataSource.setMaxLifetime(connectionPoolLifetime);
|
||||
dataSource.setKeepaliveTime(connectionPoolKeepAlive);
|
||||
dataSource.setConnectionTimeout(connectionPoolTimeout);
|
||||
dataSource.setPoolName(DATA_POOL_NAME);
|
||||
// Set connection pool options
|
||||
dataSource.setMaximumPoolSize(plugin.getSettings().getMySqlConnectionPoolSize());
|
||||
dataSource.setMinimumIdle(plugin.getSettings().getMySqlConnectionPoolIdle());
|
||||
dataSource.setMaxLifetime(plugin.getSettings().getMySqlConnectionPoolLifetime());
|
||||
dataSource.setKeepaliveTime(plugin.getSettings().getMySqlConnectionPoolKeepAlive());
|
||||
dataSource.setConnectionTimeout(plugin.getSettings().getMySqlConnectionPoolTimeout());
|
||||
dataSource.setPoolName(DATA_POOL_NAME);
|
||||
|
||||
// Set additional connection pool properties
|
||||
dataSource.setDataSourceProperties(new Properties() {{
|
||||
put("cachePrepStmts", "true");
|
||||
put("prepStmtCacheSize", "250");
|
||||
put("prepStmtCacheSqlLimit", "2048");
|
||||
put("useServerPrepStmts", "true");
|
||||
put("useLocalSessionState", "true");
|
||||
put("useLocalTransactionState", "true");
|
||||
put("rewriteBatchedStatements", "true");
|
||||
put("cacheResultSetMetadata", "true");
|
||||
put("cacheServerConfiguration", "true");
|
||||
put("elideSetAutoCommits", "true");
|
||||
put("maintainTimeStats", "false");
|
||||
}});
|
||||
// Set additional connection pool properties
|
||||
dataSource.setDataSourceProperties(new Properties() {{
|
||||
put("cachePrepStmts", "true");
|
||||
put("prepStmtCacheSize", "250");
|
||||
put("prepStmtCacheSqlLimit", "2048");
|
||||
put("useServerPrepStmts", "true");
|
||||
put("useLocalSessionState", "true");
|
||||
put("useLocalTransactionState", "true");
|
||||
put("rewriteBatchedStatements", "true");
|
||||
put("cacheResultSetMetadata", "true");
|
||||
put("cacheServerConfiguration", "true");
|
||||
put("elideSetAutoCommits", "true");
|
||||
put("maintainTimeStats", "false");
|
||||
}});
|
||||
|
||||
// Prepare database schema; make tables if they don't exist
|
||||
try (Connection connection = dataSource.getConnection()) {
|
||||
// Load database schema CREATE statements from schema file
|
||||
final String[] databaseSchema = getSchemaStatements("database/mysql_schema.sql");
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
for (String tableCreationStatement : databaseSchema) {
|
||||
statement.execute(tableCreationStatement);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (SQLException | IOException e) {
|
||||
plugin.log(Level.SEVERE, "An error occurred creating tables on the MySQL database: ", e);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
plugin.log(Level.SEVERE, "An unhandled exception occurred during database setup!", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runScript(@NotNull InputStream inputStream, @NotNull Map<String, String> replacements) {
|
||||
try (Connection connection = getConnection()) {
|
||||
final String[] scriptString;
|
||||
scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)};
|
||||
replacements.forEach((key, value) -> scriptString[0] = scriptString[0].replaceAll(key, value));
|
||||
connection.setAutoCommit(false);
|
||||
// Prepare database schema; make tables if they don't exist
|
||||
try (Connection connection = dataSource.getConnection()) {
|
||||
final String[] databaseSchema = getSchemaStatements("database/mysql_schema.sql");
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
for (String statementString : scriptString[0].split(";")) {
|
||||
statement.addBatch(statementString);
|
||||
for (String tableCreationStatement : databaseSchema) {
|
||||
statement.execute(tableCreationStatement);
|
||||
}
|
||||
statement.executeBatch();
|
||||
} catch (SQLException e) {
|
||||
throw new IllegalStateException("Failed to create database tables. Please ensure you are running MySQL v8.0+ " +
|
||||
"and that your connecting user account has privileges to create tables.", e);
|
||||
}
|
||||
} catch (IOException | SQLException e) {
|
||||
plugin.log(Level.SEVERE, "An error occurred running a script on the MySQL database: ", e);
|
||||
throw new RuntimeException(e);
|
||||
} catch (SQLException | IOException e) {
|
||||
throw new IllegalStateException("Failed to establish a connection to the MySQL database. " +
|
||||
"Please check the supplied database credentials in the config file", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,6 @@ import org.sqlite.SQLiteConfig;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.util.logging.Level;
|
||||
@@ -82,50 +80,21 @@ public class SqLiteDatabase extends Database {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean initialize() {
|
||||
public void initialize() throws IllegalStateException {
|
||||
// Set up the connection
|
||||
setConnection();
|
||||
|
||||
// Prepare database schema; make tables if they don't exist
|
||||
try {
|
||||
// Set up the connection
|
||||
setConnection();
|
||||
|
||||
// Prepare database schema; make tables if they don't exist
|
||||
try {
|
||||
// Load database schema CREATE statements from schema file
|
||||
final String[] databaseSchema = getSchemaStatements("database/sqlite_schema.sql");
|
||||
try (Statement statement = getConnection().createStatement()) {
|
||||
for (String tableCreationStatement : databaseSchema) {
|
||||
statement.execute(tableCreationStatement);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (SQLException | IOException e) {
|
||||
plugin.log(Level.SEVERE, "An error occurred creating tables on the SQLite database: ", e);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
plugin.log(Level.SEVERE, "An unhandled exception occurred during database setup!", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runScript(@NotNull InputStream inputStream, @NotNull Map<String, String> replacements) {
|
||||
try {
|
||||
final String[] scriptString;
|
||||
scriptString = new String[]{new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)};
|
||||
replacements.forEach((key, value) -> scriptString[0] = scriptString[0].replaceAll(key, value));
|
||||
final boolean autoCommit = getConnection().getAutoCommit();
|
||||
|
||||
// Execute batched SQLite script
|
||||
getConnection().setAutoCommit(false);
|
||||
// Load database schema CREATE statements from schema file
|
||||
final String[] databaseSchema = getSchemaStatements("database/sqlite_schema.sql");
|
||||
try (Statement statement = getConnection().createStatement()) {
|
||||
for (String statementString : scriptString[0].split(";")) {
|
||||
statement.addBatch(statementString);
|
||||
for (String tableCreationStatement : databaseSchema) {
|
||||
statement.execute(tableCreationStatement);
|
||||
}
|
||||
statement.executeBatch();
|
||||
}
|
||||
getConnection().setAutoCommit(autoCommit);
|
||||
} catch (IOException | SQLException e) {
|
||||
plugin.log(Level.SEVERE, "An exception occurred running script on the SQLite database", e);
|
||||
throw new RuntimeException(e);
|
||||
} catch (SQLException | IOException e) {
|
||||
throw new IllegalStateException("Failed to initialize the SQLite database", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import net.william278.huskhomes.HuskHomes;
|
||||
import net.william278.huskhomes.network.Broker;
|
||||
import net.william278.huskhomes.network.Message;
|
||||
import net.william278.huskhomes.network.Payload;
|
||||
import net.william278.huskhomes.position.Home;
|
||||
import net.william278.huskhomes.position.Position;
|
||||
import net.william278.huskhomes.teleport.Teleport;
|
||||
import net.william278.huskhomes.user.OnlineUser;
|
||||
@@ -58,6 +57,9 @@ public class EventListener {
|
||||
}, plugin.getSettings().getBrokerType() == Broker.Type.PLUGIN_MESSAGE ? 40L : 0L);
|
||||
}
|
||||
|
||||
// Cache this user's homes
|
||||
plugin.getManager().homes().cacheUserHomes(onlineUser);
|
||||
|
||||
// Set their ignoring requests state
|
||||
plugin.getDatabase().getUserData(onlineUser.getUuid()).ifPresent(userData -> {
|
||||
final boolean ignoringRequests = userData.isIgnoringTeleports();
|
||||
@@ -70,12 +72,6 @@ public class EventListener {
|
||||
.orElse("")).ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale)));
|
||||
}
|
||||
});
|
||||
|
||||
// Cache this user's homes
|
||||
plugin.getCache().getHomes().put(onlineUser.getUsername(), plugin.getDatabase()
|
||||
.getHomes(onlineUser).stream()
|
||||
.map(Home::getName)
|
||||
.toList());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -115,12 +111,12 @@ public class EventListener {
|
||||
* @param onlineUser the leaving {@link OnlineUser}
|
||||
*/
|
||||
protected final void handlePlayerLeave(@NotNull OnlineUser onlineUser) {
|
||||
// Remove this user's home cache
|
||||
plugin.getCache().getHomes().remove(onlineUser.getUsername());
|
||||
|
||||
// Set offline position
|
||||
plugin.getDatabase().setOfflinePosition(onlineUser, onlineUser.getPosition());
|
||||
|
||||
// Remove this user's home cache
|
||||
plugin.getManager().homes().removeUserHomes(onlineUser);
|
||||
|
||||
// Update global lists
|
||||
if (plugin.getSettings().isCrossServer()) {
|
||||
plugin.getOnlineUsers().stream()
|
||||
|
||||
@@ -11,13 +11,48 @@ import net.william278.huskhomes.user.User;
|
||||
import net.william278.huskhomes.util.ValidationException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.*;
|
||||
|
||||
public class HomesManager {
|
||||
|
||||
private final HuskHomes plugin;
|
||||
private final List<Home> publicHomes;
|
||||
private final Map<String, List<Home>> userHomes;
|
||||
|
||||
protected HomesManager(@NotNull HuskHomes plugin) {
|
||||
this.plugin = plugin;
|
||||
this.publicHomes = plugin.getDatabase().getPublicHomes();
|
||||
this.userHomes = new HashMap<>();
|
||||
plugin.runAsync(() -> plugin.getOnlineUsers()
|
||||
.forEach(this::cacheUserHomes));
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached user homes - maps a username to a list of their homes
|
||||
*/
|
||||
@NotNull
|
||||
public Map<String, List<String>> getUserHomes() {
|
||||
return userHomes.entrySet().stream()
|
||||
.collect(HashMap::new, (m, e) -> m.put(e.getKey(), e.getValue().stream().map(Home::getName).toList()),
|
||||
HashMap::putAll);
|
||||
}
|
||||
|
||||
public void cacheUserHomes(@NotNull User user) {
|
||||
userHomes.put(user.getUuid().toString(), plugin.getDatabase().getHomes(user));
|
||||
}
|
||||
|
||||
public void removeUserHomes(@NotNull User user) {
|
||||
userHomes.remove(user.getUuid().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached public homes - maps a username to a list of their public homes
|
||||
*/
|
||||
@NotNull
|
||||
public Map<String, List<String>> getPublicHomes() {
|
||||
return publicHomes.stream()
|
||||
.collect(HashMap::new, (m, e) -> m.put(e.getOwner().getUsername(), List.of(e.getName())),
|
||||
HashMap::putAll);
|
||||
}
|
||||
|
||||
public void createHome(@NotNull User owner, @NotNull String name, @NotNull Position position,
|
||||
|
||||
@@ -18,21 +18,15 @@ import java.util.*;
|
||||
*/
|
||||
public class RequestsManager {
|
||||
|
||||
@NotNull
|
||||
private final HuskHomes plugin;
|
||||
|
||||
/**
|
||||
* Map of user UUIDs to a queue of received teleport requests
|
||||
*/
|
||||
// Map of user UUIDs to a queue of received teleport requests
|
||||
private final Map<UUID, Deque<TeleportRequest>> requests;
|
||||
|
||||
/**
|
||||
* Set of users who are ignoring tpa requests
|
||||
*/
|
||||
// Set of users who are ignoring tpa requests
|
||||
private final Set<UUID> ignoringRequests;
|
||||
|
||||
public RequestsManager(@NotNull HuskHomes implementation) {
|
||||
this.plugin = implementation;
|
||||
public RequestsManager(@NotNull HuskHomes plugin) {
|
||||
this.plugin = plugin;
|
||||
this.requests = new HashMap<>();
|
||||
this.ignoringRequests = new HashSet<>();
|
||||
}
|
||||
@@ -173,8 +167,6 @@ public class RequestsManager {
|
||||
*
|
||||
* @param request The {@link TeleportRequest} to send
|
||||
* @param recipient The online recipient of the request
|
||||
* @return the {@link TeleportRequest} that was sent if it could be sent, otherwise an empty optional if it was not
|
||||
* sent because the recipient is ignoring requests or is vanished ({@link OnlineUser#isVanished()})
|
||||
*/
|
||||
public void sendLocalTeleportRequest(@NotNull TeleportRequest request, @NotNull OnlineUser recipient) {
|
||||
request.setRecipientName(recipient.getUsername());
|
||||
@@ -196,7 +188,7 @@ public class RequestsManager {
|
||||
// Add the request and display a message to the recipient
|
||||
addTeleportRequest(request, recipient);
|
||||
plugin.getLocales().getLocale((request.getType() == TeleportRequest.Type.TPA ? "tpa" : "tpahere")
|
||||
+ "_request_received", request.getRequesterName())
|
||||
+ "_request_received", request.getRequesterName())
|
||||
.ifPresent(recipient::sendMessage);
|
||||
plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName())
|
||||
.ifPresent(recipient::sendMessage);
|
||||
|
||||
@@ -7,13 +7,24 @@ import net.william278.huskhomes.position.Warp;
|
||||
import net.william278.huskhomes.util.ValidationException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public class WarpsManager {
|
||||
private final HuskHomes plugin;
|
||||
private final List<Warp> warps;
|
||||
|
||||
protected WarpsManager(@NotNull HuskHomes plugin) {
|
||||
this.plugin = plugin;
|
||||
this.warps = plugin.getDatabase().getWarps();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached warp names
|
||||
*/
|
||||
@NotNull
|
||||
public List<String> getWarps() {
|
||||
return warps.stream().map(Warp::getName).toList();
|
||||
}
|
||||
|
||||
public void createWarp(@NotNull String name, @NotNull Position position, boolean overwrite) throws ValidationException {
|
||||
|
||||
@@ -38,7 +38,7 @@ public class TimedTeleport extends Teleport {
|
||||
}
|
||||
|
||||
// Check if the teleporter is already warming up to teleport
|
||||
if (plugin.getCache().getCurrentlyOnWarmup().contains(teleporter.getUuid())) {
|
||||
if (plugin.isWarmingUp(teleporter.getUuid())) {
|
||||
throw new TeleportationException(TeleportationException.Type.ALREADY_WARMING_UP);
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ public class TimedTeleport extends Teleport {
|
||||
// Execute the warmup, fire the event, then execute the teleport if warmup completes normally
|
||||
private void process() {
|
||||
plugin.fireEvent(plugin.getTeleportWarmupEvent(this, timeLeft), (event) -> {
|
||||
plugin.getCache().getCurrentlyOnWarmup().add(teleporter.getUuid());
|
||||
plugin.getCurrentlyOnWarmup().add(teleporter.getUuid());
|
||||
plugin.getLocales().getLocale("teleporting_warmup_start", Integer.toString(timeLeft))
|
||||
.ifPresent(teleporter::sendMessage);
|
||||
|
||||
@@ -78,7 +78,7 @@ public class TimedTeleport extends Teleport {
|
||||
|
||||
// Tick (decrement) the timed teleport timer and end it if done
|
||||
if (tickAndGetIfDone()) {
|
||||
plugin.getCache().getCurrentlyOnWarmup().remove(teleporter.getUuid());
|
||||
plugin.getCurrentlyOnWarmup().remove(teleporter.getUuid());
|
||||
plugin.cancelTask(warmupTaskId.get());
|
||||
}
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user