williambriggs

BackpackUtils

Jul 20th, 2022
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.18 KB | None | 0 0
  1. public class BackpackUtils {
  2.  
  3.     public static void storeItems(HashMap<Integer, ItemStack> content, ItemStack item){
  4.         ItemMeta data = item.getItemMeta();
  5.  
  6.         if (content.size() == 0){
  7.             data.getPersistentDataContainer().set(new NamespacedKey(Backpack.getPlugin(), "backpack_id"), PersistentDataType.STRING, "");
  8.             item.setItemMeta(data);
  9.         } else {
  10.             try {
  11.                 ByteArrayOutputStream input = new ByteArrayOutputStream();
  12.                 BukkitObjectOutputStream output = new BukkitObjectOutputStream(input);
  13.  
  14.                 output.writeObject(content.size());
  15.  
  16.                 content.forEach((Integer, ItemStack) -> {
  17.                     try {
  18.                         output.writeObject(content);
  19.                     } catch (IOException ex) {
  20.                         System.out.println(ex);
  21.                     }
  22.                 } );
  23.  
  24.                 output.flush();
  25.  
  26.  
  27.             } catch (IOException ex) {
  28.                 System.out.println(ex);
  29.             }
  30.         }
  31.     }
  32.  
  33.     public static HashMap<Integer, ItemStack> getContents(ItemStack item) {
  34.         PersistentDataContainer data = item.getItemMeta().getPersistentDataContainer();
  35.  
  36.         HashMap<Integer, ItemStack> contents = new HashMap<>();
  37.         String encodedItems = data.get(new NamespacedKey(Backpack.getPlugin(), "Backpack_id"), PersistentDataType.STRING);
  38.  
  39.         try {
  40.             assert encodedItems != null;
  41.             if (!encodedItems.isEmpty()){
  42.             byte[] rawData = Base64.getDecoder().decode(encodedItems);
  43.  
  44.  
  45.                 ByteArrayInputStream io = new ByteArrayInputStream(rawData);
  46.                 BukkitObjectInputStream in = new BukkitObjectInputStream(io);
  47.  
  48.                 int itemsCount = in.readInt();
  49.  
  50.                 for(int i = 0; i < itemsCount; i++){
  51.                     contents.put((Integer) in.readObject(), (ItemStack) in.readObject());
  52.                     in.readObject();
  53.                 }
  54.                 in.close();
  55.             }
  56.         } catch (ClassNotFoundException | IOException | NullPointerException ex) {
  57.             System.out.println(ex);
  58.         }
  59.         return contents;
  60.     }
  61.  
  62. }
Add Comment
Please, Sign In to add comment