Restructure connection interfacing system

This commit is contained in:
William committed 2021-10-02 23:07:45 +01:00
1 parent 894b50ad0d
commit 7ef9159daf
33 files changed
+200 -256

No files matched your search

@@ -28,6 +28,7 @@ import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.UUID;
import java.util.logging.Level;
@@ -42,7 +43,7 @@ public final class HuskHomes extends JavaPlugin {
// Database handling
private static Database database;
public static Connection getConnection() {
public static Connection getConnection() throws SQLException {
return database.getConnection();
}
public static void backupDatabase() { database.backup(); }
@@ -35,26 +35,28 @@ public class HuskHomesAPI {
}
/**
Returns a Home set by a player, or NULL if it does not exist
@param player A player
@param homeName Name of the player's home you wish to retrieve
@return the player's Home, or NULL if it does not exist
@see Home
* Returns a Home set by a player, or NULL if it does not exist
*
* @param player A player
* @param homeName Name of the player's home you wish to retrieve
* @return the player's Home, or NULL if it does not exist
* @see Home
*/
public Home getHome(Player player, String homeName) {
return getHome(player.getName(), homeName);
}
/**
Returns a Home set by a player, or NULL if it does not exist
@param ownerUsername Username of the player
@param homeName Name of the player's home you wish to retrieve
@return the player's Home, or NULL if it does not exist
@see Home
* Returns a Home set by a player, or NULL if it does not exist
*
* @param ownerUsername Username of the player
* @param homeName Name of the player's home you wish to retrieve
* @return the player's Home, or NULL if it does not exist
* @see Home
*/
public Home getHome(String ownerUsername, String homeName) {
try {
return DataManager.getHome(ownerUsername, homeName, HuskHomes.getConnection());
try (Connection connection = HuskHomes.getConnection()) {
return DataManager.getHome(ownerUsername, homeName, connection);
} catch (SQLException e) {
huskHomes.getLogger().log(Level.WARNING, "An SQL exception occurred retrieving data for API access", e);
return null;
@@ -62,14 +64,15 @@ public class HuskHomesAPI {
}
/**
Returns a Warp set on the server, or NULL if it does not exist
@param warpName Name of the warp
@return a Warp, or NULL if it does not exist
@see Warp
* Returns a Warp set on the server, or NULL if it does not exist
*
* @param warpName Name of the warp
* @return a Warp, or NULL if it does not exist
* @see Warp
*/
public Warp getWarp(String warpName) {
try {
return DataManager.getWarp(warpName, HuskHomes.getConnection());
public Warp getWarp(String warpName) {
try (Connection connection = HuskHomes.getConnection()) {
return DataManager.getWarp(warpName, connection);
} catch (SQLException e) {
huskHomes.getLogger().log(Level.WARNING, "An SQL exception occurred retrieving data for API access", e);
return null;
@@ -77,24 +80,26 @@ public class HuskHomesAPI {
}
/**
Returns an ArrayList of homes set by a Player
@param player A Player
@return an ArrayList of Homes
@see Home
* Returns an ArrayList of homes set by a Player
*
* @param player A Player
* @return an ArrayList of Homes
* @see Home
*/
public List<Home> getHomes(Player player) {
return getHomes(player.getName());
}
/**
Returns an ArrayList of homes set by a player
@param ownerUsername Username of the player who's homes you want to get
@return an ArrayList of Homes
@see Home
* Returns an ArrayList of homes set by a player
*
* @param ownerUsername Username of the player who's homes you want to get
* @return an ArrayList of Homes
* @see Home
*/
public List<Home> getHomes(String ownerUsername) {
try {
return DataManager.getPlayerHomes(ownerUsername, HuskHomes.getConnection());
try (Connection connection = HuskHomes.getConnection()) {
return DataManager.getPlayerHomes(ownerUsername, connection);
} catch (SQLException e) {
huskHomes.getLogger().log(Level.WARNING, "An SQL exception occurred retrieving data for API access", e);
return null;
@@ -103,6 +108,7 @@ public class HuskHomesAPI {
/**
* Returns how many Homes a given Player has set
*
* @param player the Player being checked
* @return an integer of how many homes a player has set
* @see Home
@@ -113,15 +119,19 @@ public class HuskHomesAPI {
/**
* Returns the maximum number of homes a player can set
*
* @param player the Player being checked
* @return the maximum homes a player can set
* @deprecated Use getMaxSetHomes instead (capitalized H)
*/
@Deprecated
public int getMaxSethomes(Player player) { return getMaxSetHomes(player); }
public int getMaxSethomes(Player player) {
return getMaxSetHomes(player);
}
/**
* Returns the maximum number of homes a player can set
*
* @param player the Player being checked
* @return the maximum homes a player can set
*/
@@ -131,15 +141,19 @@ public class HuskHomesAPI {
/**
* Returns the maximum number of homes a player can set
*
* @param player the Player being checked
* @return the maximum homes a player can set
* @deprecated Use getFreeSetHomes instead (capitalized H)
*/
@Deprecated
public int getFreeSethomes(Player player) { return getFreeSetHomes(player); }
public int getFreeSethomes(Player player) {
return getFreeSetHomes(player);
}
/**
* Returns the number of homes a player can set for free
*
* @param player the Player being checked
* @return the number of free homes a player can set
*/
@@ -148,13 +162,14 @@ public class HuskHomesAPI {
}
/**
Returns an ArrayList of all the public homes set
@return an ArrayList of Homes
@see Home
* Returns an ArrayList of all the public homes set
*
* @return an ArrayList of Homes
* @see Home
*/
public List<Home> getPublicHomes() {
try {
return DataManager.getPublicHomes(HuskHomes.getConnection());
try (Connection connection = HuskHomes.getConnection()) {
return DataManager.getPublicHomes(connection);
} catch (SQLException e) {
huskHomes.getLogger().log(Level.WARNING, "An SQL exception occurred retrieving data for API access", e);
return null;
@@ -163,6 +178,7 @@ public class HuskHomesAPI {
/**
* Returns how many public Homes there are
*
* @return an integer of how many public homes there are
* @see Home
*/
@@ -171,13 +187,14 @@ public class HuskHomesAPI {
}
/**
Returns an ArrayList of all the warps set
@return an ArrayList of Warps
@see Warp
* Returns an ArrayList of all the warps set
*
* @return an ArrayList of Warps
* @see Warp
*/
public List<Warp> getWarps() {
try {
return DataManager.getWarps(HuskHomes.getConnection());
try (Connection connection = HuskHomes.getConnection()) {
return DataManager.getWarps(connection);
} catch (SQLException e) {
huskHomes.getLogger().log(Level.WARNING, "An SQL exception occurred retrieving data for API access", e);
return null;
@@ -186,6 +203,7 @@ public class HuskHomesAPI {
/**
* Returns how many Warps have been set
*
* @return an integer of how many warps have been set
* @see Warp
*/
@@ -195,6 +213,7 @@ public class HuskHomesAPI {
/**
* Returns the current spawn position as a TeleportationPoint
*
* @return the spawn position as a TeleportationPoint
*/
public TeleportationPoint getSpawnPosition() {
@@ -203,30 +222,31 @@ public class HuskHomesAPI {
/**
* Updates a player's last position on the server
*
* @param player The {@link Player} who's last position you wish to update
* @param point the {@link TeleportationPoint} to set as their new last position
* @param point the {@link TeleportationPoint} to set as their new last position
*/
public void updatePlayerLastPosition(Player player, TeleportationPoint point) {
Bukkit.getScheduler().runTaskAsynchronously(huskHomes, () -> {
try {
DataManager.setPlayerLastPosition(player, point, HuskHomes.getConnection());
} catch (SQLException e) {
huskHomes.getLogger().severe("An SQL exception occurred updating a player's last position via the API.");
}
try (Connection connection = HuskHomes.getConnection()) {
DataManager.setPlayerLastPosition(player, point, connection);
} catch (SQLException e) {
huskHomes.getLogger().severe("An SQL exception occurred updating a player's last position via the API.");
}
});
}
/**
* Teleport a player to a specific TeleportationPoint
*
* @param player The player to be teleported
* @param point The target teleportationPoint
* @param timed Whether to do a warmup countdown
* @param point The target teleportationPoint
* @param timed Whether to do a warmup countdown
* @see TeleportationPoint
*/
public void teleportPlayer(Player player, TeleportationPoint point, boolean timed) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTask(huskHomes, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (timed) {
TeleportManager.queueTimedTeleport(player, point, connection);
} else {
@@ -240,15 +260,15 @@ public class HuskHomesAPI {
/**
* Teleport a player to a specific TeleportationPoint
* @param player The player to be teleported
*
* @param player The player to be teleported
* @param targetPlayerName The target player's name
* @param timed Whether to do a warmup countdown
* @param timed Whether to do a warmup countdown
* @see TeleportationPoint
*/
public void teleportPlayer(Player player, String targetPlayerName, boolean timed) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTask(huskHomes, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (timed) {
TeleportManager.queueTimedTeleport(player, targetPlayerName, connection);
} else {
@@ -16,9 +16,8 @@ public class BackCommand extends CommandBase {
@Override
protected void onCommand(Player p, Command command, String label, String[] args) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
TeleportManager.queueBackTeleport(p, connection);
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred teleporting you back");
@@ -42,7 +42,6 @@ public class EditHomeCommand extends CommandBase implements TabCompleter {
return;
}
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
String homeName = args[0];
String ownerName = p.getName();
@@ -57,7 +56,7 @@ public class EditHomeCommand extends CommandBase implements TabCompleter {
}
}
try {
try (Connection connection = HuskHomes.getConnection()) {
if (!DataManager.homeExists(ownerName, homeName, connection)) {
if (!ownerName.equalsIgnoreCase(p.getName())) {
MessageManager.sendMessage(p, "error_home_invalid_other", ownerName, homeName);
@@ -40,9 +40,8 @@ public class EditWarpCommand extends CommandBase implements TabCompleter {
}
String warpName = args[0];
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try(Connection connection = HuskHomes.getConnection()) {
if (!DataManager.warpExists(warpName, connection)) {
MessageManager.sendMessage(p, "error_warp_invalid", warpName);
return;
@@ -30,9 +30,8 @@ public class HomeCommand extends CommandBase {
@Override
protected void onCommand(Player p, Command command, String label, String[] args) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try(Connection connection = HuskHomes.getConnection()) {
if (args.length == 1) {
String homeArgument = args[0];
if (RegexUtil.OWNER_NAME_PATTERN.matcher(homeArgument).matches()) {
@@ -66,9 +65,8 @@ public class HomeCommand extends CommandBase {
// This method updates a player's home cache.
public static void updatePlayerHomeCache(Player p) {
UUID uuid = p.getUniqueId();
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try(Connection connection = HuskHomes.getConnection()) {
List<Home> playerHomes = DataManager.getPlayerHomes(p.getName(), connection);
List<String> homeNames = new ArrayList<>();
for (Home home : playerHomes) {
@@ -43,7 +43,6 @@ public class HomeListCommand extends CommandBase {
}
public static void displayPlayerHomeList(Player player, String homeOwnerName, int pageNumber) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
if (!player.getName().equalsIgnoreCase(homeOwnerName)) {
if (!player.hasPermission("huskhomes.home.other")) {
@@ -51,7 +50,7 @@ public class HomeListCommand extends CommandBase {
return;
}
}
try {
try(Connection connection = HuskHomes.getConnection()) {
if (!DataManager.playerExists(homeOwnerName, connection)) {
MessageManager.sendMessage(player, "error_invalid_player");
return;
@@ -35,9 +35,8 @@ public class PublicHomeCommand extends CommandBase implements TabCompleter {
// Updates the public home cache
public static void updatePublicHomeTabCache() {
publicHomeTabCache.clear();
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
for (Home home : DataManager.getPublicHomes(connection)) {
publicHomeTabCache.put(home.getName(), home.getOwnerUsername());
}
@@ -48,9 +47,8 @@ public class PublicHomeCommand extends CommandBase implements TabCompleter {
}
public static void queueHomeTeleport(Player p, String publicHome) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
String[] split = publicHome.split("\\.");
String ownerName = split[0];
String homeName = split[1];
@@ -102,9 +100,8 @@ public class PublicHomeCommand extends CommandBase implements TabCompleter {
String[] split = publicHomeName.split("\\.");
String ownerName = split[0];
String homeName = split[1];
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (DataManager.homeExists(ownerName, homeName, connection)) {
Home home = DataManager.getHome(ownerName, homeName, connection);
assert home != null;
@@ -34,9 +34,8 @@ public class PublicHomeListCommand extends CommandBase {
}
public static void displayPublicHomeList(Player player, int pageNumber) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
List<Home> homes = DataManager.getPublicHomes(connection);
if (homes.isEmpty()) {
MessageManager.sendMessage(player, "error_no_public_homes_set");
@@ -21,9 +21,8 @@ public class RtpCommand extends CommandBase {
protected void onCommand(Player p, Command command, String label, String[] args) {
if (HuskHomes.getSettings().doRtpCommand()) {
if (p.getWorld().getEnvironment() == World.Environment.NORMAL) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
TeleportManager.queueRandomTeleport(p, connection);
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred queuing a Random teleport", e);
@@ -22,9 +22,8 @@ public class SetHomeCommand extends CommandBase {
String homeName = args[0];
SettingHandler.setHome(p.getLocation(), p, homeName);
} else {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (DataManager.getPlayerHomes(p.getName(), connection).size() == 0) {
// If the player hasn't set a home yet, set one called "home"
SettingHandler.setHome(p.getLocation(), p, "home");
@@ -20,9 +20,8 @@ public class SpawnCommand extends CommandBase {
protected void onCommand(Player p, Command command, String label, String[] args) {
if (HuskHomes.getSettings().doSpawnCommand()) {
String spawnWarpName = HuskHomes.getSettings().getSpawnWarpName();
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
// Cross server spawn teleport
if (HuskHomes.getSettings().doCrossServerSpawn()) {
if (DataManager.warpExists(spawnWarpName, connection)) {
@@ -25,9 +25,8 @@ public class TpCommand extends CommandBase {
@Override
protected void onCommand(Player p, Command command, String label, String[] args) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
switch (args.length) {
default:
case 0:
@@ -19,9 +19,8 @@ public class TpHereCommand extends CommandBase {
protected void onCommand(Player p, Command command, String label, String[] args) {
if (args.length == 1) {
String targetPlayer = args[0];
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
TeleportManager.teleportHere(p, targetPlayer, connection);
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred using /tphere");
@@ -7,6 +7,7 @@ import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.entity.Player;
import java.sql.Connection;
import java.sql.SQLException;
public class TpIgnoreCommand extends CommandBase {
@@ -28,8 +29,8 @@ public class TpIgnoreCommand extends CommandBase {
private void setIgnoringRequestsData(Player player, boolean ignoring) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
DataManager.setPlayerIgnoringRequests(player, ignoring, HuskHomes.getConnection());
try (Connection connection = HuskHomes.getConnection()) {
DataManager.setPlayerIgnoringRequests(player, ignoring, connection);
if (ignoring) {
HuskHomes.setIgnoringTeleportRequests(player.getUniqueId());
} else {
@@ -19,9 +19,8 @@ public class TpOfflineCommand extends CommandBase {
protected void onCommand(Player p, Command command, String label, String[] args) {
if (args.length == 1) {
final String targetPlayer = args[0];
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
TeleportManager.teleportToOfflinePlayer(p, targetPlayer, connection);
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred teleporting you to a player's offline position");
@@ -38,9 +38,8 @@ public class WarpCommand extends CommandBase {
}
if (args.length == 1) {
String warpName = args[0];
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (DataManager.warpExists(warpName, connection)) {
if (Warp.getWarpCanUse(p, warpName)) {
Warp warp = DataManager.getWarp(warpName, connection);
@@ -74,9 +73,8 @@ public class WarpCommand extends CommandBase {
targetPlayer = Bukkit.getPlayer(args[1]);
if (targetPlayer != null) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (DataManager.warpExists(warpName, connection)) {
Warp warp = DataManager.getWarp(warpName, connection);
TeleportManager.teleportPlayer(targetPlayer, warp, connection);
@@ -106,9 +104,8 @@ public class WarpCommand extends CommandBase {
// Updates the public home cache
public static void updateWarpsTabCache() {
warpsTabCache.clear();
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
for (Warp warp : DataManager.getWarps(connection)) {
warpsTabCache.add(warp.getName());
}
@@ -35,9 +35,8 @@ public class WarpListCommand extends CommandBase {
}
public static void displayWarpList(Player player, int pageNumber) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
List<Warp> warps = DataManager.getWarps(connection);
ArrayList<String> warpList = new ArrayList<>();
for (Warp warp : warps) {
@@ -3,10 +3,7 @@ package me.william278.huskhomes2.data.SQL;
import me.william278.huskhomes2.HuskHomes;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
public abstract class Database {
protected HuskHomes plugin;
@@ -15,7 +12,7 @@ public abstract class Database {
plugin = instance;
}
public abstract Connection getConnection();
public abstract Connection getConnection() throws SQLException;
public abstract void load();
@@ -26,31 +23,4 @@ public abstract class Database {
public final long hikariMaximumLifetime = HuskHomes.getSettings().getHikariMaximumLifetime();
public final long hikariKeepAliveTime = HuskHomes.getSettings().getHikariKeepAliveTime();
public final long hikariConnectionTimeOut = HuskHomes.getSettings().getHikariConnectionTimeOut();
public void initialize() {
Connection connection = getConnection();
// Test the retrieved connection; throw an error if it fails
try {
PreparedStatement ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getPlayerDataTable() + ";");
ResultSet rs = ps.executeQuery();
close(ps, rs);
} catch (SQLException ex) {
plugin.getLogger().log(Level.SEVERE, "Failed to retrieve Database connection: ", ex);
}
}
// Close the mySQL connection
public void close(PreparedStatement ps, ResultSet rs) {
try {
if (ps != null)
ps.close();
if (rs != null)
rs.close();
} catch (SQLException ex) {
plugin.getLogger().log(Level.SEVERE, "Failed to close the Database connection: ", ex);
}
}
}
@@ -78,50 +78,38 @@ public class MySQL extends Database {
}
@Override
public Connection getConnection() {
Connection connection = null;
try {
if (dataSource == null || dataSource.isClosed()) {
try {
// Create new HikariCP data source
final String jdbcUrl = "jdbc:mysql://" + host + ":" + port + "/" + database + params;
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setJdbcUrl(jdbcUrl);
hikariDataSource.setUsername(username);
hikariDataSource.setPassword(password);
hikariDataSource.setMaximumPoolSize(hikariMaximumPoolSize);
hikariDataSource.setMinimumIdle(hikariMinimumIdle);
hikariDataSource.setMaxLifetime(hikariMaximumLifetime);
hikariDataSource.setKeepaliveTime(hikariKeepAliveTime);
hikariDataSource.setConnectionTimeout(hikariConnectionTimeOut);
this.dataSource = hikariDataSource;
connection = dataSource.getConnection();
} catch (SQLException e ) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred initialising a new connection via HikariCP", e);
}
} else {
connection = dataSource.getConnection();
}
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred getting the mySQL connection via the existing Hikari pool", e);
}
return connection;
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
@Override
public void load() {
Connection connection = getConnection();
try(Statement statement = connection.createStatement()) {
for (String tableCreationStatement : SQL_SETUP_STATEMENTS) {
statement.execute(tableCreationStatement);
// Create new HikariCP data source
final String jdbcUrl = "jdbc:mysql://" + host + ":" + port + "/" + database + params;
dataSource = new HikariDataSource();
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUsername(username);
dataSource.setPassword(password);
// Set various additional parameters
dataSource.setMaximumPoolSize(hikariMaximumPoolSize);
dataSource.setMinimumIdle(hikariMinimumIdle);
dataSource.setMaxLifetime(hikariMaximumLifetime);
dataSource.setKeepaliveTime(hikariKeepAliveTime);
dataSource.setConnectionTimeout(hikariConnectionTimeOut);
dataSource.setPoolName("HuskHomesHikariPool");
// Create tables
try(Connection connection = dataSource.getConnection()) {
try(Statement statement = connection.createStatement()) {
for (String tableCreationStatement : SQL_SETUP_STATEMENTS) {
statement.execute(tableCreationStatement);
}
}
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An error occurred creating tables on the MySQL database: ", e);
}
initialize();
}
@Override
@@ -80,6 +80,7 @@ public class SQLite extends Database {
super(instance);
}
// Create the database file if it does not exist yet
private void createDatabaseFileIfNotExist() {
File databaseFile = new File(plugin.getDataFolder(), DATABASE_NAME + ".db");
if (!databaseFile.exists()) {
@@ -94,47 +95,38 @@ public class SQLite extends Database {
}
@Override
public Connection getConnection() {
Connection connection = null;
try {
if (dataSource == null || dataSource.isClosed()) {
createDatabaseFileIfNotExist();
try {
final String jdbcUrl = "jdbc:sqlite:" + plugin.getDataFolder().getAbsolutePath() + "/" + DATABASE_NAME + ".db";
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setJdbcUrl(jdbcUrl);
hikariDataSource.setMaximumPoolSize(hikariMaximumPoolSize);
hikariDataSource.setMinimumIdle(hikariMinimumIdle);
hikariDataSource.setMaxLifetime(hikariMaximumLifetime);
hikariDataSource.setKeepaliveTime(hikariKeepAliveTime);
hikariDataSource.setConnectionTimeout(hikariConnectionTimeOut);
this.dataSource = hikariDataSource;
connection = dataSource.getConnection();
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred initialising a new connection via HikariCP", e);
}
} else {
connection = dataSource.getConnection();
}
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred getting the mySQL connection via the existing Hikari pool", e);
}
return connection;
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
@Override
public void load() {
Connection connection = getConnection();
try (Statement statement = connection.createStatement()) {
for (String tableCreationStatement : SQL_SETUP_STATEMENTS) {
statement.execute(tableCreationStatement);
// Make SQLite database file
createDatabaseFileIfNotExist();
// Create new HikariCP data source
final String jdbcUrl = "jdbc:sqlite:" + plugin.getDataFolder().getAbsolutePath() + "/" + DATABASE_NAME + ".db";
dataSource = new HikariDataSource();
dataSource.setJdbcUrl(jdbcUrl);
// Set various additional parameters
dataSource.setMaximumPoolSize(hikariMaximumPoolSize);
dataSource.setMinimumIdle(hikariMinimumIdle);
dataSource.setMaxLifetime(hikariMaximumLifetime);
dataSource.setKeepaliveTime(hikariKeepAliveTime);
dataSource.setConnectionTimeout(hikariConnectionTimeOut);
dataSource.setPoolName("HuskHomesHikariPool");
// Create tables
try(Connection connection = dataSource.getConnection()) {
try(Statement statement = connection.createStatement()) {
for (String tableCreationStatement : SQL_SETUP_STATEMENTS) {
statement.execute(tableCreationStatement);
}
}
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An error occurred creating tables on the SQLite database: ", e);
}
initialize();
}
@Override
@@ -23,10 +23,9 @@ public class CrossServerMessageHandler {
private static final HuskHomes plugin = HuskHomes.getInstance();
public static void handlePluginMessage(Message receivedMessage, Player recipient) {
Connection connection = HuskHomes.getConnection();
switch (receivedMessage.getMessageType()) {
case SET_TP_DESTINATION -> Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
DataManager.setPlayerDestinationLocation(receivedMessage.getMessageData(),
new TeleportationPoint(recipient.getLocation(), HuskHomes.getSettings().getServerID()), connection);
new PluginMessage(receivedMessage.getMessageData(), Message.MessageType.CONFIRM_DESTINATION_SET, "confirmed").send(recipient);
@@ -63,7 +62,7 @@ public class CrossServerMessageHandler {
if (tpaAccepted) {
MessageManager.sendMessage(recipient, "tpa_has_accepted", tpaReplierName);
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
TeleportManager.queueTimedTeleport(recipient, tpaReplierName, connection);
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred responding to a plugin message teleport request reply");
@@ -83,7 +82,7 @@ public class CrossServerMessageHandler {
}
}
case TELEPORT_TO_ME -> Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
TeleportManager.teleportPlayer(recipient, receivedMessage.getMessageData(), connection);
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "An SQL exception occurred responding to a plugin message teleport-to-me request");
@@ -25,11 +25,11 @@ public class BlueMap extends Map {
private static String publicHomeMarkerImageAddress;
private void executeQueuedOperations() {
try {
try (Connection connection = HuskHomes.getConnection()) {
for (String warpName : queuedWarps.keySet()) {
boolean add = queuedWarps.get(warpName);
if (add) {
Warp warpToAdd = DataManager.getWarp(warpName, HuskHomes.getConnection());
Warp warpToAdd = DataManager.getWarp(warpName, connection);
if (warpToAdd != null) {
addWarpMarker(warpToAdd);
}
@@ -42,7 +42,7 @@ public class BlueMap extends Map {
String ownerName = fullHomeName.split("\\.")[0];
String homeName = fullHomeName.split("\\.")[1];
if (add) {
Home homeToAdd = DataManager.getHome(ownerName, homeName, HuskHomes.getConnection());
Home homeToAdd = DataManager.getHome(ownerName, homeName, connection);
if (homeToAdd != null) {
addPublicHomeMarker(homeToAdd);
}
@@ -156,8 +156,7 @@ public class BlueMap extends Map {
@Override
public void initialize() {
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
Connection connection = HuskHomes.getConnection();
try {
try (Connection connection = HuskHomes.getConnection()) {
for (Home home : DataManager.getPublicHomes(connection)) {
if (!HuskHomes.getSettings().doBungee() || home.getServer().equals(HuskHomes.getSettings().getServerID())) {
addPublicHomeMarker(home);
@@ -122,9 +122,8 @@ public class DynMap extends Map {
dynmapAPI.getMarkerAPI().createMarkerIcon(WARP_MARKER_IMAGE_NAME, "Warp", getScaledMarkerIconStream(getWarpIcon()));
dynmapAPI.getMarkerAPI().createMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME, "Public Home", getScaledMarkerIconStream(getPublicHomeIcon()));
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (HuskHomes.getSettings().showPublicHomesOnMap()) {
dynmapAPI.getMarkerAPI().createMarkerSet(PUBLIC_HOMES_MARKER_SET_ID, HuskHomes.getSettings().getMapPublicHomeMarkerSet(), dynmapAPI.getMarkerAPI().getMarkerIcons(), false);
for (Home home : DataManager.getPublicHomes(connection)) {
@@ -130,9 +130,8 @@ public class Pl3xMap extends Map {
}
// Populate map with markers
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (HuskHomes.getSettings().showPublicHomesOnMap()) {
for (Home home : DataManager.getPublicHomes(connection)) {
if (!HuskHomes.getSettings().doBungee() || home.getServer().equals(HuskHomes.getSettings().getServerID())) {
@@ -29,9 +29,8 @@ public class PlayerListener implements Listener {
public void onPlayerDie(PlayerDeathEvent e) {
Player p = e.getEntity();
if (p.hasPermission("huskhomes.back.death")) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
DataManager.setPlayerLastPosition(p, new TeleportationPoint(p.getLocation(), HuskHomes.getSettings().getServerID()), connection);
MessageManager.sendMessage(p, "return_by_death");
} catch (SQLException sqlException) {
@@ -47,9 +46,8 @@ public class PlayerListener implements Listener {
// Create player on SQL if they don't exist already
try {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (!DataManager.playerExists(p, connection)) {
DataManager.createPlayer(p, connection);
if (TeleportManager.getSpawnLocation() != null) {
@@ -108,9 +106,8 @@ public class PlayerListener implements Listener {
final UUID uuid = p.getUniqueId();
if (!HuskHomes.isTeleporting(uuid)) {
final Location logOutLocation = p.getLocation();
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
DataManager.setPlayerOfflinePosition(uuid,
new TeleportationPoint(logOutLocation, HuskHomes.getSettings().getServerID()),
connection);
@@ -58,8 +58,7 @@ public class EssentialsMigrator {
FileConfiguration playerFileConfig = loadConfiguration(playerFile);
final String playerName = playerFileConfig.getString("last-account-name", playerFileConfig.getString("lastAccountName"));
try {
Connection connection = HuskHomes.getConnection();
try {
try (Connection connection = HuskHomes.getConnection()) {
if (!DataManager.playerExists(playerUUID, connection)) {
DataManager.createPlayer(playerUUID, playerName, connection);
}
@@ -121,9 +120,8 @@ public class EssentialsMigrator {
final File[] warpFiles = essentialsWarpsFolder.listFiles();
if (warpFiles != null) {
Connection connection = HuskHomes.getConnection();
for (File warpFile : warpFiles) {
try {
try (Connection connection = HuskHomes.getConnection()) {
final FileConfiguration warpFileConfig = loadConfiguration(warpFile);
final String warpName = warpFileConfig.getString("name");
String worldID = warpFileConfig.getString("world");
@@ -1,7 +1,9 @@
package me.william278.huskhomes2.migrators;
import me.william278.huskhomes2.HuskHomes;
import org.checkerframework.checker.units.qual.C;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@@ -56,15 +58,18 @@ public class UpgradeDatabase {
}
int i = 1;
for (String statement : statements) {
try (PreparedStatement tableUpdateStatement = HuskHomes.getConnection().prepareStatement(statement)) {
tableUpdateStatement.execute();
plugin.getLogger().info("Database upgrade in progress... (" + i + "/" + statements.length + ")");
i++;
try (Connection connection = HuskHomes.getConnection()) {
try (PreparedStatement tableUpdateStatement = connection.prepareStatement(statement)) {
tableUpdateStatement.execute();
plugin.getLogger().info("Database upgrade in progress... (" + i + "/" + statements.length + ")");
i++;
}
} catch (SQLException e) {
plugin.getLogger().info("Skipped performing the database upgrade: " + e.getCause() + ". This might be because another server on your HuskHomes network already carried out the upgrade - in which case you can safely ignore this warning.");
e.printStackTrace();
break;
}
}
// Update the config file version
@@ -76,20 +81,26 @@ public class UpgradeDatabase {
if (plugin.getConfig().getInt("config_file_version", 1) <= 7) {
plugin.getLogger().info("Database upgrade needed: Adding creation timestamps to homes and warps...");
HuskHomes.backupDatabase(); // Backup database before upgrades are carried out!
try (PreparedStatement tableUpdateStatement = HuskHomes.getConnection().prepareStatement(
"ALTER TABLE " + HuskHomes.getSettings().getHomesDataTable()
+ " ADD `creation_time` timestamp NULL DEFAULT NULL;")) {
tableUpdateStatement.execute();
plugin.getLogger().info("Database upgrade in progress... (1/2)");
try (Connection connection = HuskHomes.getConnection()) {
try (PreparedStatement tableUpdateStatement = connection.prepareStatement(
"ALTER TABLE " + HuskHomes.getSettings().getHomesDataTable()
+ " ADD `creation_time` timestamp NULL DEFAULT NULL;")) {
tableUpdateStatement.execute();
plugin.getLogger().info("Database upgrade in progress... (1/2)");
}
} catch (SQLException e) {
plugin.getLogger().info("Skipped performing the database upgrade: " + e.getCause() + ". This might be because another server on your HuskHomes network already carried out the upgrade - in which case you can safely ignore this warning.");
e.printStackTrace();
}
try (PreparedStatement tableUpdateStatement = HuskHomes.getConnection().prepareStatement(
"ALTER TABLE " + HuskHomes.getSettings().getWarpsDataTable()
+ " ADD `creation_time` timestamp NULL DEFAULT NULL;")) {
tableUpdateStatement.execute();
plugin.getLogger().info("Database upgrade in progress... (2/2)");
try (Connection connection = HuskHomes.getConnection()) {
try (PreparedStatement tableUpdateStatement = connection.prepareStatement(
"ALTER TABLE " + HuskHomes.getSettings().getWarpsDataTable()
+ " ADD `creation_time` timestamp NULL DEFAULT NULL;")) {
tableUpdateStatement.execute();
plugin.getLogger().info("Database upgrade in progress... (2/2)");
}
} catch (SQLException e) {
plugin.getLogger().info("Skipped performing the database upgrade: " + e.getCause() + ". This might be because another server on your HuskHomes network already carried out the upgrade - in which case you can safely ignore this warning.");
e.printStackTrace();
@@ -31,9 +31,8 @@ public class SettingHandler {
// Set a home at the specified position
public static void setHome(Location location, Player player, String name) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
SetHomeConditions setHomeConditions = new SetHomeConditions(player, name, connection);
if (setHomeConditions.areConditionsMet()) {
Home home = new Home(location, HuskHomes.getSettings().getServerID(), player, name, false);
@@ -67,9 +66,8 @@ public class SettingHandler {
}
public static void updateCrossServerSpawnWarp(Player p) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (SettingHandler.setCrossServerSpawnWarp(p.getLocation(), p, connection)) {
SettingHandler.setSpawnLocation(p.getLocation());
p.getWorld().setSpawnLocation(p.getLocation());
@@ -112,9 +110,8 @@ public class SettingHandler {
// Set a warp at the specified position
public static void setWarp(Location location, Player player, String name) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
SetWarpConditions setWarpConditions = new SetWarpConditions(name, connection);
if (setWarpConditions.areConditionsMet()) {
Warp warp = new Warp(location, HuskHomes.getSettings().getServerID(), name);
@@ -148,9 +145,8 @@ public class SettingHandler {
// Delete all of a player's homes
public static void deleteAllHomes(Player player) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
int homesDeleted = 0;
for (Home home : DataManager.getPlayerHomes(player.getName(), connection)) {
if (home != null) {
@@ -183,9 +179,8 @@ public class SettingHandler {
return;
}
}
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (DataManager.homeExists(ownerName, homeName, connection)) {
Home home = DataManager.getHome(ownerName, homeName, connection);
if (home != null) {
@@ -245,9 +240,8 @@ public class SettingHandler {
// Delete all server warps
public static void deleteAllWarps(Player player) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
int warpsDeleted = 0;
for (Warp warp : DataManager.getWarps(connection)) {
if (warp != null) {
@@ -277,9 +271,8 @@ public class SettingHandler {
// Delete a warp
public static void deleteWarp(Player player, String warpName) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (DataManager.warpExists(warpName, connection)) {
Warp warp = DataManager.getWarp(warpName, connection);
PlayerDeleteWarpEvent event = new PlayerDeleteWarpEvent(player, warp);
@@ -51,9 +51,8 @@ public class TeleportManager {
}
public static void teleportPlayer(Player p) {
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
TeleportationPoint teleportationPoint = DataManager.getPlayerDestination(p, connection);
if (teleportationPoint != null) {
String server = teleportationPoint.getServer();
@@ -107,9 +107,8 @@ public class TeleportRequestHandler {
TeleportRequest.RequestType requestType = teleportRequest.getRequestType();
Player requester = Bukkit.getPlayer(requesterName);
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
if (requester != null) {
if (accepted) {
MessageManager.sendMessage(p, "tpa_you_accepted", requesterName);
@@ -89,9 +89,8 @@ public class TimedTeleport {
i[0] = i[0] -1;
if (i[0] == 0) {
cancel();
Connection connection = HuskHomes.getConnection();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
try (Connection connection = HuskHomes.getConnection()) {
// Execute the teleport
switch (getTargetType()) {
case POINT -> TeleportManager.teleportPlayer(player, targetPoint, connection);
+1 -1
View File
@@ -5,7 +5,7 @@ api-version: 1.16
authors: [William278]
softdepend: [dynmap, Vault, BlueMap, Pl3xMap]
description: A powerful, intuitive and flexible teleportation suite
libraries: [mysql:mysql-connector-java:8.0.25] # todo test removing this
libraries: [com.zaxxer:HikariCP:5.0.0]
commands:
home: