Advertisement
PiggiesGoSqueal

StorageHandler.java

Apr 27th, 2019
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.43 KB | None | 0 0
  1. package rip.captain.infinitestorage.storage;
  2.  
  3. import com.mojang.brigadier.exceptions.CommandSyntaxException;
  4. import net.minecraft.server.v1_13_R2.*;
  5. import org.bukkit.*;
  6. import org.bukkit.Material;
  7. import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemStack;
  8. import org.bukkit.entity.Player;
  9. import org.bukkit.inventory.ItemStack;
  10. import org.bukkit.inventory.meta.ItemMeta;
  11. import rip.captain.infinitestorage.configuration.Categories;
  12. import rip.captain.infinitestorage.configuration.Category;
  13. import rip.captain.infinitestorage.configuration.Config;
  14. import rip.captain.infinitestorage.utility.FormatItem;
  15.  
  16. import java.sql.*;
  17. import java.util.*;
  18. import java.util.logging.Level;
  19.  
  20. public class StorageHandler {
  21.  
  22.     Connection mySQLConnection;
  23.  
  24.     public StorageHandler(String hostname, int port) {
  25.         try {
  26.             Bukkit.getLogger().log(Level.INFO, "Connecting to the database '" + ((String) Config.MYSQL_DATABASE.getConfigurationValue()) + "'.");
  27.             if ((Boolean) Config.MYSQL_AUTH.getConfigurationValue()) {
  28.                 mySQLConnection = DriverManager.getConnection("jdbc:mysql://" + hostname + ":" + port + "/" + ((String) Config.MYSQL_DATABASE.getConfigurationValue()) + "?autoReconnect=true", (String) Config.MYSQL_USERNAME.getConfigurationValue(), (String) Config.MYSQL_PASSWORD.getConfigurationValue());
  29.             } else {
  30.                 mySQLConnection = DriverManager.getConnection("jdbc:mysql://" + hostname + ":" + port + "/" + ((String) Config.MYSQL_DATABASE.getConfigurationValue()) + "?user=" + (String) Config.MYSQL_USERNAME.getConfigurationValue() + "?autoReconnect=true");
  31.             }
  32.             //Bukkit.getLogger().log(Level.INFO, "Successfully established a connection to the MySQL server.");
  33.             generateTables();
  34.         } catch (SQLException e) {
  35.             Bukkit.getLogger().log(Level.SEVERE, "Error whilst connecting to the MySQL server!");
  36.             e.printStackTrace();
  37.         }
  38.     }
  39.  
  40.     private void generateTables() {
  41.         try {
  42.             Statement statement = mySQLConnection.createStatement();
  43.             statement.executeUpdate("CREATE TABLE IF NOT EXISTS sort_types(uuid CHAR(36) PRIMARY KEY, sort_type VARCHAR(36));");
  44.             statement.executeUpdate("CREATE TABLE IF NOT EXISTS storage_locations(location VARCHAR(128) PRIMARY KEY, owner_uuid CHAR(36));");
  45.             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;");
  46.             statement.close();
  47.             //Bukkit.getLogger().log(Level.INFO, "Generating default MySQL tables if they do not exist.");
  48.         } catch (SQLException e) {
  49.             e.printStackTrace();
  50.         }
  51.     }
  52.  
  53.     public void setItemAmount(OfflinePlayer player, ItemStack itemStack, int amount) {
  54.         String searchQuery = "UPDATE stored_items SET amount = ? WHERE uuid = ? && name = ? && nbt_data = ?";
  55.         try {
  56.             PreparedStatement preparedStatement = mySQLConnection.prepareStatement(searchQuery);
  57.             preparedStatement.setInt(1, amount);
  58.             preparedStatement.setString(2, player.getUniqueId().toString());
  59.             preparedStatement.setString(3, itemStack.getType().name());
  60.             preparedStatement.setString(4, stringifyNbtTag(itemStack));
  61.             preparedStatement.executeUpdate();
  62.             preparedStatement.close();
  63.             //Bukkit.getLogger().log(Level.INFO, "Successfully updated an item amount from the MySQL database.");
  64.         } catch (SQLException e) {
  65.             Bukkit.getLogger().log(Level.SEVERE, "Failed to updated an item amount from the infinite storage of '" + player.getUniqueId().toString() + "'!");
  66.             e.printStackTrace();
  67.         }
  68.     }
  69.  
  70.     public void purgePlayer(Player player) {
  71.         String searchQuery = "DELETE FROM stored_items WHERE uuid = '" + player.getUniqueId().toString() + "';";
  72.         try {
  73.             Statement statement = mySQLConnection.createStatement();
  74.             statement.executeQuery(searchQuery);
  75.             statement.close();
  76.             //Bukkit.getLogger().log(Level.INFO, "Data purged for player '" + player.getUniqueId().toString() + "'.");
  77.         } catch (SQLException e) {
  78.             Bukkit.getLogger().log(Level.SEVERE, "Error whilst purging the data for '" + player.getUniqueId().toString() + "'!");
  79.         }
  80.     }
  81.  
  82.     public void deleteItem(OfflinePlayer player, ItemStack itemStack) {
  83.         String searchQuery = "DELETE FROM stored_items WHERE uuid = ? && name = ? && nbt_data = ?";
  84.         try {
  85.             PreparedStatement preparedStatement = mySQLConnection.prepareStatement(searchQuery);
  86.             preparedStatement.setString(1, player.getUniqueId().toString());
  87.             preparedStatement.setString(2, itemStack.getType().name());
  88.             preparedStatement.setString(3, stringifyNbtTag(itemStack));
  89.             preparedStatement.executeUpdate();
  90.             preparedStatement.close();
  91.             //Bukkit.getLogger().log(Level.INFO, "Successfully deleted an item from the MySQL database.");
  92.         } catch (SQLException e) {
  93.             Bukkit.getLogger().log(Level.SEVERE, "Failed to delete item from the infinite storage of '" + player.getUniqueId().toString() + "'!");
  94.             e.printStackTrace();
  95.         }
  96.     }
  97.  
  98.     public int getItemAmount(OfflinePlayer player, ItemStack itemStack) {
  99.         String searchQuery = "SELECT amount FROM stored_items WHERE uuid = ? && name = ? && nbt_data = ?";
  100.         try {
  101.             PreparedStatement preparedStatement = mySQLConnection.prepareStatement(searchQuery);
  102.             preparedStatement.setString(1, player.getUniqueId().toString());
  103.             preparedStatement.setString(2, itemStack.getType().name());
  104.             preparedStatement.setString(3, stringifyNbtTag(itemStack));
  105.             preparedStatement.executeQuery();
  106.             ResultSet resultSet = preparedStatement.executeQuery();
  107.             if (resultSet.next()) {
  108.                 return resultSet.getInt("amount");
  109.             }
  110.             return 0;
  111.         } catch (SQLException e) {
  112.             Bukkit.getLogger().log(Level.SEVERE, "Failed to grab item amount from the infinite storage of '" + player.getUniqueId().toString() + "'!");
  113.             e.printStackTrace();
  114.         }
  115.         return 0;
  116.     }
  117.  
  118.     public ItemStack consolidateNbt(ItemStack itemStack) {
  119.         String nbtData = stringifyNbtTag(itemStack);
  120.         return addNbtTag(itemStack, nbtData);
  121.     }
  122.  
  123.     public void switchSortType(Player player) {
  124.  
  125.         SortType sortType = getSortType(player);
  126.  
  127.         switch (sortType) {
  128.             case NORMAL:
  129.                 setSortType(player, SortType.ALPHABETICAL);
  130.                 break;
  131.             case ALPHABETICAL:
  132.                 setSortType(player, SortType.NORMAL);
  133.                 break;
  134.         }
  135.     }
  136.  
  137.     public Map<ItemStack, Integer> retrieveCategoryFromDatabase(OfflinePlayer player, Category category, int page, boolean custom, boolean search, String searchTerm) {
  138.  
  139.         SortType sortType = getSortType(player);
  140.  
  141.         LinkedHashMap<ItemStack, Integer> itemStackAmountMap = new LinkedHashMap<>();
  142.         String searchQuery = "";
  143.  
  144.         if (search) {
  145.              searchQuery = "SELECT * FROM stored_items WHERE has_meta = ? && uuid = ? && full_name REGEXP ? LIMIT 36 OFFSET ?";
  146.         } else {
  147.             if (custom) {
  148.                 if (sortType.equals(SortType.NORMAL)) {
  149.                     searchQuery = "SELECT * FROM stored_items WHERE has_meta = ? && uuid = ? LIMIT 36 OFFSET ?";
  150.                 }
  151.                 if (sortType.equals(SortType.ALPHABETICAL)) {
  152.                     searchQuery = "SELECT * FROM stored_items WHERE has_meta = ? && uuid = ? ORDER BY full_name LIMIT 36 OFFSET ?";
  153.                 }
  154.             } else {
  155.                 if (sortType.equals(SortType.NORMAL)) {
  156.                     searchQuery = "SELECT * FROM stored_items WHERE has_meta = ? && uuid = ? && name in(" + category.getCategoriesSQLString() + ") LIMIT 36 OFFSET ?";
  157.                 }
  158.                 if (sortType.equals(SortType.ALPHABETICAL)) {
  159.                     searchQuery = "SELECT * FROM stored_items WHERE has_meta = ? && uuid = ? && name in(" + category.getCategoriesSQLString() + ") ORDER BY full_name LIMIT 36 OFFSET ?";
  160.                 }
  161.             }
  162.         }
  163.  
  164.         try {
  165.             PreparedStatement preparedStatement = mySQLConnection.prepareStatement(searchQuery);
  166.             preparedStatement.setInt(1, custom ? 1 : 0);
  167.             preparedStatement.setString(2, player.getUniqueId().toString());
  168.             if (search) {
  169.                 preparedStatement.setString(3, "^" + searchTerm + "|[ ]" + searchTerm);
  170.                 preparedStatement.setInt(4, 36 * page);
  171.             } else {
  172.                 preparedStatement.setInt(3, 36 * page);
  173.             }
  174.             ResultSet resultSet = preparedStatement.executeQuery();
  175.  
  176.             while (resultSet.next()) {
  177.                 Material itemMaterial = Material.getMaterial(resultSet.getString("name"));
  178.                 int itemAmount = resultSet.getInt("amount");
  179.  
  180.                 ItemStack finalItem = new ItemStack(itemMaterial);
  181.  
  182.                 finalItem = addNbtTag(finalItem, resultSet.getString("nbt_data"));
  183.  
  184.                 itemStackAmountMap.put(finalItem, itemAmount);
  185.             }
  186.  
  187.         } catch (SQLException e) {
  188.             Bukkit.getLogger().log(Level.SEVERE, "Failed to grab items from the infinite storage of '" + player.getUniqueId().toString() + "'!");
  189.             e.printStackTrace();
  190.         }
  191.         return itemStackAmountMap;
  192.     }
  193.  
  194.     private String stringifyLocation(Location location) {
  195.         String stringLocation = "";
  196.         stringLocation += location.getBlockX() + ",";
  197.         stringLocation += location.getBlockY() + ",";
  198.         stringLocation += location.getBlockZ() + ",";
  199.         stringLocation += location.getWorld().getName();
  200.         return stringLocation;
  201.     }
  202.  
  203.     private Location deserializeLocation(String locationString) {
  204.         String[] locationSplit = locationString.split(",");
  205.         return new Location(Bukkit.getWorld(locationSplit[3]), Integer.parseInt(locationSplit[0]), Integer.parseInt(locationSplit[1]), Integer.parseInt(locationSplit[2]));
  206.     }
  207.  
  208.     private List<String> toNotAddNbt = Arrays.asList("display");
  209.  
  210.     private ItemStack addNbtTag(ItemStack itemStack, String nbtTagString) {
  211.  
  212.         if (nbtTagString.length() <= 0) {
  213.             return itemStack;
  214.         }
  215.  
  216.         net.minecraft.server.v1_13_R2.ItemStack nmsItemStack = CraftItemStack.asNMSCopy(itemStack);
  217.  
  218.         try {
  219.             nmsItemStack.setTag(MojangsonParser.parse(nbtTagString));
  220.         } catch (CommandSyntaxException e) {
  221.             e.printStackTrace();
  222.         }
  223.  
  224.         return CraftItemStack.asBukkitCopy(nmsItemStack);
  225.     }
  226.  
  227.     private String stringifyNbtTag(ItemStack itemStack) {
  228.         net.minecraft.server.v1_13_R2.ItemStack nmsItemStack = CraftItemStack.asNMSCopy(itemStack);
  229.  
  230.         if (nmsItemStack.hasTag()) {
  231.             NBTTagCompound nbtTagCompound = nmsItemStack.getTag();
  232.  
  233.             return nbtTagCompound.toString();
  234.         }
  235.         return "";
  236.     }
  237.  
  238.     public String getOwner(Location location) {
  239.         String searchQuery = "SELECT * FROM storage_locations WHERE location = '" + stringifyLocation(location) + "';";
  240.         try {
  241.             Statement statement = mySQLConnection.createStatement();
  242.             ResultSet resultSet = statement.executeQuery(searchQuery);
  243.             if (resultSet.next()) {
  244.                 return resultSet.getString("owner_uuid");
  245.             } else {
  246.                 return null;
  247.             }
  248.         } catch (SQLException e) {
  249.             Bukkit.getLogger().log(Level.SEVERE, "Error whilst grabbing owner of block.");
  250.             e.printStackTrace();
  251.         }
  252.         return null;
  253.     }
  254.  
  255.     public boolean deleteLocation(Location location) {
  256.         String deleteQuery = "DELETE FROM storage_locations WHERE location = '" + stringifyLocation(location) + "';";
  257.         try {
  258.             Statement statement = mySQLConnection.createStatement();
  259.             statement.executeUpdate(deleteQuery);
  260.             statement.close();
  261.             //Bukkit.getLogger().log(Level.INFO, "Successfully deleted a location.");
  262.             return true;
  263.         } catch (SQLException e) {
  264.             Bukkit.getLogger().log(Level.SEVERE, "Error whilst deleting a location.");
  265.             e.printStackTrace();
  266.         }
  267.         return false;
  268.     }
  269.  
  270.     public void storeLocation(Player player, Location location) {
  271.         String storeQuery = "INSERT INTO storage_locations (location, owner_uuid) VALUES (?, ?);";
  272.         try {
  273.             PreparedStatement preparedStatement = mySQLConnection.prepareStatement(storeQuery);
  274.             preparedStatement.setString(1, stringifyLocation(location));
  275.             preparedStatement.setString(2, player.getUniqueId().toString());
  276.             preparedStatement.executeUpdate();
  277.             //Bukkit.getLogger().log(Level.INFO, "Location stored in the MySQL database.");
  278.         } catch (SQLException e) {
  279.             Bukkit.getLogger().log(Level.SEVERE, "Error whilst storing infinite storage block location!");
  280.             e.printStackTrace();
  281.         }
  282.     }
  283.  
  284.     private String getName(ItemStack item) {
  285.         if(item == null)
  286.             return null;
  287.  
  288.         //Make sure the item doesn't have a custom display name set
  289.         final ItemMeta im = item.getItemMeta();
  290.         if(im != null && im.getDisplayName() != null && im.getDisplayName() != "")
  291.             return ChatColor.stripColor(im.getDisplayName());
  292.  
  293.         //Grab the material we're using for the name
  294.         final Material material = item.getType();
  295.  
  296.         //Format to proper label: "Stone Bricks" instead of STONE_BRICKS
  297.         StringBuilder builder = new StringBuilder();
  298.         for(String word : material.toString().split("_"))
  299.             builder.append(word.substring(0, 1).toLowerCase() + word.substring(1).toLowerCase() + " ");
  300.  
  301.         //Trim the string, and also return it
  302.         return builder.toString().trim().toLowerCase();
  303.     }
  304.  
  305.     public void setSortType(Player player, SortType sortType) {
  306.         try {
  307.             PreparedStatement preparedStatement = mySQLConnection.prepareStatement("INSERT INTO sort_types (uuid, sort_type) VALUES (?, ?) ON DUPLICATE KEY UPDATE sort_type = ?");
  308.             preparedStatement.setString(1, player.getUniqueId().toString());
  309.             preparedStatement.setString(2, sortType.name());
  310.             preparedStatement.setString(3, sortType.name());
  311.             preparedStatement.executeUpdate();
  312.             preparedStatement.close();
  313.             //Bukkit.getLogger().log(Level.INFO, "Set the sort type of '" + player.getUniqueId().toString() + "' to " + sortType.name() + " in the database.");
  314.         } catch (SQLException e) {
  315.             Bukkit.getLogger().log(Level.SEVERE, "Error whilst setting the sort type of '" + player.getUniqueId().toString() + "'!");
  316.             e.printStackTrace();
  317.         }
  318.     }
  319.  
  320.     public SortType getSortType(OfflinePlayer player) {
  321.         try {
  322.             PreparedStatement preparedStatement = mySQLConnection.prepareStatement("SELECT sort_type FROM sort_types WHERE uuid = ?");
  323.             preparedStatement.setString(1, player.getUniqueId().toString());
  324.             ResultSet resultSet = preparedStatement.executeQuery();
  325.             if (resultSet.next()) {
  326.                 return SortType.valueOf(resultSet.getString("sort_type"));
  327.             }
  328.         } catch (SQLException e) {
  329.             e.printStackTrace();
  330.         }
  331.         return SortType.NORMAL;
  332.     }
  333.  
  334.     public void storeItemsInDatabase(Player player, ItemStack... itemStacks) {
  335.         for (ItemStack itemStack : itemStacks) {
  336.             String itemName = getName(itemStack);
  337.             ItemStack consolidatedItemStack = consolidateNbt(itemStack);
  338.             int hasMeta = 0;
  339.             String storeQuery = "INSERT INTO stored_items (uuid, name, amount, nbt_data, has_meta, full_name) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE amount = amount + " + consolidatedItemStack.getAmount();
  340.             if (consolidatedItemStack.hasItemMeta()) {
  341.                 if (consolidatedItemStack.getItemMeta().hasDisplayName() || consolidatedItemStack.getItemMeta().hasLore()) {
  342.                     hasMeta = 1;
  343.                 }
  344.             }
  345.             try {
  346.                 PreparedStatement preparedStatement = mySQLConnection.prepareStatement(storeQuery);
  347.                 preparedStatement.setString(1, player.getUniqueId().toString());
  348.                 preparedStatement.setString(2, consolidatedItemStack.getType().name());
  349.                 preparedStatement.setInt(3, consolidatedItemStack.getAmount());
  350.                 preparedStatement.setString(4, stringifyNbtTag(consolidatedItemStack));
  351.                 preparedStatement.setInt(5, hasMeta);
  352.                 preparedStatement.setString(6, itemName != null ? itemName : "");
  353.                 preparedStatement.execute();
  354.                 preparedStatement.close();
  355.                 //Bukkit.getLogger().log(Level.INFO, "Item successfully stored in the MySQL database.");
  356.             } catch (SQLException e) {
  357.                 Bukkit.getLogger().log(Level.SEVERE, "Error whilst storing items in the database for the player '" + player.getUniqueId().toString() + "'!");
  358.                 e.printStackTrace();
  359.             }
  360.         }
  361.     }
  362. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement