Solved Chest GUI Plugin

Discussion in 'Plugin Development' started by mateo226, Mar 12, 2015.

Thread Status:
Not open for further replies.
  1. Hello everyone! I want to create a /chest plugin which opens a virtual chest for a player IF he has a permission for it. I don't think this is too hard to do, but how would I implement saving and loading chests? Maybe making a new file for each new player with a permissions to /chest.... I might also need to make more than 1 chest per player.... Can someone show me how I could save/load my chests? Thank you!
     
  2. Offline

    ProMCKingz

  3. @ProMCKingz Thanks, I will check it out.

    @ProMCKingz Hey, I did what the post said but it doesn't work.... It doesn't save anything at all :( It doesn't even open the inv :( Here is my code maybe you can take a look at it:
    Code:
    public class Main extends JavaPlugin implements Listener {
    
        public final Logger logger = Bukkit.getServer().getLogger();
        public static Player p;
        private static Inventory inv;
        @Override
        public void onEnable() {
            this.getServer().getPluginManager().registerEvents(this, this);
    
        }
    
        @Override
        public void onDisable() {
    
        }
    
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String t,
                String[] args) {
            if (!(sender instanceof Player))
                return true;
            this.p = (Player) sender;
    
            if (cmd.getName().equalsIgnoreCase("chest")
                    && p.hasPermission("chest.use.one")) {
    
                inv = Bukkit.getServer().createInventory(p, 54,
                        "Private Chest");
                inv = getInventoryFromFile(new File("APChests/" + p.getName()), inv);
                p.openInventory(inv);
            }
            if (cmd.getName().equalsIgnoreCase("saveChest")){
                saveInventoryToFile(inv, new File("APChests/"), p.getName());
            }
    
            return false;
        }
    
        public static Inventory getInventoryFromFile(File file, Inventory inv) {
            if (file == null)
                return null;
            if (!file.exists() || file.isDirectory()
                    || !file.getAbsolutePath().endsWith(".invsave")) {
                saveInventoryToFile(inv, new File("APChests/"), p.getName());
            }
            ;
            try {
                FileConfiguration invConfig = YamlConfiguration
                        .loadConfiguration(file);
                Inventory inventory = null;
                String invTitle = invConfig.getString("Title", "Inventory");
                int invSize = invConfig.getInt("Size", 27);
                int invMaxStackSize = invConfig.getInt("Max stack size", 64);
                InventoryHolder invHolder = null;
                if (invConfig.contains("Holder"))
                    invHolder = Bukkit.getPlayer(invConfig.getString("Holder"));
                inventory = Bukkit.getServer().createInventory(invHolder, invSize,
                        ChatColor.translateAlternateColorCodes('&', invTitle));
                inventory.setMaxStackSize(invMaxStackSize);
                try {
                    ItemStack[] invContents = new ItemStack[invSize];
                    for (int i = 0; i < invSize; i++) {
                        if (invConfig.contains("Slot " + i))
                            invContents[i] = invConfig.getItemStack("Slot " + i);
                        else
                            invContents[i] = new ItemStack(Material.AIR);
                    }
                    inventory.setContents(invContents);
                } catch (Exception ex) {
                }
                return inventory;
            } catch (Exception ex) {
                return null;
            }
        }
    
        public static boolean saveInventoryToFile(Inventory inventory, File path,
                String fileName) {
            if (inventory == null || path == null || fileName == null)
                return false;
            try {
                File invFile = new File(path, fileName + ".invsave");
                if (invFile.exists())
                    invFile.delete();
                FileConfiguration invConfig = YamlConfiguration
                        .loadConfiguration(invFile);
    
                invConfig.set("Title", inventory.getTitle());
                invConfig.set("Size", inventory.getSize());
                invConfig.set("Max stack size", inventory.getMaxStackSize());
                if (inventory.getHolder() instanceof Player)
                    invConfig.set("Holder",
                            ((Player) inventory.getHolder()).getName());
    
                ItemStack[] invContents = inventory.getContents();
                for (int i = 0; i < invContents.length; i++) {
                    ItemStack itemInInv = invContents[i];
                    if (itemInInv != null)
                        if (itemInInv.getType() != Material.AIR)
                            invConfig.set("Slot " + i, itemInInv);
                }
    
                invConfig.save(invFile);
                return true;
            } catch (Exception ex) {
                return false;
            }
        }
    
    }
    
    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 13, 2016
  4. Offline

    Funergy

  5. @Funergy Nope, no error :( But none of the commands work! Not even /chest or /savechest
     
  6. Offline

    teej107

    @mateo226 Did you put those commands in your plugin.yml?
     
  7. @teej107 Yes I did....

    @teej107 I just realised it had something to do with the permissions... Now the problem is that when I open the /chest, put something in it and close it it is empty! :(

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 13, 2016
  8. Offline

    Funergy

    @mateo226 Put something in it. Use a InventoryCloseEvent and check if it is the private chest. then just put the save method in there for testing purposes when closing it check the config. if nothing is in there your saving is wrong

    and btw.
    Code:
    private static Inventory inv;
    Will not work. Just create a new inventory in the onCommand
    Code:
    Inventory inv = Bukkit.getServer().createInventory(p, 54,
                        "Private Chest");
                inv = getInventoryFromFile(new File("APChests/" + p.getName()), inv);
    It would also be great if you put the whole inventory in a HashMap linked with the UUID of the player.
    Code:
    public HashMap<UUID,Inventory> invList = new HashMap<>();
    So you wont need to use the config too much. Its called a SLAPI
    Save Load API
    You save on disable, you load in the onEnable. You may use a runnable too save it regularly because if the server crashes the chests will rollback.

    For the loading get all the "player_<UUID>" files Don't use Player names. But I also don't know if it has a max length of a file. So you will need to search that on google.
    You will need to use split and check if the name of the file begins with "player".
    Then use a for loop and create new inventories and put them in the HashMap with the provided UUID from the name of the file.

    And in the save method, loop through the HashMap and get they're uuid. With the UUID you will be able to get the file. Then just save the inventory :p.

    This is just some information I wanted to tell you.

    **I may edit this a bit if I wrote something wrong**
     
  9. @Funergy HEy thanks, I will try and do something like that now :) BTW, do you by any chance have Skype in case I find an error so I don't spam this thread?
     
  10. Offline

    Funergy

    @mateo226 Skype is not allowed on the Bukkit forums
     
  11. @Funergy Oh ok, didn't know that :)

    @Funergy I am sorry but I am just lost now.... I posted my code below and ANY example using my code would be great! Thank you very much for helping me! PS: I am pretty new to this so... I do need help sometimes...
    Code:
    public class Main extends JavaPlugin implements Listener {
    
        public final Logger logger = Bukkit.getServer().getLogger();
        public static Player p;
        private static Inventory inv;
        public HashMap<UUID,Inventory> invList = new HashMap<>();
    
        @Override
        public void onEnable() {
            this.getServer().getPluginManager().registerEvents(this, this);
    
        }
    
        @Override
        public void onDisable() {
    
        }
    
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String t,
                String[] args) {
            if (!(sender instanceof Player))
                return true;
            this.p = (Player) sender;
    
            if (cmd.getName().equalsIgnoreCase("chest")
                    && p.hasPermission("chest.use.one")) {
    
                File playerSave = new File("plugins/APChests/" + p.getName());
                inv = Bukkit.getServer().createInventory(p, 54, "Private Chest");
                if (new File("plugins/APChests/" + p.getName() + ".invsave")
                        .exists()) {
                    inv = getInventoryFromFile(playerSave, inv);
                    p.sendMessage("The /chest file for you exists, opening it!");
                } else {
                    saveInventoryToFile(inv, new File("plugins/APChests/"),
                            p.getName());
                    p.sendMessage("The /chest file for you doesn't exist, creating it!");
                }
    
                p.openInventory(inv);
    
            }
            if (cmd.getName().equalsIgnoreCase("saveChest")) {
                // I know you said I should use this on disable/enable but I am doing it here for testing...
                for (Entry<UUID,Inventory> : invList.entrySet()) {
                 
                }
            }
    
            return false;
        }
    
        public static Inventory getInventoryFromFile(File file, Inventory inv) {
            if (file == null)
                return null;
            if (!file.exists() || file.isDirectory()
                    || !file.getAbsolutePath().endsWith(".invsave")) {
                saveInventoryToFile(inv, new File("plugins/APChests/"), p.getName());
            }
            ;
            try {
                FileConfiguration invConfig = YamlConfiguration
                        .loadConfiguration(file);
                Inventory inventory = null;
                String invTitle = invConfig.getString("Title", "Inventory");
                int invSize = invConfig.getInt("Size", 27);
                int invMaxStackSize = invConfig.getInt("Max stack size", 64);
                InventoryHolder invHolder = null;
                if (invConfig.contains("Holder"))
                    invHolder = Bukkit.getPlayer(invConfig.getString("Holder"));
                inventory = Bukkit.getServer().createInventory(invHolder, invSize,
                        ChatColor.translateAlternateColorCodes('&', invTitle));
                inventory.setMaxStackSize(invMaxStackSize);
                try {
                    ItemStack[] invContents = new ItemStack[invSize];
                    for (int i = 0; i < invSize; i++) {
                        if (invConfig.contains("Slot " + i))
                            invContents = invConfig.getItemStack("Slot " + i);
                        else
                            invContents = new ItemStack(Material.AIR);
                    }
                    inventory.setContents(invContents);
                } catch (Exception ex) {
                }
                return inventory;
            } catch (Exception ex) {
                return null;
            }
        }
    
        @EventHandler
        public static void onInventoryClose(InventoryCloseEvent e) {
            if (inv != null) {
                saveInventoryToFile(inv, new File("plugins/APChests/"), p.getName());
                p.sendMessage("Inventory closed");
            }
        }
    
        public static boolean saveInventoryToFile(Inventory inventory, File path,
                String fileName) {
            if (inventory == null || path == null || fileName == null)
                return false;
            try {
                File invFile = new File(path, fileName + ".invsave");
                if (invFile.exists())
                    invFile.delete();
                FileConfiguration invConfig = YamlConfiguration
                        .loadConfiguration(invFile);
    
                invConfig.set("Title", inventory.getTitle());
                invConfig.set("Size", inventory.getSize());
                invConfig.set("Max stack size", inventory.getMaxStackSize());
                if (inventory.getHolder() instanceof Player)
                    invConfig.set("Holder",
                            ((Player) inventory.getHolder()).getName());
    
                ItemStack[] invContents = inventory.getContents();
                for (int i = 0; i < invContents.length; i++) {
                    ItemStack itemInInv = invContents;
                    if (itemInInv != null)
                        if (itemInInv.getType() != Material.AIR)
                            invConfig.set("Slot " + i, itemInInv);
                }
    
                invConfig.save(invFile);
                return true;
            } catch (Exception ex) {
                return false;
            }
        }
    
    }
    
     
    Last edited by a moderator: Mar 13, 2015
  12. Offline

    guitargun

    for the love of OOP delete this:
    public static Player p;

    just use in your onCommand Player p = (Player) sender;

    if you use something like eclipse please go by every red line because this:
    ItemStack itemInInv = invContents; (parsing a array to a single instance)

    is something you can simply fix with basic java knowledge.
    also what isn't working at the moment?
     
  13. @guitargun Hey thanks, I will do that but the part of the code you are talking about isn't made by me :p Anyways the problem is that my plugin IS NOT saving the /chest.... When I do /chest after creating the file it just opens a chest but it is different than in the beginning! Here is an example:
    My /chest before creating a file with my name that stores the contents of the chest:
    [​IMG]
    My /chest after creating the file with my name that stores the contents of the chest:
    [​IMG]


    You can also see that it says in the chat if the file for my chest is being created or if it exists and is being opened... Also did you notice that even though my original /chest had 54 spaces and a name Private Chest the seccond one that is opened by reading from a file has ONLY about 30-40 spaces AND a different name(Inventory)??? I am not really sure how to fix this... Any help would be great! Thanks!

    FIXED IT! The problem was in this line:
    Code:
    if (new File("plugins/APChests/" + p.getName())
    I changed it to:
    Code:
    if (new File("plugins/APChests/" + p.getName() + ".invsave")
    And now it works! :) Thanks everyone for helping me!

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 13, 2016
Thread Status:
Not open for further replies.

Share This Page