From b3fd814c0cba21ce69ea1b25b7733e8095953232 Mon Sep 17 00:00:00 2001 From: BuildTools Date: Wed, 26 May 2021 17:22:40 +0100 Subject: [PATCH] Major SQL & Plugin Message refactoring --- .../huskhomes2/CrossServerListHandler.java | 7 +- .../me/william278/huskhomes2/HuskHomes.java | 46 +- .../huskhomes2/PluginMessageHandler.java | 315 ----- .../huskhomes2/config/Settings.java | 10 +- .../huskhomes2/data/DataManager.java | 1025 +++++++++-------- .../william278/huskhomes2/data/Database.java | 511 -------- .../me/william278/huskhomes2/data/SQL.java | 114 -- .../huskhomes2/data/SQL/Database.java | 61 + .../william278/huskhomes2/data/SQL/MySQL.java | 112 ++ .../huskhomes2/data/SQL/SQLite.java | 116 ++ .../data/pluginmessage/PluginMessage.java | 154 +++ .../data/pluginmessage/PluginMessageType.java | 14 + .../huskhomes2/listeners/PlayerListener.java | 7 +- .../listeners/PluginMessageListener.java | 133 +++ .../huskhomes2/teleport/TeleportManager.java | 11 +- .../huskhomes2/teleport/TeleportRequest.java | 17 +- .../teleport/TeleportRequestHandler.java | 43 +- src/main/resources/config.yml | 1 + 18 files changed, 1245 insertions(+), 1452 deletions(-) delete mode 100644 src/main/java/me/william278/huskhomes2/PluginMessageHandler.java delete mode 100644 src/main/java/me/william278/huskhomes2/data/Database.java delete mode 100644 src/main/java/me/william278/huskhomes2/data/SQL.java create mode 100644 src/main/java/me/william278/huskhomes2/data/SQL/Database.java create mode 100644 src/main/java/me/william278/huskhomes2/data/SQL/MySQL.java create mode 100644 src/main/java/me/william278/huskhomes2/data/SQL/SQLite.java create mode 100644 src/main/java/me/william278/huskhomes2/data/pluginmessage/PluginMessage.java create mode 100644 src/main/java/me/william278/huskhomes2/data/pluginmessage/PluginMessageType.java create mode 100644 src/main/java/me/william278/huskhomes2/listeners/PluginMessageListener.java diff --git a/src/main/java/me/william278/huskhomes2/CrossServerListHandler.java b/src/main/java/me/william278/huskhomes2/CrossServerListHandler.java index 65e59752..93d6e5f7 100644 --- a/src/main/java/me/william278/huskhomes2/CrossServerListHandler.java +++ b/src/main/java/me/william278/huskhomes2/CrossServerListHandler.java @@ -1,8 +1,5 @@ package me.william278.huskhomes2; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - import java.util.HashMap; import java.util.HashSet; @@ -24,7 +21,7 @@ public class CrossServerListHandler { playerList.put(server, players); } - public static void updatePlayerList(Player p) { + /*public static void updatePlayerList(Player p) { playerList.clear(); if (p == null) { for (Player x : Bukkit.getOnlinePlayers()) { @@ -34,5 +31,5 @@ public class CrossServerListHandler { if (p != null) { PluginMessageHandler.requestPlayerLists(p); } - } + }*/ } diff --git a/src/main/java/me/william278/huskhomes2/HuskHomes.java b/src/main/java/me/william278/huskhomes2/HuskHomes.java index 1db6c4b4..42e7b6cb 100644 --- a/src/main/java/me/william278/huskhomes2/HuskHomes.java +++ b/src/main/java/me/william278/huskhomes2/HuskHomes.java @@ -26,10 +26,13 @@ import me.william278.huskhomes2.commands.TphereCommand; import me.william278.huskhomes2.commands.WarpCommand; import me.william278.huskhomes2.commands.WarplistCommand; import me.william278.huskhomes2.config.Settings; -import me.william278.huskhomes2.data.DataManager; +import me.william278.huskhomes2.data.SQL.Database; +import me.william278.huskhomes2.data.SQL.MySQL; +import me.william278.huskhomes2.data.SQL.SQLite; import me.william278.huskhomes2.integrations.DynMapIntegration; import me.william278.huskhomes2.integrations.VaultIntegration; import me.william278.huskhomes2.listeners.PlayerListener; +import me.william278.huskhomes2.listeners.PluginMessageListener; import me.william278.huskhomes2.migrators.LegacyMigrator; import me.william278.huskhomes2.teleport.SettingHandler; import me.william278.huskhomes2.teleport.TeleportRequestHandler; @@ -42,23 +45,30 @@ import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; +import java.sql.Connection; +import java.util.logging.Level; public final class HuskHomes extends JavaPlugin { + // Instance getting private static HuskHomes instance; - - // TODO Remove public static HuskHomes getInstance() { return instance; } - private static Settings settings; + // Database handling + private static Database database; + public static Connection getConnection() { + return database.getConnection(); + } - // TODO Remove + // Settings data + private static Settings settings; public static Settings getSettings() { return settings; } + /** * Returns the HuskHomes API * @return an instance of the HuskHomes API @@ -73,9 +83,29 @@ public final class HuskHomes extends JavaPlugin { Bukkit.getPluginManager().disablePlugin(instance); } + // Initialise the database + private void initializeDatabase() { + String dataStorageType = HuskHomes.getSettings().getDatabaseType().toLowerCase(); + switch (dataStorageType) { + case "mysql": + database = new MySQL(getInstance()); + database.load(); + break; + case "sqlite": + database = new SQLite(getInstance()); + database.load(); + break; + default: + getLogger().log(Level.WARNING, "An invalid data storage type was specified in config.yml; defaulting to SQLite"); + database = new SQLite(getInstance()); + database.load(); + break; + } + } + private void setupBungeeChannels() { Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new PluginMessageHandler()); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new PluginMessageListener()); } private void registerCommands() { @@ -157,8 +187,8 @@ public final class HuskHomes extends JavaPlugin { // Fetch spawn location if set SettingHandler.fetchSpawnLocation(); - // Set up data storage - DataManager.setupStorage(); + // Initialize the database + initializeDatabase(); // MIGRATION: Migrate SQL data if (LegacyMigrator.isCanMigrate()) { diff --git a/src/main/java/me/william278/huskhomes2/PluginMessageHandler.java b/src/main/java/me/william278/huskhomes2/PluginMessageHandler.java deleted file mode 100644 index 3f453f33..00000000 --- a/src/main/java/me/william278/huskhomes2/PluginMessageHandler.java +++ /dev/null @@ -1,315 +0,0 @@ -package me.william278.huskhomes2; - -import com.google.common.io.ByteArrayDataInput; -import com.google.common.io.ByteArrayDataOutput; -import com.google.common.io.ByteStreams; -import me.william278.huskhomes2.data.DataManager; -import me.william278.huskhomes2.integrations.VanishChecker; -import me.william278.huskhomes2.teleport.TeleportManager; -import me.william278.huskhomes2.teleport.TeleportRequest; -import me.william278.huskhomes2.teleport.TeleportRequestHandler; -import me.william278.huskhomes2.teleport.points.TeleportationPoint; -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.messaging.PluginMessageListener; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.HashSet; - -public class PluginMessageHandler implements PluginMessageListener { - - private static final HuskHomes plugin = HuskHomes.getInstance(); - - // Move a player to a different server in the bungee network - public static void sendPlayer(Player p, String targetServer) { - ByteArrayDataOutput out = ByteStreams.newDataOutput(); - out.writeUTF("Connect"); - out.writeUTF(targetServer); - p.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); - } - - // Send a plugin message (to a specific player) - public static void sendPluginMessage(Player sender, String targetPlayerName, String messageType, String messageData) { - ByteArrayDataOutput out = ByteStreams.newDataOutput(); - int clusterID = HuskHomes.getSettings().getServerClusterID(); - - // Send a plugin message to the specified player name - out.writeUTF("ForwardToPlayer"); - out.writeUTF(targetPlayerName); - - // Send the HuskHomes message with a specific type - out.writeUTF("HuskHomes:" + clusterID + ":" + messageType); - ByteArrayOutputStream messageBytes = new ByteArrayOutputStream(); - DataOutputStream messageOut = new DataOutputStream(messageBytes); - - // Send the message data; output an exception if there's an error - try { - messageOut.writeUTF(messageData); - } catch (IOException e) { - Bukkit.getLogger().warning("An error occurred trying to send a plugin message (" + e.getCause() + ")"); - e.printStackTrace(); - } - - // Write the messages to the output packet - out.writeShort(messageBytes.toByteArray().length); - out.write(messageBytes.toByteArray()); - - // Send the constructed plugin message packet - sender.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); - } - - // Sends a plugin message request asking for all the player lists on servers - public static void requestPlayerLists(Player sender) { - ByteArrayDataOutput out = ByteStreams.newDataOutput(); - int clusterID = HuskHomes.getSettings().getServerClusterID(); - - // Send a plugin message to the specified player name - out.writeUTF("Forward"); - out.writeUTF("ONLINE"); - - // Send the HuskHomes message with a specific type - out.writeUTF("HuskHomes:" + clusterID + ":get_online_players"); - ByteArrayOutputStream messageBytes = new ByteArrayOutputStream(); - DataOutputStream messageOut = new DataOutputStream(messageBytes); - - // Send the message data; output an exception if there's an error - try { - messageOut.writeUTF(HuskHomes.getSettings().getServerID()); - } catch (IOException e) { - Bukkit.getLogger().warning("An error occurred trying to send a plugin message (" + e.getCause() + ")"); - e.printStackTrace(); - } - - // Write the messages to the output packet - out.writeShort(messageBytes.toByteArray().length); - out.write(messageBytes.toByteArray()); - - // Send the constructed plugin message packet - if (sender == null) { - for (Player p : Bukkit.getOnlinePlayers()) { - sender = p; - break; - } - if (sender == null) { - return; - } - } - sender.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); - } - - // Sends a plugin message informing other servers the player list needs updating - public static void broadcastPlayerChange(Player sender) { - ByteArrayDataOutput out = ByteStreams.newDataOutput(); - int clusterID = HuskHomes.getSettings().getServerClusterID(); - - // Send a plugin message to the specified player name - out.writeUTF("Forward"); - out.writeUTF("ONLINE"); - - // Send the HuskHomes message with a specific type - out.writeUTF("HuskHomes:" + clusterID + ":player_change"); - ByteArrayOutputStream messageBytes = new ByteArrayOutputStream(); - DataOutputStream messageOut = new DataOutputStream(messageBytes); - - // Send the message data; output an exception if there's an error - try { - messageOut.writeUTF(HuskHomes.getSettings().getServerID()); - } catch (IOException e) { - Bukkit.getLogger().warning("An error occurred trying to send a plugin message (" + e.getCause() + ")"); - e.printStackTrace(); - } - - // Write the messages to the output packet - out.writeShort(messageBytes.toByteArray().length); - out.write(messageBytes.toByteArray()); - - // Send the constructed plugin message packet - if (sender == null) { - for (Player p : Bukkit.getOnlinePlayers()) { - sender = p; - break; - } - if (sender == null) { - return; - } - } - sender.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); - } - - // Sends a plugin message with player list - public static void returnPlayerList(String returnTo, Player sender) { - ByteArrayDataOutput out = ByteStreams.newDataOutput(); - int clusterID = HuskHomes.getSettings().getServerClusterID(); - - // Send a plugin message to the specified player name - out.writeUTF("Forward"); - if (returnTo == null) { - returnTo = "ONLINE"; - } - out.writeUTF(returnTo); - - // Send the HuskHomes message with a specific type - out.writeUTF("HuskHomes:" + clusterID + ":return_online_players"); - ByteArrayOutputStream messageBytes = new ByteArrayOutputStream(); - DataOutputStream messageOut = new DataOutputStream(messageBytes); - - // Send the message data; output an exception if there's an error - try { - StringBuilder playerList = new StringBuilder(); - for (Player p : Bukkit.getOnlinePlayers()) { - if (!VanishChecker.isVanished(p)) { - playerList.append(p.getName()).append(","); - } - } - if (!playerList.toString().isEmpty()) { - messageOut.writeUTF(HuskHomes.getSettings().getServerID() + "/" + StringUtils.removeEnd(playerList.toString(), ",")); - } - } catch (IOException e) { - Bukkit.getLogger().warning("An error occurred trying to send a plugin message (" + e.getCause() + ")"); - e.printStackTrace(); - } - - // Write the messages to the output packet - out.writeShort(messageBytes.toByteArray().length); - out.write(messageBytes.toByteArray()); - - // Send the constructed plugin message packet - if (sender == null) { - for (Player p : Bukkit.getOnlinePlayers()) { - sender = p; - break; - } - } - sender.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); - } - - // When a plugin message is received - @Override - public void onPluginMessageReceived(String channel, Player recipient, byte[] message) { - // Return if the message is not a Bungee message - if (!channel.equals("BungeeCord")) { - return; - } - ByteArrayDataInput input = ByteStreams.newDataInput(message); - - // Plugin messages are formatted as such: - // HuskHomes::, followed by the message arguments and data. - String messageType = input.readUTF(); - int clusterID; - - // Return if the message was not sent by HuskHomes - if (!messageType.contains("HuskHomes:")) { - return; - } - - // Ensure the cluster ID matches - try { - clusterID = Integer.parseInt(messageType.split(":")[1]); - } catch (Exception e) { - // In case the message is malformed or the cluster ID is invalid - Bukkit.getLogger().warning("Received a HuskHomes plugin message with an invalid server cluster ID! \n" + - "Please ensure you are running the latest version of HuskHomes on all your servers and that the cluster ID is set to a valid integer on all of them."); - return; - } - if (HuskHomes.getSettings().getServerClusterID() != clusterID) { - return; - } - - // Get the HuskHomes message type - messageType = messageType.split(":")[2]; - - // Get the message data packets - String messageData = ""; - short messageLength = input.readShort(); - byte[] messageBytes = new byte[messageLength]; - input.readFully(messageBytes); - DataInputStream messageIn = new DataInputStream(new ByteArrayInputStream(messageBytes)); - - // Get the message data string from the packets received - try { - messageData = messageIn.readUTF(); - } catch (IOException e) { - Bukkit.getLogger().warning("An error occurred trying to read a plugin message (" + e.getCause() + ")"); - e.printStackTrace(); - } - - // Used in replying to tp requests - String replierName; - boolean accepted; - - // Respond to different cross-server requests - switch (messageType) { - case "set_tp_destination": - setTeleportDestination(messageData, recipient); - PluginMessageHandler.sendPluginMessage(recipient, messageData, "confirm_destination_set", "confirmed"); - break; - case "confirm_destination_set": - if (messageData.equals("confirmed")) { - TeleportManager.teleportPlayer(recipient); - } - break; - case "tpa_request": - if (!VanishChecker.isVanished(recipient)) { - TeleportRequestHandler.teleportRequests.put(recipient, new TeleportRequest(messageData, "tpa")); - MessageManager.sendMessage(recipient, "tpa_request_ask", messageData); - TeleportRequestHandler.sendTpAcceptDenyButtons(recipient); - } - break; - case "tpahere_request": - if (!VanishChecker.isVanished(recipient)) { - TeleportRequestHandler.teleportRequests.put(recipient, new TeleportRequest(messageData, "tpahere")); - MessageManager.sendMessage(recipient, "tpahere_request_ask", messageData); - TeleportRequestHandler.sendTpAcceptDenyButtons(recipient); - } - break; - case "tpa_request_reply": - replierName = messageData.split(":")[0]; - accepted = Boolean.parseBoolean(messageData.split(":")[1]); - if (accepted) { - MessageManager.sendMessage(recipient, "tpa_has_accepted", replierName); - TeleportManager.queueTimedTeleport(recipient, replierName); - } else { - MessageManager.sendMessage(recipient, "tpa_has_declined", replierName); - } - break; - case "tpahere_request_reply": - replierName = messageData.split(":")[0]; - accepted = Boolean.parseBoolean(messageData.split(":")[1]); - if (accepted) { - MessageManager.sendMessage(recipient, "tpa_has_accepted", replierName); - } else { - MessageManager.sendMessage(recipient, "tpa_has_declined", replierName); - } - break; - case "teleport_to_me": - TeleportManager.teleportPlayer(recipient, messageData); - break; - case "get_online_players": - if (Bukkit.getOnlinePlayers().size() > 0) { - returnPlayerList(messageData, recipient); - } - break; - case "return_online_players": - String server = messageData.split("/")[0]; - String players = messageData.split("/")[1]; - HashSet playerList = new HashSet<>(Arrays.asList(players.split(","))); - CrossServerListHandler.updateHashset(server, playerList); - break; - case "player_change": - CrossServerListHandler.updatePlayerList(null); - break; - } - } - - // Set the requesters' teleport destination to a teleportation point of the recipient's current location - public void setTeleportDestination(String requesterName, Player recipient) { - DataManager.setPlayerDestinationLocation(requesterName, - new TeleportationPoint(recipient.getLocation(), HuskHomes.getSettings().getServerID())); - } -} diff --git a/src/main/java/me/william278/huskhomes2/config/Settings.java b/src/main/java/me/william278/huskhomes2/config/Settings.java index fe5f5fed..98b2075f 100644 --- a/src/main/java/me/william278/huskhomes2/config/Settings.java +++ b/src/main/java/me/william278/huskhomes2/config/Settings.java @@ -37,6 +37,7 @@ public class Settings { private String mySQLdatabase; private String mySQLusername; private String mySQLpassword; + private String mySQLparams; // Dynmap integration settings private boolean doDynmap; @@ -130,6 +131,7 @@ public class Settings { this.mySQLusername = config.getString("data_storage_options.mysql_credentials.username"); this.mySQLpassword = config.getString("data_storage_options.mysql_credentials.password"); this.mySQLport = config.getInt("data_storage_options.mysql_credentials.port"); + this.mySQLparams = config.getString("data_storage_options.mysql_credentials.params"); this.doDynmap = config.getBoolean("dynmap_integration.enabled"); @@ -241,7 +243,7 @@ public class Settings { return teleportWarmupTime; } - public String getStorageType() { + public String getDatabaseType() { return storageType; } @@ -257,7 +259,7 @@ public class Settings { return server; } - public int getServerClusterID() { return clusterID; } + public int getClusterID() { return clusterID; } public boolean doBungee() { return doBungee; @@ -319,6 +321,10 @@ public class Settings { return mySQLpassword; } + public String getMySQLparams() { + return mySQLparams; + } + public boolean doSpawnCommand() { return doSpawnCommand; } diff --git a/src/main/java/me/william278/huskhomes2/data/DataManager.java b/src/main/java/me/william278/huskhomes2/data/DataManager.java index 737acaf2..c9eecc8d 100644 --- a/src/main/java/me/william278/huskhomes2/data/DataManager.java +++ b/src/main/java/me/william278/huskhomes2/data/DataManager.java @@ -8,217 +8,144 @@ import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.logging.Level; -/* - TODO Should not be an utility class for SQL class - Instead of doing everything here, all methods should be moved into corresponding classes - - */ -// This class handles the saving of data; whether that be through SQLite or mySQL public class DataManager { - // Syntax for creating tables; changes based on storage medium - public static String createPlayerTable = ""; - - public static String createLocationsTable = ""; - - public static final String createHomesTable = "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getHomesDataTable() + " (" + - "`player_id` integer NOT NULL," + - "`location_id` integer NOT NULL," + - "`name` varchar(16) NOT NULL," + - "`description` varchar(255) NOT NULL," + - "`public` boolean NOT NULL," + - "PRIMARY KEY (`player_id`, `name`)," + - "FOREIGN KEY (`player_id`) REFERENCES " + HuskHomes.getSettings().getPlayerDataTable() + " (`player_id`) ON DELETE CASCADE ON UPDATE NO ACTION," + - "FOREIGN KEY (`location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + - ");"; - - public static final String createWarpsTable = "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getWarpsDataTable() + " (" + - "`location_id` integer NOT NULL," + - "`name` varchar(16) NOT NULL UNIQUE," + - "`description` varchar(255) NOT NULL," + - "PRIMARY KEY (`location_id`)," + - "FOREIGN KEY (`location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + - ");"; - private static final HuskHomes plugin = HuskHomes.getInstance(); - private static Database database; - private static Connection getConnection() { - return database.getSQLConnection(); - } - - private static void initializeDatabase() { - database = new SQL(HuskHomes.getInstance()); - database.load(); + return HuskHomes.getConnection(); } // Return a player's ID from their UUID - private static Integer getPlayerId(UUID playerUUID) { - Connection conn; + private static Integer getPlayerId(UUID uuid, Connection connection) throws SQLException { PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `user_uuid`=?;"); - ps.setString(1, playerUUID.toString()); - rs = ps.executeQuery(); - if (rs != null) { - if (rs.next()) { - return rs.getInt("player_id"); - } else { - return null; - } - } else { - return null; // If the player doesn't exist, playerID will be null + ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `user_uuid`=?;"); + ps.setString(1, uuid.toString()); + rs = ps.executeQuery(); + if (rs != null) { + if (rs.next()) { + final int playerID = rs.getInt("player_id"); + ps.close(); + return playerID; } - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); } + ps.close(); return null; } // Return a player's ID from their username - private static Integer getPlayerId(String playerUsername) { - Connection conn; + private static Integer getPlayerId(String playerUsername, Connection connection) throws SQLException { PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?;"); - ps.setString(1, playerUsername); - rs = ps.executeQuery(); - if (rs != null) { - if (rs.next()) { - return rs.getInt("player_id"); - } else { - return null; - } - } else { - return null; // If the player doesn't exist, playerID will be null + ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?;"); + ps.setString(1, playerUsername); + rs = ps.executeQuery(); + if (rs != null) { + if (rs.next()) { + final int returnable = rs.getInt("player_id"); + ps.close(); + return returnable; } - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); } + ps.close(); return null; } // Return an integer from the player table from a player ID - public static Integer getPlayerInteger(Integer playerID, String column) { - Connection conn; + public static Integer getPlayerInteger(Integer playerID, String column, Connection connection) throws SQLException { PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `player_id`=?;"); - ps.setInt(1, playerID); - rs = ps.executeQuery(); - if (rs != null) { - if (rs.next()) { - return rs.getInt(column); - } else { - return null; - } - } else { - Bukkit.getLogger().severe("Result set for a player returned null; perhaps player ID was null"); - return null; + ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `player_id`=?;"); + ps.setInt(1, playerID); + rs = ps.executeQuery(); + if (rs != null) { + if (rs.next()) { + final int returnable = rs.getInt(column); + ps.close(); + return returnable; } - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); } + ps.close(); return null; } - // Return an integer from the player table from a player name - public static Integer getPlayerInteger(String playerName, String column) { - return getPlayerInteger(getPlayerId(playerName), column); - } - // Return an integer from the player table from a player object - public static Integer getPlayerInteger(Player p, String column) { - return getPlayerInteger(getPlayerId(p.getUniqueId()), column); + public static Integer getPlayerInteger(Player p, String column, Connection connection) throws SQLException { + return getPlayerInteger(getPlayerId(p.getUniqueId(), connection), column, connection); + } + + // Return an integer from the player table from a player object + public static Integer getPlayerInteger(String username, String column, Connection connection) throws SQLException { + return getPlayerInteger(getPlayerId(username, connection), column, connection); } // Return an integer from the player table from a player ID - public static String getPlayerString(Integer playerID, String column) { - Connection conn; + public static String getPlayerString(Integer playerID, String column, Connection connection) throws SQLException { PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `player_id`=?;"); - ps.setInt(1, playerID); - rs = ps.executeQuery(); - if (rs != null) { - if (rs.next()) { - return rs.getString(column); - } else { - return null; - } + ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `player_id`=?;"); + ps.setInt(1, playerID); + rs = ps.executeQuery(); + if (rs != null) { + if (rs.next()) { + return rs.getString(column); } else { - Bukkit.getLogger().severe("Result set for a player returned null; perhaps player ID was null"); return null; } - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); + } else { + Bukkit.getLogger().severe("Result set for a player returned null; perhaps player ID was null"); + return null; } - return null; + } // Return if the player is teleporting - public static Boolean getPlayerTeleporting(Player p) { + public static Boolean getPlayerTeleporting(Player p) throws SQLException { Connection conn; PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `user_uuid`=?;"); - ps.setString(1, p.getUniqueId().toString()); - rs = ps.executeQuery(); - if (rs != null) { - if (rs.next()) { - return rs.getBoolean("is_teleporting"); - } else { - return null; - } + conn = getConnection(); + ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `user_uuid`=?;"); + ps.setString(1, p.getUniqueId().toString()); + rs = ps.executeQuery(); + if (rs != null) { + if (rs.next()) { + return rs.getBoolean("is_teleporting"); } else { - Bukkit.getLogger().severe("Failed to retrieve if player was teleporting"); return null; } - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); + } else { + Bukkit.getLogger().severe("Failed to retrieve if player was teleporting"); + return null; } - return null; } // Return a player's UUID - public static String getPlayerUUID(int playerID) { - return getPlayerString(playerID, "user_uuid"); + public static String getPlayerUUID(int playerID, Connection connection) throws SQLException { + return getPlayerString(playerID, "user_uuid", connection); } // Return a player's username - public static String getPlayerUsername(int playerID) { - return getPlayerString(playerID, "username"); + public static String getPlayerUsername(int playerID, Connection connection) throws SQLException { + return getPlayerString(playerID, "username", connection); } // Return how many homes the player has set - public static int getPlayerHomeCount(Player p) { - List playerHomes = getPlayerHomes(p.getName()); + public static int getPlayerHomeCount(Player p, Connection connection) throws SQLException { + List playerHomes = getPlayerHomes(p.getName(), connection); if (playerHomes != null) { return playerHomes.size(); } else { @@ -227,264 +154,410 @@ public class DataManager { } // Increment the number of home slots a player has - public static void incrementPlayerHomeSlots(Player p) { - setPlayerHomeSlots(p, (getPlayerHomeSlots(p)+1)); - } - - // Set how many home slots a player has - private static void setPlayerHomeSlots(Player p, int slots) { - database.setPlayerHomeSlots(p.getUniqueId(), slots); + public static void incrementPlayerHomeSlots(Player p, Connection connection) throws SQLException { + setPlayerHomeSlots(p.getUniqueId(), (getPlayerHomeSlots(p, connection) + 1), connection); } // Return how many home slots a player has - public static Integer getPlayerHomeSlots(Player p) { - return getPlayerInteger(p, "home_slots"); + public static Integer getPlayerHomeSlots(Player p, Connection connection) throws SQLException { + return getPlayerInteger(p, "home_slots", connection); } // Return how many home slots a player has - public static Long getPlayerRtpCooldown(Player p) { - return (long) getPlayerInteger(p, "rtp_cooldown"); + public static Long getPlayerRtpCooldown(Player p, Connection connection) throws SQLException { + return (long) getPlayerInteger(p, "rtp_cooldown", connection); } // Return a player's homes. - public static List getPlayerHomes(String playerName) { - Connection conn; + public static List getPlayerHomes(String playerName, Connection connection) throws SQLException { PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getHomesDataTable() + " WHERE `player_id`=(SELECT `player_id` FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?);"); - ps.setString(1, playerName); - rs = ps.executeQuery(); - if (rs != null) { - List playerHomes = new ArrayList<>(); - while (rs.next()) { - int locationID = rs.getInt("location_id"); - TeleportationPoint teleportationPoint = getTeleportationPoint(locationID); - if (teleportationPoint != null) { - playerHomes.add(new Home(teleportationPoint, - playerName, getPlayerUUID(rs.getInt("player_id")), - rs.getString("name"), - rs.getString("description"), - rs.getBoolean("public"))); - } - } - return playerHomes; - } else { - Bukkit.getLogger().severe("Result set of a player's homes returned null; perhaps player ID was null"); - return null; + ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getHomesDataTable() + " WHERE `player_id`=(SELECT `player_id` FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?);"); + ps.setString(1, playerName); + rs = ps.executeQuery(); + if (rs != null) { + final List playerHomes = new ArrayList<>(); + while (rs.next()) { + int locationID = rs.getInt("location_id"); + TeleportationPoint teleportationPoint = getTeleportationPoint(locationID, connection); + playerHomes.add(new Home(teleportationPoint, + playerName, getPlayerUUID(rs.getInt("player_id"), connection), + rs.getString("name"), + rs.getString("description"), + rs.getBoolean("public"))); } - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); + ps.close(); + return playerHomes; } + ps.close(); return null; } // Return all the public homes - public static List getPublicHomes() { - Connection conn; + public static List getPublicHomes(Connection connection) throws SQLException { PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getHomesDataTable() + " WHERE `public`;"); - rs = ps.executeQuery(); - if (rs != null) { - List publicHomes = new ArrayList<>(); - while (rs.next()) { - int playerID = rs.getInt("player_id"); - int locationID = rs.getInt("location_id"); - TeleportationPoint teleportationPoint = getTeleportationPoint(locationID); - if (teleportationPoint != null) { - publicHomes.add(new Home(teleportationPoint, getPlayerUsername(playerID), getPlayerUUID(playerID), rs.getString("name"), rs.getString("description"), true)); - } - } - return publicHomes; - } else { - Bukkit.getLogger().severe("Result set of public returns returned null!"); - return null; + ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getHomesDataTable() + " WHERE `public`;"); + rs = ps.executeQuery(); + if (rs != null) { + final List publicHomes = new ArrayList<>(); + while (rs.next()) { + int playerID = rs.getInt("player_id"); + int locationID = rs.getInt("location_id"); + TeleportationPoint teleportationPoint = getTeleportationPoint(locationID, connection); + publicHomes.add(new Home(teleportationPoint, getPlayerUsername(playerID, connection), + getPlayerUUID(playerID, connection), rs.getString("name"), + rs.getString("description"), true)); } - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); + ps.close(); + return publicHomes; } + ps.close(); return null; } // Return an array of all the warps - public static List getWarps() { - Connection conn; + public static List getWarps(Connection connection) throws SQLException { PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getWarpsDataTable() + ";"); - rs = ps.executeQuery(); - List warps = new ArrayList<>(); - if (rs != null) { - while (rs.next()) { - int locationID = rs.getInt("location_id"); - TeleportationPoint teleportationPoint = getTeleportationPoint(locationID); - if (teleportationPoint != null) { - warps.add(new Warp(teleportationPoint, - rs.getString("name"), - rs.getString("description"))); - } - } - } else { - Bukkit.getLogger().severe("Result set of warps returned null!"); + ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getWarpsDataTable() + ";"); + rs = ps.executeQuery(); + final List warps = new ArrayList<>(); + if (rs != null) { + while (rs.next()) { + int locationID = rs.getInt("location_id"); + TeleportationPoint teleportationPoint = getTeleportationPoint(locationID, connection); + warps.add(new Warp(teleportationPoint, + rs.getString("name"), + rs.getString("description"))); } - return warps; - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); + } else { + Bukkit.getLogger().severe("Result set of warps returned null!"); } - return null; + ps.close(); + return warps; } // Return a warp with a given name (warp names are unique) - public static Warp getWarp(String name) { - Connection conn; + public static Warp getWarp(String name, Connection connection) throws SQLException { PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getWarpsDataTable() + " WHERE `name`=?;"); - ps.setString(1, name); - rs = ps.executeQuery(); - if (rs != null) { - if (rs.next()) { - int locationID = rs.getInt("location_id"); - TeleportationPoint teleportationPoint = getTeleportationPoint(locationID); - if (teleportationPoint != null) { - return new Warp(teleportationPoint, - rs.getString("name"), - rs.getString("description")); - } else { - Bukkit.getLogger().severe("An error occurred returning a warp from the table!"); - return null; - } - } - } else { - Bukkit.getLogger().severe("Warp returned null!"); - return null; + ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getWarpsDataTable() + " WHERE `name`=?;"); + ps.setString(1, name); + rs = ps.executeQuery(); + if (rs != null) { + if (rs.next()) { + int locationID = rs.getInt("location_id"); + TeleportationPoint teleportationPoint = getTeleportationPoint(locationID, connection); + return new Warp(teleportationPoint, + rs.getString("name"), + rs.getString("description")); } - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); } + ps.close(); return null; } // Obtain the teleportation location ID from a home - public static Integer getHomeLocationID(int ownerID, String homeName) { - Connection conn; + public static Integer getHomeLocationID(int ownerID, String homeName, Connection connection) throws SQLException { PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getHomesDataTable() + " WHERE `player_id`=? AND `name`=?;"); - ps.setInt(1, ownerID); - ps.setString(2, homeName); - rs = ps.executeQuery(); - if (rs != null) { - if (rs.next()) { - return rs.getInt("location_id"); - } - } else { - Bukkit.getLogger().severe("Failed to obtain home teleportation location ID"); + ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getHomesDataTable() + " WHERE `player_id`=? AND `name`=?;"); + ps.setInt(1, ownerID); + ps.setString(2, homeName); + rs = ps.executeQuery(); + if (rs != null) { + if (rs.next()) { + final int locationID = rs.getInt("location_id"); + ps.close(); + return locationID; } - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); + } else { + Bukkit.getLogger().severe("Failed to obtain home teleportation location ID"); } + ps.close(); return null; } // Delete a home's corresponding home teleport location - public static void deleteHomeTeleportLocation(int ownerID, String homeName) { - Integer locationID = getHomeLocationID(ownerID, homeName); - database.deleteTeleportationPoint(locationID); + public static void deleteHomeTeleportLocation(int ownerID, String homeName, Connection connection) throws SQLException { + Integer locationID = getHomeLocationID(ownerID, homeName, connection); + deleteTeleportationPoint(locationID, connection); } // Update a home's teleport location (deletion of the old one is done afterward to prevent cascading deletion from wiping the home - public static void updateHomeTeleportLocation(int ownerID, String homeName, TeleportationPoint teleportationPoint) { - Integer oldLocationID = getHomeLocationID(ownerID, homeName); - database.setHomeTeleportPoint(homeName, ownerID, teleportationPoint); - database.deleteTeleportationPoint(oldLocationID); + public static void updateHomeTeleportLocation(int ownerID, String homeName, TeleportationPoint teleportationPoint, Connection connection) throws SQLException { + Integer oldLocationID = getHomeLocationID(ownerID, homeName, connection); + setHomeTeleportPoint(homeName, ownerID, teleportationPoint, connection); + deleteTeleportationPoint(oldLocationID, connection); } // Get the ID of the teleportation point of the warp - public static Integer getWarpLocationID(String warpName) { - Connection conn; + public static Integer getWarpLocationID(String warpName, Connection connection) throws SQLException { PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getWarpsDataTable() + " WHERE `name`=?;"); - ps.setString(1, warpName); - rs = ps.executeQuery(); - if (rs != null) { - if (rs.next()) { - int locationID = rs.getInt("location_id"); - return locationID; - } - } else { - Bukkit.getLogger().severe("Failed to obtain warp teleportation location ID"); + ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getWarpsDataTable() + " WHERE `name`=?;"); + ps.setString(1, warpName); + rs = ps.executeQuery(); + if (rs != null) { + if (rs.next()) { + int locationID = rs.getInt("location_id"); + return locationID; } - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); + } else { + Bukkit.getLogger().severe("Failed to obtain warp teleportation location ID"); } + ps.close(); return null; } + // Delete a warp + public static void deleteWarp(String warpName, Connection connection) throws SQLException { + Integer warpLocationID = getWarpLocationID(warpName, connection); + deleteTeleportationPoint(warpLocationID, connection); + + PreparedStatement ps; + // Delete the warp with the given name + ps = connection.prepareStatement("DELETE FROM " + HuskHomes.getSettings().getWarpsDataTable() + " WHERE `name`=?;"); + ps.setString(1, warpName); + ps.executeUpdate(); + } + + + public static void deleteHome(String homeName, String ownerUsername, Connection connection) throws SQLException { + PreparedStatement ps; + + // Delete the home with the given name and player ID + ps = connection.prepareStatement("DELETE FROM " + HuskHomes.getSettings().getHomesDataTable() + " WHERE `name`=? AND `player_id`=(SELECT `player_id` FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?);"); + ps.setString(1, homeName); + ps.setString(2, ownerUsername); + ps.executeUpdate(); + ps.close(); + + } + + public static void addPlayer(Player p, Connection connection) throws SQLException { + PreparedStatement ps; + + ps = connection.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getPlayerDataTable() + " (user_uuid,username,home_slots,rtp_cooldown,is_teleporting) VALUES(?,?,?,?,?);"); + ps.setString(1, p.getUniqueId().toString()); + ps.setString(2, p.getName()); + ps.setInt(3, Home.getFreeHomes(p)); + ps.setInt(4, 0); + ps.setBoolean(5, false); + + ps.executeUpdate(); + ps.close(); + } + + // Insert a player into the database + public static void addPlayer(UUID playerUUID, String playerName, Connection connection) throws SQLException { + PreparedStatement ps; + + ps = connection.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getPlayerDataTable() + " (user_uuid,username,home_slots,rtp_cooldown,is_teleporting) VALUES(?,?,?,?,?);"); + ps.setString(1, playerUUID.toString()); + ps.setString(2, playerName); + ps.setInt(3, HuskHomes.getSettings().getFreeHomeSlots()); + ps.setInt(4, 0); + ps.setBoolean(5, false); + + ps.executeUpdate(); + ps.close(); + } + + // Insert a player into the database + public static void addPlayer(UUID playerUUID, String playerName, int homeSlots, Connection connection) throws SQLException { + PreparedStatement ps; + + ps = connection.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getPlayerDataTable() + " (user_uuid,username,home_slots,rtp_cooldown,is_teleporting) VALUES(?,?,?,?,?);"); + ps.setString(1, playerUUID.toString()); + ps.setString(2, playerName); + ps.setInt(3, homeSlots); + ps.setInt(4, 0); + ps.setBoolean(5, false); + + ps.executeUpdate(); + ps.close(); + } + + public static void updatePlayerUsername(UUID uuid, String newName, Connection connection) throws SQLException { + PreparedStatement ps; + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `username`=? WHERE `user_uuid`=?;"); + ps.setString(1, newName); + ps.setString(2, uuid.toString()); + ps.executeUpdate(); + ps.close(); + } + + public static void setPlayerTeleporting(UUID uuid, boolean value, Connection connection) throws SQLException { + PreparedStatement ps; + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `is_teleporting`=? WHERE `user_uuid`=?;"); + ps.setBoolean(1, value); + ps.setString(2, uuid.toString()); + ps.executeUpdate(); + } + + public static void setPlayerHomeSlots(UUID uuid, int newValue, Connection connection) throws SQLException { + PreparedStatement ps; + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `home_slots`=? WHERE `user_uuid`=?;"); + ps.setInt(1, newValue); + ps.setString(2, uuid.toString()); + ps.executeUpdate(); + ps.close(); + } + + public static void setRtpCoolDown(UUID uuid, int newTime, Connection connection) throws SQLException { + PreparedStatement ps; + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `rtp_cooldown`=? WHERE `user_uuid`=?;"); + ps.setInt(1, newTime); + ps.setString(2, uuid.toString()); + ps.executeUpdate(); + ps.close(); + } + + + // Update the location of a home + public static void setHomePrivacy(String homeName, String ownerName, boolean isPublic, Connection connection) throws SQLException { + PreparedStatement ps; + + // Set the home location ID to the new teleport point for the given home + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getHomesDataTable() + " SET `public`=? WHERE `name`=? AND `player_id`=(SELECT `player_id` FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?);"); + ps.setBoolean(1, isPublic); + ps.setString(2, homeName); + ps.setString(3, ownerName); + ps.executeUpdate(); + ps.close(); + } + + + // Update the location of a home + public static void setWarpTeleportPoint(String warpName, TeleportationPoint point, Connection connection) throws SQLException { + PreparedStatement ps; + + // Add the teleportation point + Integer locationID = addTeleportationPoint(point, connection); + + // Set the warp location ID to the new teleport point + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getWarpsDataTable() + " SET `location_id`=? WHERE `name`=?;"); + ps.setInt(1, locationID); + ps.setString(2, warpName); + ps.executeUpdate(); + ps.close(); + } + + // Update the description of a home + public static void setHomeDescription(String homeName, String ownerName, String newDescription, Connection connection) throws SQLException { + PreparedStatement ps; + + // Update the home description + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getHomesDataTable() + " SET `description`=? WHERE `name`=? AND `player_id`=(SELECT `player_id` FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?);"); + ps.setString(1, newDescription); + ps.setString(2, homeName); + ps.setString(3, ownerName); + ps.executeUpdate(); + ps.close(); + } + + // Update the description of a warp + public static void setWarpDescription(String warpName, String newDescription, Connection connection) throws SQLException { + PreparedStatement ps; + + // Update the warp description + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getWarpsDataTable() + " SET `description`=? WHERE `name`=?;"); + ps.setString(1, newDescription); + ps.setString(2, warpName); + ps.executeUpdate(); + ps.close(); + } + + // Update the name of a home + public static void setHomeName(String oldHomeName, String ownerName, String newHomeName, Connection connection) throws SQLException { + PreparedStatement ps; + + // Update the home name + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getHomesDataTable() + " SET `name`=? WHERE `name`=? AND `player_id`=(SELECT `player_id` FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?);"); + ps.setString(1, newHomeName); + ps.setString(2, oldHomeName); + ps.setString(3, ownerName); + + ps.executeUpdate(); + + } + + // Update the name of a warp + public static void setWarpName(String oldWarpName, String newWarpName, Connection connection) throws SQLException { + PreparedStatement ps; + + // Update the warp name + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getWarpsDataTable() + " SET `name`=? WHERE `name`=?;"); + ps.setString(1, newWarpName); + ps.setString(2, oldWarpName); + + ps.executeUpdate(); + ps.close(); + } + + // Update a player's destination teleport point + public static void setTeleportationDestination(String username, TeleportationPoint point, Connection connection) throws SQLException { + PreparedStatement ps; + + // Add the teleportation point + Integer locationID = addTeleportationPoint(point, connection); + + // Set the destination location with the location_id of the last inserted teleport point + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `dest_location_id`=? WHERE `username`=?;"); + ps.setInt(1, locationID); + ps.setString(2, username); + ps.executeUpdate(); + ps.close(); + } + // Update a warp's teleport location (deletion of the old one is done afterward to prevent cascading deletion from wiping the warp - public static void updateWarpTeleportLocation(String warpName, TeleportationPoint teleportationPoint) { - Integer oldLocationID = getWarpLocationID(warpName); - database.setWarpTeleportPoint(warpName, teleportationPoint); - database.deleteTeleportationPoint(oldLocationID); + public static void updateWarpTeleportLocation(String warpName, TeleportationPoint teleportationPoint, Connection connection) throws SQLException { + Integer oldLocationID = getWarpLocationID(warpName, connection); + setWarpTeleportPoint(warpName, teleportationPoint, connection); + deleteTeleportationPoint(oldLocationID, connection); } - public static void deleteWarpTeleportLocation(String warpName) { - Integer locationID = getWarpLocationID(warpName); - database.deleteTeleportationPoint(locationID); + public static void updateHomePrivacy(String ownerName, String homeName, boolean isPublic, Connection connection) throws SQLException { + setHomePrivacy(homeName, ownerName, isPublic, connection); } - public static void updateHomePrivacy(String ownerName, String homeName, boolean isPublic) { - database.setHomePrivacy(homeName, ownerName, isPublic); + public static void updateHomeName(String ownerName, String homeName, String newName, Connection connection) throws SQLException { + setHomeName(homeName, ownerName, newName, connection); } - public static void updateHomeName(String ownerName, String homeName, String newName) { - database.setHomeName(homeName, ownerName, newName); + public static void updateHomeDescription(String ownerName, String homeName, String newDescription, Connection connection) throws SQLException { + setHomeDescription(homeName, ownerName, newDescription, connection); } - public static void updateHomeDescription(String ownerName, String homeName, String newDescription) { - database.setHomeDescription(homeName, ownerName, newDescription); + public static void updateHomeLocation(String ownerName, String homeName, Location newLocation, Connection connection) throws SQLException { + Integer playerID = getPlayerId(ownerName, connection); + updateHomeTeleportLocation(playerID, homeName, + new TeleportationPoint(newLocation, HuskHomes.getSettings().getServerID()), connection); } - public static void updateHomeLocation(String ownerName, String homeName, Location newLocation) { - Integer playerID = getPlayerId(ownerName); - updateHomeTeleportLocation(playerID,homeName, - new TeleportationPoint(newLocation, HuskHomes.getSettings().getServerID())); + public static void updateWarpName(String warpName, String newName, Connection connection) throws SQLException { + setWarpName(warpName, newName, connection); } - public static void updateWarpName(String warpName, String newName) { - database.setWarpName(warpName, newName); + public static void updateWarpDescription(String warpName, String newDescription, Connection connection) throws SQLException { + setWarpDescription(warpName, newDescription, connection); } - public static void updateWarpDescription(String warpName, String newDescription) { - database.setWarpDescription(warpName, newDescription); - } - - public static void updateWarpLocation(String warpName, Location newLocation) { - updateWarpTeleportLocation(warpName, - new TeleportationPoint(newLocation, HuskHomes.getSettings().getServerID())); + public static void updateWarpLocation(String warpName, Location newLocation, Connection connection) throws SQLException { + updateWarpTeleportLocation(warpName, new TeleportationPoint(newLocation, + HuskHomes.getSettings().getServerID()), connection); } // Return a home with a given owner username and home name - public static Home getHome(String ownerUsername, String homeName) { + public static Home getHome(String ownerUsername, String homeName, Connection connection) throws SQLException { Connection conn; PreparedStatement ps; ResultSet rs; @@ -498,18 +571,13 @@ public class DataManager { if (rs != null) { if (rs.next()) { int locationID = rs.getInt("location_id"); - TeleportationPoint teleportationPoint = getTeleportationPoint(locationID); - if (teleportationPoint != null) { - return new Home(teleportationPoint, - ownerUsername, - getPlayerUUID(rs.getInt("player_id")), - rs.getString("name"), - rs.getString("description"), - rs.getBoolean("public")); - } else { - Bukkit.getLogger().severe("An error occurred retrieving a home from the table!"); - return null; - } + TeleportationPoint teleportationPoint = getTeleportationPoint(locationID, connection); + return new Home(teleportationPoint, + ownerUsername, + getPlayerUUID(rs.getInt("player_id"), connection), + rs.getString("name"), + rs.getString("description"), + rs.getBoolean("public")); } } else { Bukkit.getLogger().severe("Home returned null; perhaps player ID was null?"); @@ -597,202 +665,233 @@ public class DataManager { return null; } - public static TeleportationPoint getTeleportationPoint(Integer locationID) { - Connection conn; + public static TeleportationPoint getTeleportationPoint(Integer locationID, Connection connection) throws SQLException, IllegalArgumentException { PreparedStatement ps; ResultSet rs; - try { - conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getLocationsDataTable() + " WHERE `location_id`=?;"); - ps.setInt(1, locationID); - rs = ps.executeQuery(); - if (rs.next()) { - return new TeleportationPoint(rs.getString("world"), - rs.getDouble("x"), rs.getDouble("y"), - rs.getDouble("z"), rs.getFloat("yaw"), - rs.getFloat("pitch"), rs.getString("server")); - } else { - throw new IllegalArgumentException("Could not return a teleportationPoint from the locations data table at (ID#" + locationID + ")"); - } - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); + ps = connection.prepareStatement("SELECT * FROM " + HuskHomes.getSettings().getLocationsDataTable() + " WHERE `location_id`=?;"); + ps.setInt(1, locationID); + rs = ps.executeQuery(); + if (rs.next()) { + final TeleportationPoint point = new TeleportationPoint(rs.getString("world"), + rs.getDouble("x"), rs.getDouble("y"), + rs.getDouble("z"), rs.getFloat("yaw"), + rs.getFloat("pitch"), rs.getString("server")); + ps.close(); + return point; + } else { + ps.close(); + throw new IllegalArgumentException("Could not return a teleportationPoint from the locations data table at (ID#" + locationID + ")"); + } + } + + public static TeleportationPoint getPlayerDestination(Player p, Connection connection) throws SQLException { + Integer locationID = getPlayerInteger(p, "dest_location_id", connection); + if (locationID != null) { + return getTeleportationPoint(locationID, connection); + } else { + return null; + } + } + + public static TeleportationPoint getPlayerLastPosition(Player p, Connection connection) throws SQLException { + Integer locationID = getPlayerInteger(p, "last_location_id", connection); + if (locationID != null) { + return getTeleportationPoint(locationID, connection); + } else { + return null; + } + } + + // Insert a teleportation point, returns generated id + public static Integer addTeleportationPoint(TeleportationPoint point, Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getLocationsDataTable() + " (world,server,x,y,z,yaw,pitch) VALUES(?,?,?,?,?,?,?);", Statement.RETURN_GENERATED_KEYS); + + ps.setString(1, point.getWorldName()); + ps.setString(2, point.getServer()); + ps.setDouble(3, point.getX()); + ps.setDouble(4, point.getY()); + ps.setDouble(5, point.getZ()); + ps.setFloat(6, point.getYaw()); + ps.setFloat(7, point.getPitch()); + ps.executeUpdate(); + + ResultSet rs = ps.getGeneratedKeys(); + if (rs.next()) { + return rs.getInt(1); } return null; } - public static TeleportationPoint getPlayerDestination(Player p) { - Integer locationID = getPlayerInteger(p, "dest_location_id"); - if (locationID != null) { - return getTeleportationPoint(locationID); - } else { - return null; - } - } + // Update a player's last position teleport point + public static void setTeleportationLastPosition(UUID uuid, TeleportationPoint point, Connection connection) throws SQLException { + PreparedStatement ps; + // Add the teleportation point + Integer locationID = addTeleportationPoint(point, connection); - public static TeleportationPoint getPlayerLastPosition(Player p) { - Integer locationID = getPlayerInteger(p, "last_location_id"); - if (locationID != null) { - return getTeleportationPoint(locationID); - } else { - return null; - } + // Set the destination location with the location_id of the last inserted teleport point + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `last_location_id`=? WHERE `user_uuid`=?;"); + ps.setInt(1, locationID); + ps.setString(2, uuid.toString()); + ps.executeUpdate(); + ps.close(); } // Update a player's last position location on SQL - public static void setPlayerLastPosition(Player p, TeleportationPoint point) { - deletePlayerLastPosition(p); - database.setTeleportationLastPosition(p.getUniqueId(), point); + public static void setPlayerLastPosition(Player p, TeleportationPoint point, Connection connection) throws SQLException { + deletePlayerLastPosition(p, connection); + setTeleportationLastPosition(p.getUniqueId(), point, connection); } // Update a player's destination location on SQL - public static void setPlayerDestinationLocation(String playerName, TeleportationPoint point) { - deletePlayerDestination(playerName); - database.setTeleportationDestination(playerName, point); + public static void setPlayerDestinationLocation(String playerName, TeleportationPoint point, Connection connection) throws SQLException { + deletePlayerDestination(playerName, connection); + setTeleportationDestination(playerName, point, connection); } // Update a player's destination location on SQL - public static void setPlayerDestinationLocation(Player p, TeleportationPoint point) { - setPlayerDestinationLocation(p.getName(), point); + public static void setPlayerDestinationLocation(Player p, TeleportationPoint point, Connection connection) { + setPlayerDestinationLocation(p, point, connection); } - public static void setPlayerTeleporting(Player p, boolean value) { - database.setPlayerTeleporting(p.getUniqueId(), value); + public static void setPlayerTeleporting(Player p, boolean value, Connection connection) throws SQLException { + setPlayerTeleporting(p, value, connection); } - public static void clearPlayerDestination(String playerName) { - deletePlayerDestination(playerName); - database.clearPlayerDestination(playerName); + public static void clearPlayerDestination(String playerName, Connection connection) throws SQLException { + deletePlayerDestination(playerName, connection); + clearPlayerDestData(playerName, connection); } - public static void updateRtpCooldown(Player p) { + public static void updateRtpCooldown(Player p, Connection connection) throws SQLException { long currentTime = Instant.now().getEpochSecond(); int newCooldownTime = (int) currentTime + (60 * HuskHomes.getSettings().getRtpCooldown()); - database.setRtpCooldown(p.getUniqueId(), newCooldownTime); + setRtpCoolDown(p.getUniqueId(), newCooldownTime, connection); } - public static void deletePlayerDestination(String playerName) { - Integer destinationID = getPlayerInteger(playerName, "dest_location_id"); + public static void deletePlayerDestination(String playerName, Connection connection) throws SQLException { + Integer destinationID = getPlayerInteger(playerName, "dest_location_id", connection); if (destinationID != null) { - database.deleteTeleportationPoint(destinationID); - database.clearPlayerDestination(playerName); + deleteTeleportationPoint(destinationID, connection); + clearPlayerDestination(playerName, connection); } } - public static void deletePlayerDestination(Player p) { - deletePlayerDestination(p.getName()); + public static void deletePlayerDestination(Player p, Connection connection) throws SQLException { + deletePlayerDestination(p.getName(), connection); } - public static void deletePlayerLastPosition(Player p) { - Integer lastPositionID = getPlayerInteger(p, "last_location_id"); + // Delete a teleportation point from SQL + public static void deleteTeleportationPoint(int locationID, Connection connection) throws SQLException { + PreparedStatement ps; + ps = connection.prepareStatement("DELETE FROM " + HuskHomes.getSettings().getLocationsDataTable() + " WHERE `location_id`=?;"); + ps.setInt(1, locationID); + ps.executeUpdate(); + } + + public static void deletePlayerLastPosition(Player p, Connection connection) throws SQLException { + Integer lastPositionID = getPlayerInteger(p, "last_location_id", connection); if (lastPositionID != null) { - database.deleteTeleportationPoint(lastPositionID); - database.clearPlayerLastPosition(p.getUniqueId()); + deleteTeleportationPoint(lastPositionID, connection); + clearPlayerLastData(p.getUniqueId(), connection); } } - public static void addWarp(Warp warp) { - database.addWarp(warp); + // Update the location of a home + public static void setHomeTeleportPoint(String homeName, int ownerID, TeleportationPoint point, Connection connection) throws SQLException { + PreparedStatement ps; + // Add the teleportation point + Integer locationID = addTeleportationPoint(point, connection); + + // Set the home location ID to the new teleport point for the given home + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getHomesDataTable() + " SET `location_id`=? WHERE `name`=? AND `player_id`=?;"); + ps.setInt(1, locationID); + ps.setString(2, homeName); + ps.setInt(3, ownerID); + ps.executeUpdate(); + ps.close(); } - public static void addHome(Home home, UUID playerUUID) { - Integer playerID = getPlayerId(playerUUID); + // Clear a player's destination + public static void clearPlayerDestData(String playerName, Connection connection) throws SQLException { + PreparedStatement ps; + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `dest_location_id`=NULL WHERE `username`=?;"); + ps.setString(1, playerName); + ps.executeUpdate(); + ps.close(); + } + + // Clear a player's last position + public static void clearPlayerLastData(UUID uuid, Connection connection) throws SQLException { + PreparedStatement ps; + ps = connection.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `last_location_id`=NULL WHERE `user_uuid`=?;"); + ps.setString(1, uuid.toString()); + ps.executeUpdate(); + ps.close(); + } + + public static void addWarp(Warp warp, Connection connection) throws SQLException { + PreparedStatement ps; + // Add the teleportation point + Integer locationID = addTeleportationPoint(warp, connection); + + // Insert the warp with the location_id of the last inserted teleport point + ps = connection.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getWarpsDataTable() + " (location_id,name,description) VALUES(?,?,?);"); + ps.setInt(1, locationID); + ps.setString(2, warp.getName()); + ps.setString(3, warp.getDescription()); + ps.executeUpdate(); + } + + public static void addHome(Home home, UUID playerUUID, Connection connection) throws SQLException { + Integer playerID = getPlayerId(playerUUID, connection); if (playerID != null) { - database.addHome(home, playerID); + PreparedStatement ps; + + Integer locationID = addTeleportationPoint(home, connection); + + ps = connection.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getHomesDataTable() + " (player_id,location_id,name,description,public) VALUES(?,?,?,?,?);"); + ps.setInt(1, playerID); + ps.setInt(2, locationID); + ps.setString(3, home.getName()); + ps.setString(4, home.getDescription()); + ps.setBoolean(5, home.isPublic()); + ps.executeUpdate(); } else { Bukkit.getLogger().warning("Failed to add a home for a player!"); } } - public static void addHome(Home home, Player p) { - addHome(home, p.getUniqueId()); + + public static void addHome(Home home, Player p, Connection connection) throws SQLException { + addHome(home, p.getUniqueId(), connection); } - public static void deleteHome(String homeName, Player p) { - Integer playerID = getPlayerId(p.getUniqueId()); + public static void deleteHome(String homeName, Player p, Connection connection) throws SQLException { + Integer playerID = getPlayerId(p.getUniqueId(), connection); if (playerID != null) { - deleteHomeTeleportLocation(playerID, homeName); - database.deleteHome(homeName, p.getName()); + deleteHomeTeleportLocation(playerID, homeName, connection); + deleteHome(homeName, p.getName(), connection); } else { Bukkit.getLogger().warning("Player ID returned null when deleting a home"); } } - public static void deleteWarp(String warpName) { - deleteWarpTeleportLocation(warpName); - database.deleteWarp(warpName); + + public static void createPlayer(Player p, Connection connection) throws SQLException { + addPlayer(p, connection); } - public static void setupStorage() { - if (HuskHomes.getSettings().getStorageType().equalsIgnoreCase("mysql")) { - createPlayerTable = "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getPlayerDataTable() + " (" + - "`player_id` integer AUTO_INCREMENT," + - "`user_uuid` char(36) NOT NULL UNIQUE," + - "`username` varchar(16) NOT NULL," + - "`home_slots` integer NOT NULL," + - "`rtp_cooldown` integer NOT NULL," + - "`is_teleporting` boolean NOT NULL," + - "`dest_location_id` integer NULL," + - "`last_location_id` integer NULL," + - - "PRIMARY KEY (`player_id`)," + - "FOREIGN KEY (`dest_location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE SET NULL ON UPDATE NO ACTION," + - "FOREIGN KEY (`last_location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE SET NULL ON UPDATE NO ACTION" + - ");"; - createLocationsTable = "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getLocationsDataTable() + " (" + - "`location_id` integer AUTO_INCREMENT," + - "`server` text NOT NULL," + - "`world` text NOT NULL," + - "`x` double NOT NULL," + - "`y` double NOT NULL," + - "`z` double NOT NULL," + - "`yaw` float NOT NULL," + - "`pitch` float NOT NULL," + - - "PRIMARY KEY (`location_id`)" + - ");"; - } else { - createPlayerTable = "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getPlayerDataTable() + " (" + - "`player_id` integer NOT NULL," + - "`user_uuid` char(36) NOT NULL UNIQUE," + - "`username` varchar(16) NOT NULL," + - "`home_slots` integer NOT NULL," + - "`rtp_cooldown` integer NOT NULL," + - "`is_teleporting` boolean NOT NULL," + - "`dest_location_id` integer NULL," + - "`last_location_id` integer NULL," + - "PRIMARY KEY (`player_id`)," + - "FOREIGN KEY (`dest_location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE SET NULL ON UPDATE NO ACTION," + - "FOREIGN KEY (`last_location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE SET NULL ON UPDATE NO ACTION" + - ");"; - createLocationsTable = "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getLocationsDataTable() + " (" + - "`location_id` integer PRIMARY KEY," + - "`server` text NOT NULL," + - "`world` text NOT NULL," + - "`x` double NOT NULL," + - "`y` double NOT NULL," + - "`z` double NOT NULL," + - "`yaw` float NOT NULL," + - "`pitch` float NOT NULL" + - ");"; - } - initializeDatabase(); + public static void createPlayer(UUID playerUUID, String playerUsername, Connection connection) throws SQLException { + addPlayer(playerUUID, playerUsername, connection); } - public static void createPlayer(Player p) { - database.addPlayer(p); + public static void createPlayer(UUID playerUUID, String playerUsername, int homeSlots, Connection connection) throws SQLException { + addPlayer(playerUUID, playerUsername, homeSlots, connection); } - public static void createPlayer(UUID playerUUID, String playerUsername) { - database.addPlayer(playerUUID, playerUsername); - } - - public static void createPlayer(UUID playerUUID, String playerUsername, int homeSlots) { - database.addPlayer(playerUUID, playerUsername, homeSlots); - } - - public static void checkPlayerNameChange(Player p) { - if (!getPlayerUsername(getPlayerId(p.getUniqueId())).equals(p.getName())) { - database.updatePlayerUsername(p.getUniqueId(), p.getName()); + public static void checkPlayerNameChange(Player p, Connection connection) throws SQLException { + if (!getPlayerUsername(getPlayerId(p.getUniqueId(), connection), connection).equals(p.getName())) { + updatePlayerUsername(p.getUniqueId(), p.getName(), connection); } } } \ No newline at end of file diff --git a/src/main/java/me/william278/huskhomes2/data/Database.java b/src/main/java/me/william278/huskhomes2/data/Database.java deleted file mode 100644 index 9d9b0e50..00000000 --- a/src/main/java/me/william278/huskhomes2/data/Database.java +++ /dev/null @@ -1,511 +0,0 @@ -package me.william278.huskhomes2.data; - -import me.william278.huskhomes2.HuskHomes; -import me.william278.huskhomes2.teleport.points.Home; -import me.william278.huskhomes2.teleport.points.TeleportationPoint; -import me.william278.huskhomes2.teleport.points.Warp; -import org.bukkit.entity.Player; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.UUID; -import java.util.logging.Level; - -/* - TODO Should not relay on SQL - Instead should contain abstract getters and setters etc, so some alternative way of storing data may exist - Current method should possibly go into the SQL class - */ -public abstract class Database { - protected HuskHomes plugin; - private Connection connection; - - public Database(HuskHomes instance) { - plugin = instance; - } - - public abstract Connection getSQLConnection(); - - public abstract void load(); - - public void initialize() { - connection = getSQLConnection(); - 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, "Unable to retrieve connection", ex); - } - } - - // Insert a teleportation point, returns generated id - public Integer addTeleportationPoint(TeleportationPoint point, Connection conn) { - try { - PreparedStatement ps = conn.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getLocationsDataTable() + " (world,server,x,y,z,yaw,pitch) VALUES(?,?,?,?,?,?,?);", Statement.RETURN_GENERATED_KEYS); - - ps.setString(1, point.getWorldName()); - ps.setString(2, point.getServer()); - ps.setDouble(3, point.getX()); - ps.setDouble(4, point.getY()); - ps.setDouble(5, point.getZ()); - ps.setFloat(6, point.getYaw()); - ps.setFloat(7, point.getPitch()); - ps.executeUpdate(); - - ResultSet rs = ps.getGeneratedKeys(); - if (rs.next()) { - return rs.getInt(1); - } - - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - return null; - } - - // Insert a home into the database - public void addHome(Home home, int playerID) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - Integer locationID = addTeleportationPoint(home, conn); - - ps = conn.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getHomesDataTable() + " (player_id,location_id,name,description,public) VALUES(?,?,?,?,?);"); - ps.setInt(1, playerID); - ps.setInt(2, locationID); - ps.setString(3, home.getName()); - ps.setString(4, home.getDescription()); - ps.setBoolean(5, home.isPublic()); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Insert a warp into the database - public void addWarp(Warp warp) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Add the teleportation point - Integer locationID = addTeleportationPoint(warp, conn); - - // Insert the warp with the location_id of the last inserted teleport point - ps = conn.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getWarpsDataTable() + " (location_id,name,description) VALUES(?,?,?);"); - ps.setInt(1, locationID); - ps.setString(2, warp.getName()); - ps.setString(3, warp.getDescription()); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Delete a warp - public void deleteWarp(String warpName) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Delete the warp with the given name - ps = conn.prepareStatement("DELETE FROM " + HuskHomes.getSettings().getWarpsDataTable() + " WHERE `name`=?;"); - ps.setString(1, warpName); - ps.executeUpdate(); - - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Delete a warp - // Insert a player into the database - - public void deleteHome(String homeName, String ownerUsername) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Delete the home with the given name and player ID - ps = conn.prepareStatement("DELETE FROM " + HuskHomes.getSettings().getHomesDataTable() + " WHERE `name`=? AND `player_id`=(SELECT `player_id` FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?);"); - ps.setString(1, homeName); - ps.setString(2, ownerUsername); - ps.executeUpdate(); - - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - public void addPlayer(Player p) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - ps = conn.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getPlayerDataTable() + " (user_uuid,username,home_slots,rtp_cooldown,is_teleporting) VALUES(?,?,?,?,?);"); - ps.setString(1, p.getUniqueId().toString()); - ps.setString(2, p.getName()); - ps.setInt(3, Home.getFreeHomes(p)); - ps.setInt(4, 0); - ps.setBoolean(5, false); - - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Insert a player into the database - public void addPlayer(UUID playerUUID, String playerName) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - ps = conn.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getPlayerDataTable() + " (user_uuid,username,home_slots,rtp_cooldown,is_teleporting) VALUES(?,?,?,?,?);"); - ps.setString(1, playerUUID.toString()); - ps.setString(2, playerName); - ps.setInt(3, HuskHomes.getSettings().getFreeHomeSlots()); - ps.setInt(4, 0); - ps.setBoolean(5, false); - - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Insert a player into the database - public void addPlayer(UUID playerUUID, String playerName, int homeSlots) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - ps = conn.prepareStatement("INSERT INTO " + HuskHomes.getSettings().getPlayerDataTable() + " (user_uuid,username,home_slots,rtp_cooldown,is_teleporting) VALUES(?,?,?,?,?);"); - ps.setString(1, playerUUID.toString()); - ps.setString(2, playerName); - ps.setInt(3, homeSlots); - ps.setInt(4, 0); - ps.setBoolean(5, false); - - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - public void updatePlayerUsername(UUID uuid, String newName) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `username`=? WHERE `user_uuid`=?;"); - ps.setString(1, newName); - ps.setString(2, uuid.toString()); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - public void setPlayerTeleporting(UUID uuid, boolean value) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `is_teleporting`=? WHERE `user_uuid`=?;"); - ps.setBoolean(1, value); - ps.setString(2, uuid.toString()); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - public void setPlayerHomeSlots(UUID uuid, int newValue) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `home_slots`=? WHERE `user_uuid`=?;"); - ps.setInt(1, newValue); - ps.setString(2, uuid.toString()); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - public void setRtpCooldown(UUID uuid, int newTime) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `rtp_cooldown`=? WHERE `user_uuid`=?;"); - ps.setInt(1, newTime); - ps.setString(2, uuid.toString()); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Delete a teleportation point from SQL - public void deleteTeleportationPoint(int locationID) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - ps = conn.prepareStatement("DELETE FROM " + HuskHomes.getSettings().getLocationsDataTable() + " WHERE `location_id`=?;"); - ps.setInt(1, locationID); - - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Update the location of a home - public void setHomePrivacy(String homeName, String ownerName, boolean isPublic) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Set the home location ID to the new teleport point for the given home - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getHomesDataTable() + " SET `public`=? WHERE `name`=? AND `player_id`=(SELECT `player_id` FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?);"); - ps.setBoolean(1, isPublic); - ps.setString(2, homeName); - ps.setString(3, ownerName); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Update the location of a home - public void setHomeTeleportPoint(String homeName, int ownerID, TeleportationPoint point) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Add the teleportation point - Integer locationID = addTeleportationPoint(point, conn); - - // Set the home location ID to the new teleport point for the given home - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getHomesDataTable() + " SET `location_id`=? WHERE `name`=? AND `player_id`=?;"); - ps.setInt(1, locationID); - ps.setString(2, homeName); - ps.setInt(3, ownerID); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Update the location of a home - public void setWarpTeleportPoint(String warpName, TeleportationPoint point) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Add the teleportation point - Integer locationID = addTeleportationPoint(point, conn); - - // Set the warp location ID to the new teleport point - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getWarpsDataTable() + " SET `location_id`=? WHERE `name`=?;"); - ps.setInt(1, locationID); - ps.setString(2, warpName); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - // Update the description of a home - public void setHomeDescription(String homeName, String ownerName, String newDescription) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Update the home description - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getHomesDataTable() + " SET `description`=? WHERE `name`=? AND `player_id`=(SELECT `player_id` FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?);"); - ps.setString(1, newDescription); - ps.setString(2, homeName); - ps.setString(3, ownerName); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Update the description of a warp - public void setWarpDescription(String warpName, String newDescription) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Update the warp description - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getWarpsDataTable() + " SET `description`=? WHERE `name`=?;"); - ps.setString(1, newDescription); - ps.setString(2, warpName); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Update the name of a home - public void setHomeName(String oldHomeName, String ownerName, String newHomeName) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Update the home name - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getHomesDataTable() + " SET `name`=? WHERE `name`=? AND `player_id`=(SELECT `player_id` FROM " + HuskHomes.getSettings().getPlayerDataTable() + " WHERE `username`=?);"); - ps.setString(1, newHomeName); - ps.setString(2, oldHomeName); - ps.setString(3, ownerName); - - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Update the name of a warp - public void setWarpName(String oldWarpName, String newWarpName) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Update the warp name - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getWarpsDataTable() + " SET `name`=? WHERE `name`=?;"); - ps.setString(1, newWarpName); - ps.setString(2, oldWarpName); - - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Update a player's last position teleport point - public void setTeleportationLastPosition(UUID uuid, TeleportationPoint point) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Add the teleportation point - Integer locationID = addTeleportationPoint(point, conn); - - // Set the destination location with the location_id of the last inserted teleport point - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `last_location_id`=? WHERE `user_uuid`=?;"); - ps.setInt(1, locationID); - ps.setString(2, uuid.toString()); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Update a player's destination teleport point - public void setTeleportationDestination(String username, TeleportationPoint point) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - - // Add the teleportation point - Integer locationID = addTeleportationPoint(point, conn); - - // Set the destination location with the location_id of the last inserted teleport point - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `dest_location_id`=? WHERE `username`=?;"); - ps.setInt(1, locationID); - ps.setString(2, username); - ps.executeUpdate(); - - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Clear a player's destination - public void clearPlayerDestination(String playerName) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `dest_location_id`=NULL WHERE `username`=?;"); - ps.setString(1, playerName); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - // Clear a player's last position - public void clearPlayerLastPosition(UUID uuid) { - Connection conn; - PreparedStatement ps; - - try { - conn = getSQLConnection(); - ps = conn.prepareStatement("UPDATE " + HuskHomes.getSettings().getPlayerDataTable() + " SET `last_location_id`=NULL WHERE `user_uuid`=?;"); - ps.setString(1, uuid.toString()); - ps.executeUpdate(); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, Error.SQL_CONNECTION_EXECUTE, ex); - } - } - - public void close(PreparedStatement ps, ResultSet rs) { - try { - if (ps != null) - ps.close(); - if (rs != null) - rs.close(); - } catch (SQLException ex) { - Error.close(plugin, ex); - } - } -} diff --git a/src/main/java/me/william278/huskhomes2/data/SQL.java b/src/main/java/me/william278/huskhomes2/data/SQL.java deleted file mode 100644 index 30c8a1ac..00000000 --- a/src/main/java/me/william278/huskhomes2/data/SQL.java +++ /dev/null @@ -1,114 +0,0 @@ -package me.william278.huskhomes2.data; - -import me.william278.huskhomes2.HuskHomes; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.logging.Level; - -/* - TODO Split into SQLite, MySQL and abstract SQL classes - Even tho both are using pretty much the same syntax and stuff, their initializations are too different and should - not co-exist in the same class. - */ -public class SQL extends Database { - - private static final String SQLITE_DATABASE_NAME = "HuskHomesData"; - - private Connection connection; - - private void setConnection(Connection connection) { - this.connection = connection; - } - - public SQL(HuskHomes instance) { - super(instance); - } - - // Initialise connection via mySQL - private void getMySQLConnection() { - String host = HuskHomes.getSettings().getMySQLhost(); - int port = HuskHomes.getSettings().getMySQLport(); - String database = HuskHomes.getSettings().getMySQLdatabase(); - String username = HuskHomes.getSettings().getMySQLusername(); - String password = HuskHomes.getSettings().getMySQLpassword(); - - try { - synchronized (HuskHomes.getInstance()) { - Class.forName("com.mysql.jdbc.Driver"); - setConnection(DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true&useSSL=false", username, password)); - } - } catch (SQLException e) { - HuskHomes.disablePlugin("[!] Could not connect to the mySQL Database with the credentials provided!\n[!] Check that your host IP address and port are valid and that your username and password are valid and that the user has the correct access permissions on the database."); - } catch (ClassNotFoundException e) { - HuskHomes.disablePlugin("[!] A critical exception occurred when attempting to establish a connection to the mySQL database!"); - e.printStackTrace(); - } - } - - // Initialise connection via SQLite - private void getSQLiteConnection() { - File dataFolder = new File(plugin.getDataFolder(), SQLITE_DATABASE_NAME + ".db"); - if (!dataFolder.exists()) { - try { - if (!dataFolder.createNewFile()) { - plugin.getLogger().log(Level.SEVERE, "Failed to write new file: " + SQLITE_DATABASE_NAME + ".db (file already exists)"); - } - } catch (IOException e) { - plugin.getLogger().log(Level.SEVERE, "An error occurred writing a file: " + SQLITE_DATABASE_NAME + ".db (" + e.getCause() + ")"); - } - } - try { - Class.forName("org.sqlite.JDBC"); - setConnection(DriverManager.getConnection("jdbc:sqlite:" + plugin.getDataFolder().getAbsolutePath() + "/" + SQLITE_DATABASE_NAME + ".db")); - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, "An exception occurred initialising the SQLite database", ex); - } catch (ClassNotFoundException ex) { - plugin.getLogger().log(Level.SEVERE, "You need the SQLite JBDC library; please download and place this in the /lib folder."); - } - } - - public Connection getSQLConnection() { - try { - if (connection == null || connection.isClosed()) { - String dataStorageType = HuskHomes.getSettings().getStorageType().toLowerCase(); - switch (dataStorageType) { - case "mysql": - getMySQLConnection(); - break; - case "sqlite": - getSQLiteConnection(); - break; - default: - plugin.getLogger().log(Level.WARNING, "An invalid data storage type was specified in config.yml; defaulting to SQLite"); - getSQLiteConnection(); - break; - } - } - } catch (SQLException ex) { - plugin.getLogger().log(Level.WARNING, "An error occurred checking the status of the SQL connection"); - } - return connection; - } - - public void load() { - connection = getSQLConnection(); - - try { - Statement s = connection.createStatement(); - s.execute(DataManager.createLocationsTable); - s.execute(DataManager.createPlayerTable); - s.execute(DataManager.createHomesTable); - s.execute(DataManager.createWarpsTable); - s.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - - initialize(); - } -} \ No newline at end of file diff --git a/src/main/java/me/william278/huskhomes2/data/SQL/Database.java b/src/main/java/me/william278/huskhomes2/data/SQL/Database.java new file mode 100644 index 00000000..40dcc4c7 --- /dev/null +++ b/src/main/java/me/william278/huskhomes2/data/SQL/Database.java @@ -0,0 +1,61 @@ +package me.william278.huskhomes2.data.SQL; + +import me.william278.huskhomes2.HuskHomes; +import me.william278.huskhomes2.data.Error; +import me.william278.huskhomes2.teleport.points.Home; +import me.william278.huskhomes2.teleport.points.TeleportationPoint; +import me.william278.huskhomes2.teleport.points.Warp; +import org.bukkit.entity.Player; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; +import java.util.logging.Level; + +/* + TODO Should not relay on SQL + Instead should contain abstract getters and setters etc, so some alternative way of storing data may exist + Current method should possibly go into the SQL class + */ +public abstract class Database { + protected HuskHomes plugin; + private Connection connection; + + public Database(HuskHomes instance) { + plugin = instance; + } + + public abstract Connection getConnection(); + + public abstract void load(); + + public void initialize() { + 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); + } + } + + +} diff --git a/src/main/java/me/william278/huskhomes2/data/SQL/MySQL.java b/src/main/java/me/william278/huskhomes2/data/SQL/MySQL.java new file mode 100644 index 00000000..22ac87be --- /dev/null +++ b/src/main/java/me/william278/huskhomes2/data/SQL/MySQL.java @@ -0,0 +1,112 @@ +package me.william278.huskhomes2.data.SQL; + +import me.william278.huskhomes2.HuskHomes; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.logging.Level; + +public class MySQL extends Database { + + final static String[] SQL_SETUP_STATEMENTS = { + "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getPlayerDataTable() + " (" + + "`player_id` integer AUTO_INCREMENT," + + "`user_uuid` char(36) NOT NULL UNIQUE," + + "`username` varchar(16) NOT NULL," + + "`home_slots` integer NOT NULL," + + "`rtp_cooldown` integer NOT NULL DEFAULT 0," + + "`is_teleporting` boolean NOT NULL DEFAULT 0," + + "`dest_location_id` integer NULL," + + "`last_location_id` integer NULL," + + + "PRIMARY KEY (`player_id`)," + + "FOREIGN KEY (`dest_location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE SET NULL ON UPDATE NO ACTION," + + "FOREIGN KEY (`last_location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE SET NULL ON UPDATE NO ACTION" + + ");", + + "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getLocationsDataTable() + " (" + + "`location_id` integer AUTO_INCREMENT," + + "`server` text NOT NULL," + + "`world` text NOT NULL," + + "`x` double NOT NULL," + + "`y` double NOT NULL," + + "`z` double NOT NULL," + + "`yaw` float NOT NULL," + + "`pitch` float NOT NULL," + + + "PRIMARY KEY (`location_id`)" + + ");", + + "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getHomesDataTable() + " (" + + "`player_id` integer NOT NULL," + + "`location_id` integer NOT NULL," + + "`name` varchar(16) NOT NULL," + + "`description` varchar(255) NOT NULL," + + "`public` boolean NOT NULL," + + "PRIMARY KEY (`player_id`, `name`)," + + "FOREIGN KEY (`player_id`) REFERENCES " + HuskHomes.getSettings().getPlayerDataTable() + " (`player_id`) ON DELETE CASCADE ON UPDATE NO ACTION," + + "FOREIGN KEY (`location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + + ");", + + "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getWarpsDataTable() + " (" + + "`location_id` integer NOT NULL," + + "`name` varchar(16) NOT NULL UNIQUE," + + "`description` varchar(255) NOT NULL," + + "PRIMARY KEY (`location_id`)," + + "FOREIGN KEY (`location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + + ");" + }; + + final String host = HuskHomes.getSettings().getMySQLhost(); + final int port = HuskHomes.getSettings().getMySQLport(); + final String database = HuskHomes.getSettings().getMySQLdatabase(); + final String username = HuskHomes.getSettings().getMySQLusername(); + final String password = HuskHomes.getSettings().getMySQLpassword(); + final String params = HuskHomes.getSettings().getMySQLparams(); + + private Connection connection; + + public MySQL(HuskHomes instance) { + super(instance); + } + + @Override + public Connection getConnection() { + try { + if (connection == null || connection.isClosed()) { + try { + synchronized (HuskHomes.getInstance()) { + Class.forName("com.mysql.cj.jdbc.Driver"); + connection = (DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + params, username, password)); + } + } catch (SQLException ex) { + plugin.getLogger().log(Level.SEVERE, "An exception occurred initialising the mySQL database: ", ex); + } catch (ClassNotFoundException ex) { + plugin.getLogger().log(Level.SEVERE, "The mySQL JBDC library is missing! Please download and place this in the /lib folder."); + } + } + } catch (SQLException exception) { + plugin.getLogger().log(Level.WARNING, "An error occurred checking the status of the SQL connection: ", exception); + } + return connection; + } + + @Override + public void load() { + connection = getConnection(); + try { + Statement statement = connection.createStatement(); + for (String tableCreationStatement : SQL_SETUP_STATEMENTS) { + statement.execute(tableCreationStatement); + } + statement.close(); + } catch (SQLException exception) { + plugin.getLogger().log(Level.SEVERE, "An error occurred creating tables: ", exception); + exception.printStackTrace(); + } + + initialize(); + } +} diff --git a/src/main/java/me/william278/huskhomes2/data/SQL/SQLite.java b/src/main/java/me/william278/huskhomes2/data/SQL/SQLite.java new file mode 100644 index 00000000..8a14f590 --- /dev/null +++ b/src/main/java/me/william278/huskhomes2/data/SQL/SQLite.java @@ -0,0 +1,116 @@ +package me.william278.huskhomes2.data.SQL; + +import me.william278.huskhomes2.HuskHomes; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.logging.Level; + +public class SQLite extends Database { + + final static String[] SQL_SETUP_STATEMENTS = { + "PRAGMA foreign_keys = ON;", + + "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getPlayerDataTable() + " (" + + "`player_id` integer NOT NULL," + + "`user_uuid` char(36) NOT NULL UNIQUE," + + "`username` varchar(16) NOT NULL," + + "`home_slots` integer NOT NULL," + + "`rtp_cooldown` integer NOT NULL DEFAULT 0," + + "`is_teleporting` boolean NOT NULL DEFAULT 0," + + "`dest_location_id` integer NULL," + + "`last_location_id` integer NULL," + + "PRIMARY KEY (`player_id`)," + + "FOREIGN KEY (`dest_location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE SET NULL ON UPDATE NO ACTION," + + "FOREIGN KEY (`last_location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE SET NULL ON UPDATE NO ACTION" + + ");", + + "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getLocationsDataTable() + " (" + + "`location_id` integer PRIMARY KEY," + + "`server` text NOT NULL," + + "`world` text NOT NULL," + + "`x` double NOT NULL," + + "`y` double NOT NULL," + + "`z` double NOT NULL," + + "`yaw` float NOT NULL," + + "`pitch` float NOT NULL" + + ");", + + "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getHomesDataTable() + " (" + + "`player_id` integer NOT NULL," + + "`location_id` integer NOT NULL," + + "`name` varchar(16) NOT NULL," + + "`description` varchar(255) NOT NULL," + + "`public` boolean NOT NULL," + + "PRIMARY KEY (`player_id`, `name`)," + + "FOREIGN KEY (`player_id`) REFERENCES " + HuskHomes.getSettings().getPlayerDataTable() + " (`player_id`) ON DELETE CASCADE ON UPDATE NO ACTION," + + "FOREIGN KEY (`location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + + ");", + + "CREATE TABLE IF NOT EXISTS " + HuskHomes.getSettings().getWarpsDataTable() + " (" + + "`location_id` integer NOT NULL," + + "`name` varchar(16) NOT NULL UNIQUE," + + "`description` varchar(255) NOT NULL," + + "PRIMARY KEY (`location_id`)," + + "FOREIGN KEY (`location_id`) REFERENCES " + HuskHomes.getSettings().getLocationsDataTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + + ");" + }; + + private static final String DATABASE_NAME = "HuskHomesData"; + + private Connection connection; + + public SQLite(HuskHomes instance) { + super(instance); + } + + @Override + public Connection getConnection() { + try { + if (connection == null || connection.isClosed()) { + File databaseFile = new File(plugin.getDataFolder(), DATABASE_NAME + ".db"); + if (!databaseFile.exists()) { + try { + if (!databaseFile.createNewFile()) { + plugin.getLogger().log(Level.SEVERE, "Failed to write new file: " + DATABASE_NAME + ".db (file already exists)"); + } + } catch (IOException e) { + plugin.getLogger().log(Level.SEVERE, "An error occurred writing a file: " + DATABASE_NAME + ".db (" + e.getCause() + ")"); + } + } + try { + Class.forName("org.sqlite.JDBC"); + connection = (DriverManager.getConnection("jdbc:sqlite:" + plugin.getDataFolder().getAbsolutePath() + "/" + DATABASE_NAME + ".db")); + } catch (SQLException ex) { + plugin.getLogger().log(Level.SEVERE, "An exception occurred initialising the SQLite database", ex); + } catch (ClassNotFoundException ex) { + plugin.getLogger().log(Level.SEVERE, "The SQLite JBDC library is missing! Please download and place this in the /lib folder."); + } + } + } catch (SQLException exception) { + plugin.getLogger().log(Level.WARNING, "An error occurred checking the status of the SQL connection: ", exception); + } + return connection; + } + + @Override + public void load() { + connection = getConnection(); + try { + Statement statement = connection.createStatement(); + for (String tableCreationStatement : SQL_SETUP_STATEMENTS) { + statement.execute(tableCreationStatement); + } + statement.close(); + } catch (SQLException exception) { + plugin.getLogger().log(Level.SEVERE, "An error occurred creating tables: ", exception); + exception.printStackTrace(); + } + + initialize(); + } +} diff --git a/src/main/java/me/william278/huskhomes2/data/pluginmessage/PluginMessage.java b/src/main/java/me/william278/huskhomes2/data/pluginmessage/PluginMessage.java new file mode 100644 index 00000000..18de7469 --- /dev/null +++ b/src/main/java/me/william278/huskhomes2/data/pluginmessage/PluginMessage.java @@ -0,0 +1,154 @@ +package me.william278.huskhomes2.data.pluginmessage; + +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; +import me.william278.huskhomes2.HuskHomes; +import org.bukkit.entity.Player; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.Locale; + +public class PluginMessage { + + private static final HuskHomes plugin = HuskHomes.getInstance(); + + // Move a player to a different server in the bungee network + public static void sendPlayer(Player p, String targetServer) { + ByteArrayDataOutput out = ByteStreams.newDataOutput(); + out.writeUTF("Connect"); + out.writeUTF(targetServer); + p.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); + } + + private static final String MESSAGE_DATA_SEPARATOR = "$"; + private final int clusterID; + private final PluginMessageType messageType; + private final String targetPlayerName; + private final String messageData; + + /** + * Creates a Plugin Message ready to be sent + * @param targetPlayerName Name of the player the message will be sent to over Bungee + * @param pluginMessageType Type of the plugin message + * @param messageData Associated message data + */ + public PluginMessage(String targetPlayerName, PluginMessageType pluginMessageType, String... messageData) { + this.clusterID = HuskHomes.getSettings().getClusterID(); + this.messageType = pluginMessageType; + StringBuilder newMessageData = new StringBuilder(); + for (String s : messageData) { + newMessageData.append(s).append(MESSAGE_DATA_SEPARATOR); + } + this.messageData = newMessageData.substring(0, newMessageData.toString().length()-1); + this.targetPlayerName = targetPlayerName; + } + + public PluginMessage(PluginMessageType pluginMessageType, String... messageData) { + this.clusterID = HuskHomes.getSettings().getClusterID(); + this.messageType = pluginMessageType; + StringBuilder newMessageData = new StringBuilder(); + for (String s : messageData) { + newMessageData.append(s).append(MESSAGE_DATA_SEPARATOR); + } + this.messageData = newMessageData.substring(0, newMessageData.toString().length()-1); + this.targetPlayerName = null; + } + + public PluginMessage(int clusterID, String targetPlayerName, String pluginMessageType, String... messageData) { + this.clusterID = clusterID; + this.messageType = PluginMessageType.valueOf(pluginMessageType.toUpperCase(Locale.ENGLISH)); + StringBuilder newMessageData = new StringBuilder(); + for (String s : messageData) { + newMessageData.append(s).append(MESSAGE_DATA_SEPARATOR); + } + this.messageData = newMessageData.substring(0, newMessageData.toString().length()-1); + this.targetPlayerName = targetPlayerName; + } + + // Get the string version of the plugin message type + private String getPluginMessageString(PluginMessageType type) { + return type.name().toLowerCase(Locale.ENGLISH); + } + + /** + * Send the plugin message + * @param sender The player to send the message + */ + public void send(Player sender) { + ByteArrayDataOutput out = ByteStreams.newDataOutput(); + + // Send a plugin message to the specified player name + out.writeUTF("ForwardToPlayer"); + out.writeUTF(targetPlayerName); + + // Send the HuskHomes message with a specific type + out.writeUTF("HuskHomes:" + clusterID + ":" + getPluginMessageString(messageType)); + ByteArrayOutputStream messageBytes = new ByteArrayOutputStream(); + DataOutputStream messageOut = new DataOutputStream(messageBytes); + + // Send the message data; output an exception if there's an error + try { + messageOut.writeUTF(messageData); + } catch (IOException e) { + plugin.getLogger().warning("An error occurred trying to send a plugin message (" + e.getCause() + ")"); + e.printStackTrace(); + } + + // Write the messages to the output packet + out.writeShort(messageBytes.toByteArray().length); + out.write(messageBytes.toByteArray()); + + // Send the constructed plugin message packet + sender.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); + } + + public void sendToAll(Player sender) { + ByteArrayDataOutput out = ByteStreams.newDataOutput(); + + // Send a plugin message to all players + out.writeUTF("Forward"); + out.writeUTF("ALL"); + + // Send the HuskHomes message with a specific type + out.writeUTF("HuskHomes:" + clusterID + ":" + getPluginMessageString(messageType)); + ByteArrayOutputStream messageBytes = new ByteArrayOutputStream(); + DataOutputStream messageOut = new DataOutputStream(messageBytes); + + // Send the message data; output an exception if there's an error + try { + messageOut.writeUTF(messageData); + } catch (IOException e) { + plugin.getLogger().warning("An error occurred trying to send a plugin message (" + e.getCause() + ")"); + e.printStackTrace(); + } + + // Write the messages to the output packet + out.writeShort(messageBytes.toByteArray().length); + out.write(messageBytes.toByteArray()); + + // Send the constructed plugin message packet + sender.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); + } + + public int getClusterID() { + return clusterID; + } + + public PluginMessageType getMessageType() { + return messageType; + } + + public String getTargetPlayerName() { + return targetPlayerName; + } + + public String getMessageData() { + return messageData; + } + + public String[] getMessageDataItems() { + return messageData.split("\\" + MESSAGE_DATA_SEPARATOR); + } +} diff --git a/src/main/java/me/william278/huskhomes2/data/pluginmessage/PluginMessageType.java b/src/main/java/me/william278/huskhomes2/data/pluginmessage/PluginMessageType.java new file mode 100644 index 00000000..ce2b751e --- /dev/null +++ b/src/main/java/me/william278/huskhomes2/data/pluginmessage/PluginMessageType.java @@ -0,0 +1,14 @@ +package me.william278.huskhomes2.data.pluginmessage; + +public enum PluginMessageType { + SET_TP_DESTINATION, + CONFIRM_DESTINATION_SET, + TPA_REQUEST, + TPAHERE_REQUEST, + TPA_REQUEST_REPLY, + TPAHERE_REQUEST_REPLY, + TELEPORT_TO_ME, + GET_ONLINE_PLAYERS, + RETURN_ONLINE_PLAYERS, + PLAYER_CHANGE +} diff --git a/src/main/java/me/william278/huskhomes2/listeners/PlayerListener.java b/src/main/java/me/william278/huskhomes2/listeners/PlayerListener.java index affcaead..5ef66933 100644 --- a/src/main/java/me/william278/huskhomes2/listeners/PlayerListener.java +++ b/src/main/java/me/william278/huskhomes2/listeners/PlayerListener.java @@ -3,7 +3,7 @@ package me.william278.huskhomes2.listeners; import me.william278.huskhomes2.CrossServerListHandler; import me.william278.huskhomes2.HuskHomes; import me.william278.huskhomes2.MessageManager; -import me.william278.huskhomes2.PluginMessageHandler; +import me.william278.huskhomes2.data.pluginmessage.PluginMessageHandler; import me.william278.huskhomes2.commands.HomeCommand; import me.william278.huskhomes2.data.DataManager; import me.william278.huskhomes2.teleport.TeleportManager; @@ -14,7 +14,6 @@ import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.chat.hover.content.Text; -import org.bukkit.entity.Husk; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -70,11 +69,11 @@ public class PlayerListener implements Listener { TeleportManager.teleportPlayer(p); } - // Update player lists globally + /*// Update player lists globally if (HuskHomes.getSettings().doCrossServerTabCompletion()) { CrossServerListHandler.updatePlayerList(p); PluginMessageHandler.broadcastPlayerChange(p); - } + }*/ } } catch (NullPointerException ignored) { } // Ignore NullPointerExceptions from players that execute this event and return null (e.g Citizens). } diff --git a/src/main/java/me/william278/huskhomes2/listeners/PluginMessageListener.java b/src/main/java/me/william278/huskhomes2/listeners/PluginMessageListener.java new file mode 100644 index 00000000..4cbfc726 --- /dev/null +++ b/src/main/java/me/william278/huskhomes2/listeners/PluginMessageListener.java @@ -0,0 +1,133 @@ +package me.william278.huskhomes2.listeners; + +import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteStreams; +import me.william278.huskhomes2.HuskHomes; +import me.william278.huskhomes2.MessageManager; +import me.william278.huskhomes2.data.DataManager; +import me.william278.huskhomes2.data.pluginmessage.PluginMessage; +import me.william278.huskhomes2.data.pluginmessage.PluginMessageType; +import me.william278.huskhomes2.integrations.VanishChecker; +import me.william278.huskhomes2.teleport.TeleportManager; +import me.william278.huskhomes2.teleport.TeleportRequest; +import me.william278.huskhomes2.teleport.TeleportRequestHandler; +import me.william278.huskhomes2.teleport.points.TeleportationPoint; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.util.logging.Level; + +public class PluginMessageListener implements org.bukkit.plugin.messaging.PluginMessageListener { + + private void handlePluginMessage(PluginMessage pluginMessage, Player recipient) { + switch (pluginMessage.getMessageType()) { + case SET_TP_DESTINATION: + DataManager.setPlayerDestinationLocation(pluginMessage.getMessageData(), + new TeleportationPoint(recipient.getLocation(), HuskHomes.getSettings().getServerID())); + new PluginMessage(pluginMessage.getMessageData(), PluginMessageType.CONFIRM_DESTINATION_SET, "confirmed").send(recipient); + return; + case CONFIRM_DESTINATION_SET: + if (pluginMessage.getMessageData().equals("confirmed")) { + TeleportManager.teleportPlayer(recipient); + } + return; + case TPA_REQUEST: + if (!VanishChecker.isVanished(recipient)) { + TeleportRequestHandler.teleportRequests.put(recipient, new TeleportRequest(pluginMessage.getMessageData(), TeleportRequest.RequestType.TPA)); + MessageManager.sendMessage(recipient, "tpa_request_ask", pluginMessage.getMessageData()); + TeleportRequestHandler.sendTpAcceptDenyButtons(recipient); + } + return; + case TPAHERE_REQUEST: + if (!VanishChecker.isVanished(recipient)) { + TeleportRequestHandler.teleportRequests.put(recipient, new TeleportRequest(pluginMessage.getMessageData(), TeleportRequest.RequestType.TPAHERE)); + MessageManager.sendMessage(recipient, "tpahere_request_ask", pluginMessage.getMessageData()); + TeleportRequestHandler.sendTpAcceptDenyButtons(recipient); + } + return; + case TPA_REQUEST_REPLY: + final String tpaReplierName = pluginMessage.getMessageDataItems()[0]; + final boolean tpaAccepted = Boolean.parseBoolean(pluginMessage.getMessageDataItems()[1]); + if (tpaAccepted) { + MessageManager.sendMessage(recipient, "tpa_has_accepted", tpaReplierName); + TeleportManager.queueTimedTeleport(recipient, tpaReplierName); + } else { + MessageManager.sendMessage(recipient, "tpa_has_declined", tpaReplierName); + } + return; + case TPAHERE_REQUEST_REPLY: + final String tpaHereReplierName = pluginMessage.getMessageDataItems()[0]; + final boolean tpaHereAccepted = Boolean.parseBoolean(pluginMessage.getMessageDataItems()[1]); + if (tpaHereAccepted) { + MessageManager.sendMessage(recipient, "tpa_has_accepted", tpaHereReplierName); + } else { + MessageManager.sendMessage(recipient, "tpa_has_declined", tpaHereReplierName); + } + return; + case TELEPORT_TO_ME: + TeleportManager.teleportPlayer(recipient, pluginMessage.getMessageData()); + return; + case GET_ONLINE_PLAYERS: + /*if (Bukkit.getOnlinePlayers().size() > 0) { + returnPlayerList(messageData, recipient); + }*/ + return; + default: + HuskHomes.getInstance().getLogger().log(Level.WARNING, "Received a HuskHomes plugin message with an unrecognised type. Is your version of HuskTowns up to date?"); + } + } + + @Override + public void onPluginMessageReceived(String channel, Player player, byte[] message) { + // Return if the message is not a Bungee message + if (!channel.equals("BungeeCord")) { + return; + } + ByteArrayDataInput input = ByteStreams.newDataInput(message); + + // Plugin messages are formatted as such: + // HuskHomes::, followed by the message arguments and data. + String messageType = input.readUTF(); + int clusterID; + + // Return if the message was not sent by HuskHomes + if (!messageType.contains("HuskHomes:")) { + return; + } + + // Ensure the cluster ID matches + try { + clusterID = Integer.parseInt(messageType.split(":")[1]); + } catch (Exception e) { + // In case the message is malformed or the cluster ID is invalid + HuskHomes.getInstance().getLogger().warning("Received a HuskHomes plugin message with an invalid server Cluster ID! \n" + + "Please ensure that the cluster ID is set to a valid integer on all servers."); + return; + } + if (HuskHomes.getSettings().getClusterID() != clusterID) { + return; + } + + // Get the message data packets + String messageData = ""; + short messageLength = input.readShort(); + byte[] messageBytes = new byte[messageLength]; + input.readFully(messageBytes); + DataInputStream messageIn = new DataInputStream(new ByteArrayInputStream(messageBytes)); + + // Get the message data string from the packets received + try { + messageData = messageIn.readUTF(); + } catch (IOException e) { + Bukkit.getLogger().warning("An error occurred trying to read a plugin message (" + e.getCause() + ")"); + e.printStackTrace(); + } + + // Handle the plugin message appropriately + handlePluginMessage(new PluginMessage(clusterID, player.getName(), messageType.split(":")[2], messageData), player); + } + +} diff --git a/src/main/java/me/william278/huskhomes2/teleport/TeleportManager.java b/src/main/java/me/william278/huskhomes2/teleport/TeleportManager.java index 53a95d49..e151dcd6 100644 --- a/src/main/java/me/william278/huskhomes2/teleport/TeleportManager.java +++ b/src/main/java/me/william278/huskhomes2/teleport/TeleportManager.java @@ -1,10 +1,11 @@ package me.william278.huskhomes2.teleport; -import me.william278.huskhomes2.CrossServerListHandler; import me.william278.huskhomes2.HuskHomes; import me.william278.huskhomes2.MessageManager; -import me.william278.huskhomes2.PluginMessageHandler; +import me.william278.huskhomes2.data.pluginmessage.PluginMessage; +import me.william278.huskhomes2.data.pluginmessage.PluginMessageHandler; import me.william278.huskhomes2.data.DataManager; +import me.william278.huskhomes2.data.pluginmessage.PluginMessageType; import me.william278.huskhomes2.integrations.VaultIntegration; import me.william278.huskhomes2.teleport.points.RandomPoint; import me.william278.huskhomes2.teleport.points.TeleportationPoint; @@ -45,7 +46,7 @@ public class TeleportManager { } else if (HuskHomes.getSettings().doBungee()) { DataManager.setPlayerDestinationLocation(p, teleportationPoint); DataManager.setPlayerTeleporting(p, true); - PluginMessageHandler.sendPlayer(p, server); + PluginMessage.sendPlayer(p, server); } } } @@ -152,11 +153,11 @@ public class TeleportManager { } private static void teleportHereCrossServer(Player requester, String targetPlayerName) { - PluginMessageHandler.sendPluginMessage(requester, targetPlayerName, "teleport_to_me", requester.getName()); + new PluginMessage(targetPlayerName, PluginMessageType.TELEPORT_TO_ME, requester.getName()).send(requester); } private static void setTeleportationDestinationCrossServer(Player requester, String targetPlayerName) { - PluginMessageHandler.sendPluginMessage(requester, targetPlayerName, "set_tp_destination", requester.getName()); + new PluginMessage(targetPlayerName, PluginMessageType.SET_TP_DESTINATION, requester.getName()).send(requester); } public static void setPlayerDestinationFromTargetPlayer(Player requester, String targetPlayerName) { diff --git a/src/main/java/me/william278/huskhomes2/teleport/TeleportRequest.java b/src/main/java/me/william278/huskhomes2/teleport/TeleportRequest.java index 29952e4d..0f559aaf 100644 --- a/src/main/java/me/william278/huskhomes2/teleport/TeleportRequest.java +++ b/src/main/java/me/william278/huskhomes2/teleport/TeleportRequest.java @@ -8,13 +8,11 @@ public class TeleportRequest { private final String senderName; private final long requestExpiryTime; - private String requestType; + private RequestType requestType; - public TeleportRequest(String senderName, String requestType) { + public TeleportRequest(String senderName, RequestType requestType) { this.senderName = senderName; - if (requestType.equalsIgnoreCase("tpa") || requestType.equalsIgnoreCase("tpahere")) { - this.requestType = requestType.toLowerCase(); - } + this.requestType = requestType; long currentUnixTime = Instant.now().getEpochSecond(); requestExpiryTime = currentUnixTime + HuskHomes.getSettings().getTeleportRequestExpiryTime(); } @@ -23,7 +21,7 @@ public class TeleportRequest { return senderName; } - public String getRequestType() { + public RequestType getRequestType() { return requestType; } @@ -31,4 +29,9 @@ public class TeleportRequest { long currentUnixTime = Instant.now().getEpochSecond(); return currentUnixTime > requestExpiryTime; } -} + + public enum RequestType { + TPA, + TPAHERE + } +} \ No newline at end of file diff --git a/src/main/java/me/william278/huskhomes2/teleport/TeleportRequestHandler.java b/src/main/java/me/william278/huskhomes2/teleport/TeleportRequestHandler.java index 6aaf90ba..30599585 100644 --- a/src/main/java/me/william278/huskhomes2/teleport/TeleportRequestHandler.java +++ b/src/main/java/me/william278/huskhomes2/teleport/TeleportRequestHandler.java @@ -4,8 +4,9 @@ import de.themoep.minedown.MineDown; import me.william278.huskhomes2.CrossServerListHandler; import me.william278.huskhomes2.HuskHomes; import me.william278.huskhomes2.MessageManager; -import me.william278.huskhomes2.PluginMessageHandler; import me.william278.huskhomes2.data.DataManager; +import me.william278.huskhomes2.data.pluginmessage.PluginMessage; +import me.william278.huskhomes2.data.pluginmessage.PluginMessageType; import me.william278.huskhomes2.integrations.VanishChecker; import me.william278.huskhomes2.integrations.VaultIntegration; import me.william278.huskhomes2.teleport.points.RandomPoint; @@ -30,14 +31,20 @@ public class TeleportRequestHandler { // Timestamp identifying when the global player list should be updated next; private static long nextPlayerListUpdateTime = Instant.now().getEpochSecond() + HuskHomes.getSettings().getCrossServerTabUpdateDelay(); - private static void sendTeleportRequestCrossServer(Player requester, String targetPlayerName, String teleportRequestType) { - String pluginMessage = teleportRequestType + "_request"; - PluginMessageHandler.sendPluginMessage(requester, targetPlayerName, pluginMessage, requester.getName()); + private static void sendTeleportRequestCrossServer(Player requester, String targetPlayerName, TeleportRequest.RequestType requestType) { + if (requestType == TeleportRequest.RequestType.TPA) { + new PluginMessage(targetPlayerName, PluginMessageType.TPA_REQUEST, requester.getName()).send(requester); + } else if (requestType == TeleportRequest.RequestType.TPAHERE) { + new PluginMessage(targetPlayerName, PluginMessageType.TPAHERE_REQUEST, requester.getName()).send(requester); + } } - private static void replyTeleportRequestCrossServer(Player replier, String requesterName, String teleportRequestType, boolean accepted) { - String pluginMessage = teleportRequestType + "_request_reply"; - PluginMessageHandler.sendPluginMessage(replier, requesterName, pluginMessage, replier.getName() + ":" + accepted); + private static void replyTeleportRequestCrossServer(Player replier, String requesterName, TeleportRequest.RequestType requestType, boolean accepted) { + if (requestType == TeleportRequest.RequestType.TPA) { + new PluginMessage(requesterName, PluginMessageType.TPA_REQUEST_REPLY, replier.getName(), Boolean.toString(accepted)); + } else if (requestType == TeleportRequest.RequestType.TPAHERE) { + new PluginMessage(requesterName, PluginMessageType.TPAHERE_REQUEST_REPLY, replier.getName(), Boolean.toString(accepted)); + } } private static TextComponent runCommandButton(String buttonText, ChatColor color, String command, String hoverMessage) { @@ -71,7 +78,7 @@ public class TeleportRequestHandler { if (targetPlayer != null) { if (targetPlayer.getUniqueId() != requester.getUniqueId()) { if (!VanishChecker.isVanished(targetPlayer)) { - teleportRequests.put(targetPlayer, new TeleportRequest(requester.getName(), "tpa")); + teleportRequests.put(targetPlayer, new TeleportRequest(requester.getName(), TeleportRequest.RequestType.TPA)); MessageManager.sendMessage(requester, "tpa_request_sent", targetPlayerName); MessageManager.sendMessage(targetPlayer, "tpa_request_ask", requester.getName()); TeleportRequestHandler.sendTpAcceptDenyButtons(targetPlayer); @@ -83,7 +90,7 @@ public class TeleportRequestHandler { } } else { if (HuskHomes.getSettings().doBungee()) { - sendTeleportRequestCrossServer(requester, targetPlayerName, "tpa"); + sendTeleportRequestCrossServer(requester, targetPlayerName, TeleportRequest.RequestType.TPA); MessageManager.sendMessage(requester, "tpa_request_sent", targetPlayerName); } else { MessageManager.sendMessage(requester, "error_player_not_found", targetPlayerName); @@ -95,7 +102,7 @@ public class TeleportRequestHandler { Player targetPlayer = Bukkit.getPlayer(targetPlayerName); if (targetPlayer != null) { if (targetPlayer.getUniqueId() != requester.getUniqueId()) { - teleportRequests.put(targetPlayer, new TeleportRequest(requester.getName(), "tpahere")); + teleportRequests.put(targetPlayer, new TeleportRequest(requester.getName(), TeleportRequest.RequestType.TPAHERE)); MessageManager.sendMessage(requester, "tpahere_request_sent", targetPlayerName); MessageManager.sendMessage(targetPlayer, "tpahere_request_ask", requester.getName()); TeleportRequestHandler.sendTpAcceptDenyButtons(targetPlayer); @@ -104,7 +111,7 @@ public class TeleportRequestHandler { } } else { if (HuskHomes.getSettings().doBungee()) { - sendTeleportRequestCrossServer(requester, targetPlayerName, "tpahere"); + sendTeleportRequestCrossServer(requester, targetPlayerName, TeleportRequest.RequestType.TPAHERE); MessageManager.sendMessage(requester, "tpahere_request_sent", targetPlayerName); } else { MessageManager.sendMessage(requester, "error_player_not_found", targetPlayerName); @@ -119,7 +126,7 @@ public class TeleportRequestHandler { } TeleportRequest teleportRequest = teleportRequests.get(p); String requesterName = teleportRequest.getSenderName(); - String requestType = teleportRequest.getRequestType(); + TeleportRequest.RequestType requestType = teleportRequest.getRequestType(); Player requester = Bukkit.getPlayer(requesterName); if (requester != null) { @@ -127,9 +134,9 @@ public class TeleportRequestHandler { MessageManager.sendMessage(p, "tpa_you_accepted", requesterName); MessageManager.sendMessage(requester, "tpa_has_accepted", p.getName()); - if (requestType.equals("tpa")) { + if (requestType == TeleportRequest.RequestType.TPA) { TeleportManager.queueTimedTeleport(requester, p.getName()); - } else if (requestType.equals("tpahere")) { + } else if (requestType == TeleportRequest.RequestType.TPAHERE) { TeleportManager.queueTimedTeleport(p, requesterName); } } else { @@ -141,10 +148,10 @@ public class TeleportRequestHandler { if (accepted) { MessageManager.sendMessage(p, "tpa_you_accepted", requesterName); - if (requestType.equals("tpa")) { - replyTeleportRequestCrossServer(p, requesterName, "tpa", true); - } else if (requestType.equals("tpahere")) { - replyTeleportRequestCrossServer(p, requesterName, "tpahere", true); + if (requestType == TeleportRequest.RequestType.TPA) { + replyTeleportRequestCrossServer(p, requesterName, TeleportRequest.RequestType.TPA, true); + } else if (requestType == TeleportRequest.RequestType.TPAHERE) { + replyTeleportRequestCrossServer(p, requesterName, TeleportRequest.RequestType.TPAHERE, true); TeleportManager.queueTimedTeleport(p, requesterName); } } else { diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 9a9ef321..6f57d385 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -14,6 +14,7 @@ data_storage_options: database: database_name username: root password: password + params: '?autoReconnect=true&useSSL=false' table_names: player_data: 'huskhomes_player_data' locations_data: 'huskhomes_location_data'