Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package rip.captain.infinitestorage.storage;
- import com.mojang.brigadier.exceptions.CommandSyntaxException;
- import net.minecraft.server.v1_13_R2.*;
- import org.bukkit.*;
- import org.bukkit.Material;
- import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemStack;
- import org.bukkit.entity.Player;
- import org.bukkit.inventory.ItemStack;
- import org.bukkit.inventory.meta.ItemMeta;
- import rip.captain.infinitestorage.configuration.Categories;
- import rip.captain.infinitestorage.configuration.Category;
- import rip.captain.infinitestorage.configuration.Config;
- import rip.captain.infinitestorage.utility.FormatItem;
- import java.sql.*;
- import java.util.*;
- import java.util.logging.Level;
- public class StorageHandler {
- Connection mySQLConnection;
- public StorageHandler(String hostname, int port) {
- try {
- Bukkit.getLogger().log(Level.INFO, "Connecting to the database '" + ((String) Config.MYSQL_DATABASE.getConfigurationValue()) + "'.");
- if ((Boolean) Config.MYSQL_AUTH.getConfigurationValue()) {
- mySQLConnection = DriverManager.getConnection("jdbc:mysql://" + hostname + ":" + port + "/" + ((String) Config.MYSQL_DATABASE.getConfigurationValue()) + "?autoReconnect=true", (String) Config.MYSQL_USERNAME.getConfigurationValue(), (String) Config.MYSQL_PASSWORD.getConfigurationValue());
- } else {
- mySQLConnection = DriverManager.getConnection("jdbc:mysql://" + hostname + ":" + port + "/" + ((String) Config.MYSQL_DATABASE.getConfigurationValue()) + "?user=" + (String) Config.MYSQL_USERNAME.getConfigurationValue() + "?autoReconnect=true");
- }
- //Bukkit.getLogger().log(Level.INFO, "Successfully established a connection to the MySQL server.");
- generateTables();
- } catch (SQLException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Error whilst connecting to the MySQL server!");
- e.printStackTrace();
- }
- }
- private void generateTables() {
- try {
- Statement statement = mySQLConnection.createStatement();
- statement.executeUpdate("CREATE TABLE IF NOT EXISTS sort_types(uuid CHAR(36) PRIMARY KEY, sort_type VARCHAR(36));");
- statement.executeUpdate("CREATE TABLE IF NOT EXISTS storage_locations(location VARCHAR(128) PRIMARY KEY, owner_uuid CHAR(36));");
- statement.executeUpdate("CREATE TABLE IF NOT EXISTS stored_items(uuid CHAR(36), name VARCHAR(128), amount INT, nbt_data VARCHAR(604), has_meta TINYINT(1), full_name VARCHAR(128), UNIQUE KEY item_identify (uuid, name, nbt_data)) ENGINE=InnoDB;");
- statement.close();
- //Bukkit.getLogger().log(Level.INFO, "Generating default MySQL tables if they do not exist.");
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public void setItemAmount(OfflinePlayer player, ItemStack itemStack, int amount) {
- String searchQuery = "UPDATE stored_items SET amount = ? WHERE uuid = ? && name = ? && nbt_data = ?";
- try {
- PreparedStatement preparedStatement = mySQLConnection.prepareStatement(searchQuery);
- preparedStatement.setInt(1, amount);
- preparedStatement.setString(2, player.getUniqueId().toString());
- preparedStatement.setString(3, itemStack.getType().name());
- preparedStatement.setString(4, stringifyNbtTag(itemStack));
- preparedStatement.executeUpdate();
- preparedStatement.close();
- //Bukkit.getLogger().log(Level.INFO, "Successfully updated an item amount from the MySQL database.");
- } catch (SQLException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Failed to updated an item amount from the infinite storage of '" + player.getUniqueId().toString() + "'!");
- e.printStackTrace();
- }
- }
- public void purgePlayer(Player player) {
- String searchQuery = "DELETE FROM stored_items WHERE uuid = '" + player.getUniqueId().toString() + "';";
- try {
- Statement statement = mySQLConnection.createStatement();
- statement.executeQuery(searchQuery);
- statement.close();
- //Bukkit.getLogger().log(Level.INFO, "Data purged for player '" + player.getUniqueId().toString() + "'.");
- } catch (SQLException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Error whilst purging the data for '" + player.getUniqueId().toString() + "'!");
- }
- }
- public void deleteItem(OfflinePlayer player, ItemStack itemStack) {
- String searchQuery = "DELETE FROM stored_items WHERE uuid = ? && name = ? && nbt_data = ?";
- try {
- PreparedStatement preparedStatement = mySQLConnection.prepareStatement(searchQuery);
- preparedStatement.setString(1, player.getUniqueId().toString());
- preparedStatement.setString(2, itemStack.getType().name());
- preparedStatement.setString(3, stringifyNbtTag(itemStack));
- preparedStatement.executeUpdate();
- preparedStatement.close();
- //Bukkit.getLogger().log(Level.INFO, "Successfully deleted an item from the MySQL database.");
- } catch (SQLException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Failed to delete item from the infinite storage of '" + player.getUniqueId().toString() + "'!");
- e.printStackTrace();
- }
- }
- public int getItemAmount(OfflinePlayer player, ItemStack itemStack) {
- String searchQuery = "SELECT amount FROM stored_items WHERE uuid = ? && name = ? && nbt_data = ?";
- try {
- PreparedStatement preparedStatement = mySQLConnection.prepareStatement(searchQuery);
- preparedStatement.setString(1, player.getUniqueId().toString());
- preparedStatement.setString(2, itemStack.getType().name());
- preparedStatement.setString(3, stringifyNbtTag(itemStack));
- preparedStatement.executeQuery();
- ResultSet resultSet = preparedStatement.executeQuery();
- if (resultSet.next()) {
- return resultSet.getInt("amount");
- }
- return 0;
- } catch (SQLException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Failed to grab item amount from the infinite storage of '" + player.getUniqueId().toString() + "'!");
- e.printStackTrace();
- }
- return 0;
- }
- public ItemStack consolidateNbt(ItemStack itemStack) {
- String nbtData = stringifyNbtTag(itemStack);
- return addNbtTag(itemStack, nbtData);
- }
- public void switchSortType(Player player) {
- SortType sortType = getSortType(player);
- switch (sortType) {
- case NORMAL:
- setSortType(player, SortType.ALPHABETICAL);
- break;
- case ALPHABETICAL:
- setSortType(player, SortType.NORMAL);
- break;
- }
- }
- public Map<ItemStack, Integer> retrieveCategoryFromDatabase(OfflinePlayer player, Category category, int page, boolean custom, boolean search, String searchTerm) {
- SortType sortType = getSortType(player);
- LinkedHashMap<ItemStack, Integer> itemStackAmountMap = new LinkedHashMap<>();
- String searchQuery = "";
- if (search) {
- searchQuery = "SELECT * FROM stored_items WHERE has_meta = ? && uuid = ? && full_name REGEXP ? LIMIT 36 OFFSET ?";
- } else {
- if (custom) {
- if (sortType.equals(SortType.NORMAL)) {
- searchQuery = "SELECT * FROM stored_items WHERE has_meta = ? && uuid = ? LIMIT 36 OFFSET ?";
- }
- if (sortType.equals(SortType.ALPHABETICAL)) {
- searchQuery = "SELECT * FROM stored_items WHERE has_meta = ? && uuid = ? ORDER BY full_name LIMIT 36 OFFSET ?";
- }
- } else {
- if (sortType.equals(SortType.NORMAL)) {
- searchQuery = "SELECT * FROM stored_items WHERE has_meta = ? && uuid = ? && name in(" + category.getCategoriesSQLString() + ") LIMIT 36 OFFSET ?";
- }
- if (sortType.equals(SortType.ALPHABETICAL)) {
- searchQuery = "SELECT * FROM stored_items WHERE has_meta = ? && uuid = ? && name in(" + category.getCategoriesSQLString() + ") ORDER BY full_name LIMIT 36 OFFSET ?";
- }
- }
- }
- try {
- PreparedStatement preparedStatement = mySQLConnection.prepareStatement(searchQuery);
- preparedStatement.setInt(1, custom ? 1 : 0);
- preparedStatement.setString(2, player.getUniqueId().toString());
- if (search) {
- preparedStatement.setString(3, "^" + searchTerm + "|[ ]" + searchTerm);
- preparedStatement.setInt(4, 36 * page);
- } else {
- preparedStatement.setInt(3, 36 * page);
- }
- ResultSet resultSet = preparedStatement.executeQuery();
- while (resultSet.next()) {
- Material itemMaterial = Material.getMaterial(resultSet.getString("name"));
- int itemAmount = resultSet.getInt("amount");
- ItemStack finalItem = new ItemStack(itemMaterial);
- finalItem = addNbtTag(finalItem, resultSet.getString("nbt_data"));
- itemStackAmountMap.put(finalItem, itemAmount);
- }
- } catch (SQLException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Failed to grab items from the infinite storage of '" + player.getUniqueId().toString() + "'!");
- e.printStackTrace();
- }
- return itemStackAmountMap;
- }
- private String stringifyLocation(Location location) {
- String stringLocation = "";
- stringLocation += location.getBlockX() + ",";
- stringLocation += location.getBlockY() + ",";
- stringLocation += location.getBlockZ() + ",";
- stringLocation += location.getWorld().getName();
- return stringLocation;
- }
- private Location deserializeLocation(String locationString) {
- String[] locationSplit = locationString.split(",");
- return new Location(Bukkit.getWorld(locationSplit[3]), Integer.parseInt(locationSplit[0]), Integer.parseInt(locationSplit[1]), Integer.parseInt(locationSplit[2]));
- }
- private List<String> toNotAddNbt = Arrays.asList("display");
- private ItemStack addNbtTag(ItemStack itemStack, String nbtTagString) {
- if (nbtTagString.length() <= 0) {
- return itemStack;
- }
- net.minecraft.server.v1_13_R2.ItemStack nmsItemStack = CraftItemStack.asNMSCopy(itemStack);
- try {
- nmsItemStack.setTag(MojangsonParser.parse(nbtTagString));
- } catch (CommandSyntaxException e) {
- e.printStackTrace();
- }
- return CraftItemStack.asBukkitCopy(nmsItemStack);
- }
- private String stringifyNbtTag(ItemStack itemStack) {
- net.minecraft.server.v1_13_R2.ItemStack nmsItemStack = CraftItemStack.asNMSCopy(itemStack);
- if (nmsItemStack.hasTag()) {
- NBTTagCompound nbtTagCompound = nmsItemStack.getTag();
- return nbtTagCompound.toString();
- }
- return "";
- }
- public String getOwner(Location location) {
- String searchQuery = "SELECT * FROM storage_locations WHERE location = '" + stringifyLocation(location) + "';";
- try {
- Statement statement = mySQLConnection.createStatement();
- ResultSet resultSet = statement.executeQuery(searchQuery);
- if (resultSet.next()) {
- return resultSet.getString("owner_uuid");
- } else {
- return null;
- }
- } catch (SQLException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Error whilst grabbing owner of block.");
- e.printStackTrace();
- }
- return null;
- }
- public boolean deleteLocation(Location location) {
- String deleteQuery = "DELETE FROM storage_locations WHERE location = '" + stringifyLocation(location) + "';";
- try {
- Statement statement = mySQLConnection.createStatement();
- statement.executeUpdate(deleteQuery);
- statement.close();
- //Bukkit.getLogger().log(Level.INFO, "Successfully deleted a location.");
- return true;
- } catch (SQLException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Error whilst deleting a location.");
- e.printStackTrace();
- }
- return false;
- }
- public void storeLocation(Player player, Location location) {
- String storeQuery = "INSERT INTO storage_locations (location, owner_uuid) VALUES (?, ?);";
- try {
- PreparedStatement preparedStatement = mySQLConnection.prepareStatement(storeQuery);
- preparedStatement.setString(1, stringifyLocation(location));
- preparedStatement.setString(2, player.getUniqueId().toString());
- preparedStatement.executeUpdate();
- //Bukkit.getLogger().log(Level.INFO, "Location stored in the MySQL database.");
- } catch (SQLException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Error whilst storing infinite storage block location!");
- e.printStackTrace();
- }
- }
- private String getName(ItemStack item) {
- if(item == null)
- return null;
- //Make sure the item doesn't have a custom display name set
- final ItemMeta im = item.getItemMeta();
- if(im != null && im.getDisplayName() != null && im.getDisplayName() != "")
- return ChatColor.stripColor(im.getDisplayName());
- //Grab the material we're using for the name
- final Material material = item.getType();
- //Format to proper label: "Stone Bricks" instead of STONE_BRICKS
- StringBuilder builder = new StringBuilder();
- for(String word : material.toString().split("_"))
- builder.append(word.substring(0, 1).toLowerCase() + word.substring(1).toLowerCase() + " ");
- //Trim the string, and also return it
- return builder.toString().trim().toLowerCase();
- }
- public void setSortType(Player player, SortType sortType) {
- try {
- PreparedStatement preparedStatement = mySQLConnection.prepareStatement("INSERT INTO sort_types (uuid, sort_type) VALUES (?, ?) ON DUPLICATE KEY UPDATE sort_type = ?");
- preparedStatement.setString(1, player.getUniqueId().toString());
- preparedStatement.setString(2, sortType.name());
- preparedStatement.setString(3, sortType.name());
- preparedStatement.executeUpdate();
- preparedStatement.close();
- //Bukkit.getLogger().log(Level.INFO, "Set the sort type of '" + player.getUniqueId().toString() + "' to " + sortType.name() + " in the database.");
- } catch (SQLException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Error whilst setting the sort type of '" + player.getUniqueId().toString() + "'!");
- e.printStackTrace();
- }
- }
- public SortType getSortType(OfflinePlayer player) {
- try {
- PreparedStatement preparedStatement = mySQLConnection.prepareStatement("SELECT sort_type FROM sort_types WHERE uuid = ?");
- preparedStatement.setString(1, player.getUniqueId().toString());
- ResultSet resultSet = preparedStatement.executeQuery();
- if (resultSet.next()) {
- return SortType.valueOf(resultSet.getString("sort_type"));
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return SortType.NORMAL;
- }
- public void storeItemsInDatabase(Player player, ItemStack... itemStacks) {
- for (ItemStack itemStack : itemStacks) {
- String itemName = getName(itemStack);
- ItemStack consolidatedItemStack = consolidateNbt(itemStack);
- int hasMeta = 0;
- String storeQuery = "INSERT INTO stored_items (uuid, name, amount, nbt_data, has_meta, full_name) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE amount = amount + " + consolidatedItemStack.getAmount();
- if (consolidatedItemStack.hasItemMeta()) {
- if (consolidatedItemStack.getItemMeta().hasDisplayName() || consolidatedItemStack.getItemMeta().hasLore()) {
- hasMeta = 1;
- }
- }
- try {
- PreparedStatement preparedStatement = mySQLConnection.prepareStatement(storeQuery);
- preparedStatement.setString(1, player.getUniqueId().toString());
- preparedStatement.setString(2, consolidatedItemStack.getType().name());
- preparedStatement.setInt(3, consolidatedItemStack.getAmount());
- preparedStatement.setString(4, stringifyNbtTag(consolidatedItemStack));
- preparedStatement.setInt(5, hasMeta);
- preparedStatement.setString(6, itemName != null ? itemName : "");
- preparedStatement.execute();
- preparedStatement.close();
- //Bukkit.getLogger().log(Level.INFO, "Item successfully stored in the MySQL database.");
- } catch (SQLException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Error whilst storing items in the database for the player '" + player.getUniqueId().toString() + "'!");
- e.printStackTrace();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement