Util Serialize Inventory To String (Remake)

Discussion in 'Resources' started by PhantomUnicorns, Aug 16, 2016.

Thread Status:
Not open for further replies.
  1. Offline

    PhantomUnicorns

    Now I know this isn't a full remake and I only added minor things, but I thought I should share this because it was useful to me. I was making a Custom Enchants plugin when I was trying to save an inventory (long story) so I searched it up, I already knew the basic concept of saving it so there was nothing to learn :p. And found this thread which contained pretty useful information. I had to make it save lore's (with color codes) so I could save my custom enchants with no problem. I also added itemstack to string and string to itemstack functions for single itemstack saving.By the way (btw) this is not my creation the creator is the maker of the thread above (this), with the display name of Phil2812. If any one has any questions I may not respond but feel free to ask, also if you have any adjustments to mine please post it in the comments and I will edit this post and credit that part to you. I also tried to copy the style of Phil2812 for this class so it will look nice and fancy :D.
    Code:
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.Map.Entry;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Material;
    import org.bukkit.enchantments.Enchantment;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    
    public class InventoryStringDeSerializer {
        @SuppressWarnings("deprecation")
        public static String InventoryToString (Inventory invInventory)
        {
          
            String serialization = Math.round(invInventory.getSize()/9) + ";";
            for (int i = 0; i < invInventory.getSize(); i++)
            {
                ItemStack is = invInventory.getItem(i);
                if (is != null)
                {
                    String serializedItemStack = new String();
                 
                    String isType = String.valueOf(is.getType().getId());
                    serializedItemStack += "[email protected]" + isType;
                    boolean hasLore = false;
                 
                    if (is.getDurability() != 0)
                    {
                        String isDurability = String.valueOf(is.getDurability());
                        serializedItemStack += ":[email protected]" + isDurability;
                    }
                 
                    if (is.getAmount() != 1)
                    {
                        String isAmount = String.valueOf(is.getAmount());
                        serializedItemStack += ":[email protected]" + isAmount;
                    }
    
                    if (is.getItemMeta().hasLore())
                    {
                        String isAmount = String.valueOf(is.getItemMeta().getLore().size());
                        serializedItemStack += ":[email protected]" + isAmount;
                        hasLore = true;
                    }
                    else
                    {
                        String isAmount = String.valueOf(0);
                        serializedItemStack += ":[email protected]" + isAmount;
                    }
                  
                    if (hasLore)
                    {
                         for (int k = 0;k<is.getItemMeta().getLore().size();k++) {
                             String isAmount = String.valueOf(is.getItemMeta().getLore().get(k).replaceAll("§", "&"));
                             serializedItemStack += ":l" + (k + 1) + "@" + isAmount;
                         }
                    }
                 
                    Map<Enchantment,Integer> isEnch = is.getEnchantments();
                    if (isEnch.size() > 0)
                    {
                        for (Entry<Enchantment,Integer> ench : isEnch.entrySet())
                        {
                            serializedItemStack += ":[email protected]" + ench.getKey().getId() + "@" + ench.getValue();
                        }
                    }
                 
                    serialization += i + "#" + serializedItemStack + ";";
                }
            }
            return serialization;
        }
     
        @SuppressWarnings("deprecation")
        public static Inventory StringToInventory (String invString)
        {
            String[] serializedBlocks = invString.split(";");
            String invInfo = serializedBlocks[0];
            Inventory deserializedInventory = Bukkit.getServer().createInventory(null, Integer.valueOf(invInfo)*9);
         
            for (int i = 1; i < serializedBlocks.length; i++)
            {
                String[] serializedBlock = serializedBlocks[i].split("#");
                int stackPosition = Integer.valueOf(serializedBlock[0]);
             
                if (stackPosition >= deserializedInventory.getSize())
                {
                    continue;
                }
             
                ItemStack is = null;
                Boolean createdItemStack = false;
             
                String[] serializedItemStack = serializedBlock[1].split(":");
                int amountLore = 0;
                for (String itemInfo : serializedItemStack)
                {
                    String[] itemAttribute = itemInfo.split("@");
                    if (itemAttribute[0].equals("t"))
                    {
                        is = new ItemStack(Material.getMaterial(Integer.valueOf(itemAttribute[1])));
                        createdItemStack = true;
                    }
                    else if (itemAttribute[0].equals("d") && createdItemStack)
                    {
                        is.setDurability(Short.valueOf(itemAttribute[1]));
                    }
                    else if (itemAttribute[0].equals("a") && createdItemStack)
                    {
                        is.setAmount(Integer.valueOf(itemAttribute[1]));
                    }
                    else if (itemAttribute[0].equals("e") && createdItemStack)
                    {
                        is.addEnchantment(Enchantment.getById(Integer.valueOf(itemAttribute[1])), Integer.valueOf(itemAttribute[2]));
                    }
                    else if (itemAttribute[0].equals("la"))
                    {
                        amountLore = Integer.valueOf(itemAttribute[1]);
                    }
                    if (amountLore!=0)
                    {
                        ArrayList<String> lores = new ArrayList<String>();
                        amountLore++;
                        if (is.getItemMeta().hasLore())
                        {
                            lores.addAll(is.getItemMeta().getLore());
                        }
                        for (int k = 0;k<amountLore;k++)
                        {
                            if (itemAttribute[0].equals("l" + (k + 1))) {
                                String isAmount = new String();
                                if (itemAttribute.length>1)
                                {
                                    if (itemAttribute[1] != null)
                                    {
                                        isAmount = String.valueOf(itemAttribute[1]);
                                    }
                                    else
                                    {
                                        isAmount = "";
                                    }
                                }
                                else
                                {
                                    isAmount = "";
                                }
                                lores.add(isAmount.replaceAll("&", "§"));
                            }
                        }
                        ItemMeta itemMeta = is.getItemMeta();
                        itemMeta.setLore(lores);
                        is.setItemMeta(itemMeta);
                    }
                }
                deserializedInventory.setItem(stackPosition, is);
            }
         
            return deserializedInventory;
        }
      
        @SuppressWarnings("deprecation")
        public static String ItemToString (ItemStack item)
        {
            if (item != null)
            {
                String serializedItemStack = new String();
             
                String isType = String.valueOf(item.getType().getId());
                serializedItemStack += "[email protected]" + isType;
                boolean hasLore = false;
             
                if (item.getDurability() != 0)
                {
                    String isDurability = String.valueOf(item.getDurability());
                    serializedItemStack += ":[email protected]" + isDurability;
                }
             
                if (item.getAmount() != 1)
                {
                    String isAmount = String.valueOf(item.getAmount());
                    serializedItemStack += ":[email protected]" + isAmount;
                }
    
                if (item.getItemMeta().hasLore())
                {
                    String isAmount = String.valueOf(item.getItemMeta().getLore().size());
                    serializedItemStack += ":[email protected]" + isAmount;
                    hasLore = true;
                }
                else
                {
                    String isAmount = String.valueOf(0);
                    serializedItemStack += ":[email protected]" + isAmount;
                }
              
                if (hasLore)
                {
                     for (int k = 0;k<item.getItemMeta().getLore().size();k++) {
                         String isAmount = String.valueOf(item.getItemMeta().getLore().get(k).replaceAll("§", "&"));
                         serializedItemStack += ":l" + (k + 1) + "@" + isAmount;
                     }
                }
             
                Map<Enchantment,Integer> isEnch = item.getEnchantments();
                if (isEnch.size() > 0)
                {
                    for (Entry<Enchantment,Integer> ench : isEnch.entrySet())
                    {
                        serializedItemStack += ":[email protected]" + ench.getKey().getId() + "@" + ench.getValue();
                    }
                }
                return serializedItemStack;
            }
            else
            {
                return null;
            }
        }
      
    
        @SuppressWarnings("deprecation")
        public static ItemStack StringToItem (String item)
        {
            if (item!=null)
            {
                if (item.equals(""))
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
            ItemStack is = null;
            Boolean createdItemStack = false;
            String[] serializedItemStack = item.split(":");
         
            int amountLore = 0;
            for (String itemInfo : serializedItemStack)
            {
                String[] itemAttribute = itemInfo.split("@");
                if (itemAttribute[0].equals("t"))
                {
                    is = new ItemStack(Material.getMaterial(Integer.valueOf(itemAttribute[1])));
                    createdItemStack = true;
                }
                else if (itemAttribute[0].equals("d") && createdItemStack)
                {
                    is.setDurability(Short.valueOf(itemAttribute[1]));
                }
                else if (itemAttribute[0].equals("a") && createdItemStack)
                {
                    is.setAmount(Integer.valueOf(itemAttribute[1]));
                }
                else if (itemAttribute[0].equals("e") && createdItemStack)
                {
                    is.addEnchantment(Enchantment.getById(Integer.valueOf(itemAttribute[1])), Integer.valueOf(itemAttribute[2]));
                }
                else if (itemAttribute[0].equals("la"))
                {
                    amountLore = Integer.valueOf(itemAttribute[1]);
                }
                if (amountLore!=0)
                {
                    ArrayList<String> lores = new ArrayList<String>();
                    amountLore++;
                    if (is.getItemMeta().hasLore())
                    {
                        lores.addAll(is.getItemMeta().getLore());
                    }
                    for (int k = 0;k<amountLore;k++)
                    {
                        if (itemAttribute[0].equals("l" + (k + 1))) {
                            String isAmount = new String();
                            if (itemAttribute.length>1)
                            {
                                if (itemAttribute[1] != null)
                                {
                                    isAmount = String.valueOf(itemAttribute[1]);
                                }
                                else
                                {
                                    isAmount = "";
                                }
                            }
                            else
                            {
                                isAmount = "";
                            }
                            lores.add(isAmount.replaceAll("&", "§"));
                        }
                    }
                    ItemMeta itemMeta = is.getItemMeta();
                    itemMeta.setLore(lores);
                    is.setItemMeta(itemMeta);
                }
            }
            if (is!=null)
            {
                return is;
            }
            else
            {
                return null;
            }
        }
    }
    The next but of code is a better version that takes less space and save's more information.
    Code:
    import java.util.ArrayList;
    import java.util.Map.Entry;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Material;
    import org.bukkit.enchantments.Enchantment;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    
    public class InventoryToString {
       
        static String sep = "•";
        static String blockSep = "†";
       
        public static String invToString (Inventory inventory) {
            String serInv = Math.round(inventory.getSize()/9) + blockSep;
            serInv += inventory.getName().replaceAll("§", "&") + blockSep;
            ItemStack[] items = inventory.getContents();
            for (int i = 0;i<Math.round(inventory.getSize()/9)*9;i++) {
                ItemStack item = items[i];
                if (item!=null) {
                    if (item.getType()!=Material.AIR) {
                        serInv += "@w" + sep + i;
                        for (int k = 0;k<Material.values().length;k++)
                            if (Material.values()[k].equals(item.getType())) 
                                serInv += "@m" + sep + k;
                        serInv += "@a" + sep + item.getAmount();
                        if (item.getDurability()!=0)
                            serInv += "@d" + sep + item.getDurability();
                        if (item.hasItemMeta()) {
                                if (item.getItemMeta().hasDisplayName())
                                    serInv += "@dn" + sep + item.getItemMeta().getDisplayName().replaceAll("§", "&");
                            if (item.getItemMeta().hasLore()) {
                                serInv += "@l" + sep + item.getItemMeta().getLore().get(0).replaceAll("§", "&");
                                for (int k = 1;k<item.getItemMeta().getLore().size();k++) {
                                    serInv += sep + item.getItemMeta().getLore().get(k).replaceAll("§", "&");
                                }
                            }
                            if (item.getItemMeta().hasEnchants()) {
                                serInv += "@e" + sep;
                                for (Entry<Enchantment,Integer> ench : item.getEnchantments().entrySet()) {
                                    for (int k = 0;k<Enchantment.values().length;k++) {
                                        if (Enchantment.values()[k].equals(ench.getKey())) {
                                            if (Enchantment.values().length-k>1) {
                                                serInv += k + "<>" + ench.getValue() + sep;
                                            }else {
                                                serInv += k + "<>" + ench.getValue(); 
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        serInv += blockSep;
                    }
                }
            }
            return serInv;
        }
       
        public static Inventory stringToInv (String string) {
            String[] blocks = string.split(blockSep);
            Inventory ser = Bukkit.createInventory(null, Integer.valueOf(blocks[0])*9, blocks[1].replaceAll("&", "§"));
            for (int j = 2;j<blocks.length;j++) {
                String[] itemAttributes = blocks[j].split("@");
                ItemStack item = null;
                int where = 0;
                for (int i = 0;i<itemAttributes.length;i++) {
                    String[] attribute = itemAttributes[i].split(sep);
                    if (attribute[0].equals("w")) {
                        where = Integer.valueOf(attribute[1]);
                    }else if (attribute[0].equals("m")) {
                        item = new ItemStack(Material.values()[Integer.valueOf(attribute[1])], 1);
                    }else if (attribute[0].equals("a")) {
                        item.setAmount(Integer.valueOf(attribute[1]));
                    }else if (attribute[0].equals("d")) {
                        item.setDurability(Short.valueOf(attribute[1]));
                    }else if (attribute[0].equals("dn")) {
                        ItemMeta itemMeta = item.getItemMeta();
                        itemMeta.setDisplayName(attribute[1].replaceAll("&", "§"));
                        item.setItemMeta(itemMeta);
                    }else if (attribute[0].equals("l")) {
                        ItemMeta itemMeta = item.getItemMeta();
                        ArrayList<String> lores = new ArrayList<String>();
                        for (int k = 1;k<attribute.length;k++) {
                            lores.add(attribute[k].replaceAll("&", "§"));
                        }
                        itemMeta.setLore(lores);
                        item.setItemMeta(itemMeta);
                    }else if (attribute[0].equals("e")) {
                        ItemMeta itemMeta = item.getItemMeta();
                        for (int k = 1;k<attribute.length;k++) {
                            String[] spe = attribute[k].split("<>");
                            itemMeta.addEnchant(Enchantment.values()[Integer.valueOf(spe[0])], Integer.valueOf(spe[1]), true);
                        }
                        item.setItemMeta(itemMeta);
                    }
                }
                ser.setItem(where, item);
            }
            return ser;
        }
    }
    
     
    Last edited: Aug 18, 2016
    MCMastery likes this.
  2. Offline

    Zombie_Striker

    @PhantomUnicorns
    Neat idea. However, most of the code is useless, redundant, or can be done better. Most of the limes and methods used can be reduced a lot.
    Being "fancy" is not something you should be focused on, though. It's something nice to have, but considering almost no one will be looking at the code, it is better to have efficient code than fancy code.

    [edit] Just fully read your wall of text. I guess I should direct these comments to him :p.
     
    MCMastery likes this.
  3. Offline

    MCMastery

    Code:
        public static String InventoryToString (Inventory invInventory)
    TRIGGERED :mad::mad::mad::mad::mad::mad::mad::mad:[fire][fire][fire][fire][fire][fire][fire][fire][lava][lava][lava][lava][lava][lava][lava][lava][tnt][tnt][tnt][tnt][tnt][tnt][tnt]

    Cool idea though - I've been having to make my own thingy that does this :p Please don't call it invInventory tho xD
     
    ChipDev likes this.
  4. Offline

    PhantomUnicorns

    Well I tried not to derive from his type of code, and I myself wanted it to be 'fancy'...Am a neat freak XD. If it's not the same all the way through it kills me and I recode the whole plugin/java class. I know that is not the most efficient way of saving an inventory but it works and someone can easily use, I think its great for beginners to look at and learn. I thought about renaming the functions and class but it wouldn't be the same.

    @MCMastery you can change it however you want but I wanted to keep how Phil2812 had it. Don't ask why but I guess it's my way of crediting Phil2812
     
    MCMastery likes this.
Thread Status:
Not open for further replies.

Share This Page