Java Code Examples for org.bukkit.inventory.ItemStack#setDurability()

The following examples show how to use org.bukkit.inventory.ItemStack#setDurability() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Autorepair.java    From ce with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void effect(Event e, ItemStack item, int level) {
	PlayerMoveEvent event = (PlayerMoveEvent) e;
	Player owner = event.getPlayer();

	
	if(owner != null && owner.isOnline() && !owner.isDead()) {
		if(healFully)
			item.setDurability((short) 0);
		else {
			int newDur = item.getDurability() - ( 1 + (healAmount*level));
			
			if(newDur > 0)
				item.setDurability((short) newDur);
			else
				item.setDurability((short) 0);
		}
	}
}
 
Example 2
Source File: IPItem.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
private void createToggleableItem(boolean flagValue, Material material, int durability, String name, UUID uuid) {
    this.flagValue = flagValue;
    this.slot = -1;
    this.name = name;
    this.type = Type.TOGGLE;
    description.clear();
    item = new ItemStack(material);
    item.setDurability((short)durability);
    ItemMeta meta = item.getItemMeta();
    meta.setDisplayName(ChatColor.WHITE + name);
    if (flagValue) {
        if (uuid == null)
            description.add(ChatColor.GREEN + ASkyBlock.getPlugin().myLocale().igsAllowed);
        else
            description.add(ChatColor.GREEN + ASkyBlock.getPlugin().myLocale(uuid).igsAllowed);
    } else {
        if (uuid == null)
            description.add(ChatColor.RED + ASkyBlock.getPlugin().myLocale().igsDisallowed);
        else
            description.add(ChatColor.RED + ASkyBlock.getPlugin().myLocale(uuid).igsDisallowed);
    }
    meta.setLore(description);
    // Remove extraneous info
    if (!Bukkit.getServer().getVersion().contains("1.7") && !Bukkit.getServer().getVersion().contains("1.8")) {
        meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
        meta.addItemFlags(ItemFlag.HIDE_DESTROYS);
        meta.addItemFlags(ItemFlag.HIDE_PLACED_ON);
        meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
    }
    item.setItemMeta(meta);
}
 
Example 3
Source File: NewItemShop.java    From BedwarsRel with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private ItemStack toItemStack(VillagerTrade trade, Player player, Game game) {
  ItemStack tradeStack = trade.getRewardItem().clone();
  Method colorable = Utils.getColorableMethod(tradeStack.getType());
  ItemMeta meta = tradeStack.getItemMeta();
  ItemStack item1 = trade.getItem1();
  ItemStack item2 = trade.getItem2();
  if (Utils.isColorable(tradeStack)) {
    tradeStack.setDurability(game.getPlayerTeam(player).getColor().getDyeColor().getWoolData());
  } else if (colorable != null) {
    colorable.setAccessible(true);
    try {
      colorable.invoke(meta, new Object[]{game.getPlayerTeam(player).getColor().getColor()});
    } catch (Exception e) {
      BedwarsRel.getInstance().getBugsnag().notify(e);
      e.printStackTrace();
    }
  }
  List<String> lores = meta.getLore();
  if (lores == null) {
    lores = new ArrayList<String>();
  }

  lores.add(ChatColor.WHITE + String.valueOf(item1.getAmount()) + " "
      + item1.getItemMeta().getDisplayName());
  if (item2 != null) {
    lores.add(ChatColor.WHITE + String.valueOf(item2.getAmount()) + " "
        + item2.getItemMeta().getDisplayName());
  }

  meta.setLore(lores);
  tradeStack.setItemMeta(meta);
  return tradeStack;
}
 
Example 4
Source File: ColorChanger.java    From BedWars with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static ItemStack changeLegacyStackColor(ItemStack itemStack, TeamColor teamColor) {
    Material material = itemStack.getType();
    String materialName = material.name();

    if (Main.autoColoredMaterials.contains(materialName)) {
        itemStack.setDurability((short) teamColor.woolData);
    } else if (material.toString().contains("GLASS")) {
        itemStack.setType(Material.getMaterial("STAINED_GLASS"));
        itemStack.setDurability((short) teamColor.woolData);
    } else if (material.toString().contains("GLASS_PANE")) {
        itemStack.setType(Material.getMaterial("STAINED_GLASS_PANE"));
        itemStack.setDurability((short) teamColor.woolData);
    }
    return itemStack;
}
 
Example 5
Source File: PlayerHeadProvider.java    From UHC with MIT License 5 votes vote down vote up
public ItemStack getPlayerHeadItem(String name) {
    final ItemStack stack = new ItemStack(Material.SKULL_ITEM, 1);
    stack.setDurability(PLAYER_HEAD_DATA);

    final SkullMeta meta = (SkullMeta) stack.getItemMeta();
    meta.setOwner(name);
    stack.setItemMeta(meta);

    return stack;
}
 
Example 6
Source File: NMSHandler.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked"})
@Override
public ItemStack setPotion(Material material, Tag itemTags, ItemStack chestItem) {
    Map<String,Tag> cont = (Map<String,Tag>) ((CompoundTag) itemTags).getValue();
    if (cont != null) {
        if (((CompoundTag) itemTags).getValue().containsKey("tag")) {
            Map<String,Tag> contents = (Map<String,Tag>)((CompoundTag) itemTags).getValue().get("tag").getValue();
            StringTag stringTag = ((StringTag)contents.get("Potion"));
            if (stringTag != null) {
                String tag = ((StringTag)contents.get("Potion")).getValue();
                //Bukkit.getLogger().info("DEBUG: potioninfo found: " + tag);
                net.minecraft.server.v1_12_R1.ItemStack stack = CraftItemStack.asNMSCopy(chestItem);
                NBTTagCompound tagCompound = stack.getTag();
                if(tagCompound == null){
                    tagCompound = new NBTTagCompound();
                }
                tagCompound.setString("Potion", tag);
                stack.setTag(tagCompound);
                return CraftItemStack.asBukkitCopy(stack);
            }
        }
    }
    // Schematic is old, the potions do not have tags
    // Set it to zero so that the potion bottles don't look like giant purple and black blocks
    chestItem.setDurability((short)0);
    Bukkit.getLogger().warning("Potion in schematic is pre-V1.9 format and will just be water.");
    return chestItem;
}
 
Example 7
Source File: FlagShovels.java    From HeavySpleef with GNU General Public License v3.0 5 votes vote down vote up
@Subscribe
public void onPlayerBreakBlock(PlayerBlockBreakEvent event) {
	for (SpleefPlayer player : event.getGame().getPlayers()) {
		ItemStack stack = player.getBukkitPlayer().getItemInHand();
		if (stack.getType() != Material.DIAMOND_SPADE) {
			continue;
		}
		
		stack.setDurability((short)0);
		player.getBukkitPlayer().setItemInHand(stack);
	}
}
 
Example 8
Source File: ColorChanger.java    From BedWars with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static ItemStack changeLegacyStackColor(ItemStack itemStack, TeamColor teamColor) {
    Material material = itemStack.getType();
    String materialName = material.name();

    if (Main.autoColoredMaterials.contains(materialName)) {
        itemStack.setDurability((short) teamColor.woolData);
    } else if (material.toString().contains("GLASS")) {
        itemStack.setType(Material.getMaterial("STAINED_GLASS"));
        itemStack.setDurability((short) teamColor.woolData);
    } else if (material.toString().contains("GLASS_PANE")) {
        itemStack.setType(Material.getMaterial("STAINED_GLASS_PANE"));
        itemStack.setDurability((short) teamColor.woolData);
    }
    return itemStack;
}
 
Example 9
Source File: TreeFellerHandler.java    From QualityArmory with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true)
public void onBlock(BlockBreakEvent e) {
	if(CustomItemManager.isUsingCustomData())
		return;
	if(QualityArmory.isCustomItem(e.getPlayer().getItemInHand()) && e.getPlayer().getItemOnCursor().getType().name().endsWith ("AXE")
			&& System.currentTimeMillis()-lastClicked.get(e.getPlayer().getUniqueId())<1000) {
		lastClicked.put(e.getPlayer().getUniqueId(), System.currentTimeMillis());
		int durib = QualityArmory.findSafeSpot(e.getPlayer().getItemInHand(), true,QAMain.overrideURL);
		ItemStack temp = e.getPlayer().getItemInHand();
		temp.setDurability((short) (durib+(QAMain.overrideURL?0:4)));
		e.getPlayer().setItemInHand(temp);
	}
}
 
Example 10
Source File: NMSHandler.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked"})
@Override
public ItemStack setPotion(Material material, Tag itemTags, ItemStack chestItem) {
    Map<String,Tag> cont = (Map<String,Tag>) ((CompoundTag) itemTags).getValue();
    if (cont != null) {
        if (((CompoundTag) itemTags).getValue().containsKey("tag")) {
            Map<String,Tag> contents = (Map<String,Tag>)((CompoundTag) itemTags).getValue().get("tag").getValue();
            StringTag stringTag = ((StringTag)contents.get("Potion"));
            if (stringTag != null) {
                String tag = ((StringTag)contents.get("Potion")).getValue();
                //Bukkit.getLogger().info("DEBUG: potioninfo found: " + tag);
                net.minecraft.server.v1_9_R1.ItemStack stack = CraftItemStack.asNMSCopy(chestItem);
                NBTTagCompound tagCompound = stack.getTag();
                if(tagCompound == null){
                    tagCompound = new NBTTagCompound();
                }
                tagCompound.setString("Potion", tag);
                stack.setTag(tagCompound);
                return CraftItemStack.asBukkitCopy(stack);
            }
        }
    }
    // Schematic is old, the potions do not have tags
    // Set it to zero so that the potion bottles don't look like giant purple and black blocks
    chestItem.setDurability((short)0);
    Bukkit.getLogger().warning("Potion in schematic is pre-V1.9 format and will just be water.");
    return chestItem;
}
 
Example 11
Source File: CustomGunItem.java    From QualityArmory with GNU General Public License v3.0 4 votes vote down vote up
@Override
public ItemStack getItem(MaterialStorage ms) {
	CustomBaseObject base = QualityArmory.getCustomItem(ms);
	if(base==null)
		return null;
	String displayname = base.getDisplayName();
	if (ms == null || ms.getMat() == null)
		return new ItemStack(Material.AIR);

	ItemStack is = new ItemStack(ms.getMat());
	if (ms.getData() < 0)
		is.setDurability((short) 0);


	ItemMeta im = is.getItemMeta();
	if (im == null)
		im = Bukkit.getServer().getItemFactory().getItemMeta(ms.getMat());
	if (im != null) {
		im.setDisplayName(displayname);
		List<String> lore = base.getCustomLore()!=null?new ArrayList<>(base.getCustomLore()):new ArrayList<>();

		if (base instanceof Ammo) {
			boolean setSkull = false;
			if (((Ammo) base).isSkull() && ((Ammo) base).hasCustomSkin()) {
				setSkull = true;
				is = SkullHandler.getCustomSkull64(((Ammo) base).getCustomSkin().getBytes());
			}
			if (((Ammo) base).isSkull() && !setSkull) {
				((SkullMeta) im).setOwner(((Ammo) base).getSkullOwner());
			}
		}


		if(base instanceof Gun)
			lore.addAll(Gun.getGunLore((Gun) base, null, ((Gun) base).getMaxBullets()));
		if (base instanceof ArmorObject)
			lore.addAll(OLD_ItemFact.getArmorLore((ArmorObject) base));

		im.setLore(lore);
		if (QAMain.ITEM_enableUnbreakable) {
			try {
				im.setUnbreakable(true);
			} catch (Error | Exception e34) {
			}
		}
		try {
			if (QAMain.ITEM_enableUnbreakable) {
				im.addItemFlags(org.bukkit.inventory.ItemFlag.HIDE_UNBREAKABLE);
			}
			im.addItemFlags(org.bukkit.inventory.ItemFlag.HIDE_ATTRIBUTES);
			im.addItemFlags(org.bukkit.inventory.ItemFlag.HIDE_DESTROYS);
		} catch (Error e) {

		}
		if (ms.getData() >= 0)
			im.setCustomModelData(ms.getData());

		if (is.getType() == Material.CROSSBOW) {
			//Now the player will hold the crossbow like a gun
		//	CrossbowMeta im2 = (CrossbowMeta) im;
		//	im2.addChargedProjectile(new ItemStack(Material.VOID_AIR));
		}
		is.setItemMeta(im);
	} else {
		QAMain.getInstance().getLogger()
				.warning(QAMain.prefix + " ItemMeta is null for " + base.getName() + ". I have");
	}
	is.setAmount(1);
	return is;
}
 
Example 12
Source File: ControlPanel.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This loads the control panel from the controlpanel.yml file
 */
public static void loadControlPanel() {
    ASkyBlock plugin = ASkyBlock.getPlugin();
    // Map of known panel contents by name
    panels.clear();
    // Map of panel inventories by name
    controlPanel.clear();
    cpFile = Util.loadYamlFile("controlpanel.yml");
    ConfigurationSection controlPanels = cpFile.getRoot();
    if (controlPanels == null) {
        plugin.getLogger().severe("Controlpanel.yml is corrupted! Delete so it can be regenerated or fix!");
        return;
    }
    // Go through the yml file and create inventories and panel maps
    for (String panel : controlPanels.getKeys(false)) {
        // plugin.getLogger().info("DEBUG: Panel " + panel);
        ConfigurationSection panelConf = cpFile.getConfigurationSection(panel);
        if (panelConf != null) {
            // New panel map
            HashMap<Integer, CPItem> cp = new HashMap<Integer, CPItem>();
            String panelName = ChatColor.translateAlternateColorCodes('&', panelConf.getString("panelname", "Commands"));
            if (panel.equalsIgnoreCase("default")) {
                defaultPanelName = panelName;
            }
            ConfigurationSection buttons = cpFile.getConfigurationSection(panel + ".buttons");
            if (buttons != null) {
                // Get how many buttons can be in the CP
                int size = buttons.getKeys(false).size() + 8;
                size -= (size % 9);
                // Add inventory to map of inventories
                controlPanel.put(panelName, Bukkit.createInventory(null, size, panelName));
                // Run through buttons
                int slot = 0;
                for (String item : buttons.getKeys(false)) {
                    try {
                        String m = buttons.getString(item + ".material", "BOOK");
                        // Split off damage
                        String[] icon = m.split(":");
                        Material material = Material.matchMaterial(icon[0]);
                        if (material == null) {
                            material = Material.PAPER;
                            plugin.getLogger().severe("Error in controlpanel.yml " + icon[0] + " is an unknown material, using paper.");
                        }
                        String description = ChatColor.translateAlternateColorCodes('&',buttons.getString(item + ".description", ""));
                        String command = buttons.getString(item + ".command", "").replace("[island]", Settings.ISLANDCOMMAND);
                        String nextSection = buttons.getString(item + ".nextsection", "");
                        ItemStack i = new ItemStack(material);
                        if (icon.length == 2) {
                            i.setDurability(Short.parseShort(icon[1]));
                        }
                        CPItem cpItem = new CPItem(i, description, command, nextSection);
                        cp.put(slot, cpItem);
                        controlPanel.get(panelName).setItem(slot, cpItem.getItem());
                        slot++;
                    } catch (Exception e) {
                        plugin.getLogger().warning("Problem loading control panel " + panel + " item #" + slot);
                        plugin.getLogger().warning(e.getMessage());
                        e.printStackTrace();
                    }
                }
                // Add overall control panel
                panels.put(panelName, cp);
            }
        }
    }
}
 
Example 13
Source File: PlayerCustomItemDamage.java    From AdditionsAPI with MIT License 4 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerCustomItemDamage(PlayerCustomItemDamageEvent event) {
	if (event.isCancelled())
		return;
	Player player = event.getPlayer();
	/*
	 * Somehow, someone got an NPE here. No idea how, but let's just prevent it from
	 * happening in the future. They were using PaperSpigot so it's probably
	 * something to do with that. Or I messed something up elsewhere xD
	 * 
	 * EDIT: I messed up - it's treefeller that dropped the axe's durability to
	 * below 0, it got removed and thus got nulled. Same for sickles.
	 */
	if (event.getCustomItem() == null)
		return;

	CustomItem cItem = event.getCustomItem();
	ItemStack item = event.getItem();
	CustomItemStack cStack = new CustomItemStack(item);
	int durability = 0;
	if (cItem.hasFakeDurability())
		durability = cStack.getFakeDurability();
	else
		durability = item.getType().getMaxDurability() - item.getDurability();
	// TODO: Check if you can modify the durability for items that are not
	// unbreakable and with Fake Durability.
	if (!item.containsEnchantment(Enchantment.DURABILITY)) {
		durability -= event.getDamage();
	} else {
		for (int i = 1; i <= event.getDamage(); i++) {
			if (NumberUtils.calculateChance(1 / ((double) item.getEnchantmentLevel(Enchantment.DURABILITY) + 1D))) {
				durability -= 1;
			}
		}
	}
	if (cItem.hasFakeDurability()) {
		cStack.setFakeDurability(durability);
	} else if (!cItem.isUnbreakable()) {
		item.setDurability((short) (item.getType().getMaxDurability() - durability));
	}
	if (durability < 0) {
		PlayerCustomItemBreakEvent breakEvent = new PlayerCustomItemBreakEvent(player, item, cItem);
		Bukkit.getPluginManager().callEvent(breakEvent);
		if (!event.isCancelled()) {
			player.getInventory().remove(item);
			player.playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1F, 1F);
		}
		return;
	}
}
 
Example 14
Source File: ItemStackImpl.java    From Civs with GNU General Public License v3.0 4 votes vote down vote up
public static ItemStack deserialize(Map<String, Object> args) {
    int version = args.containsKey("v") ? ((Number)args.get("v")).intValue() : -1;
    short damage = 0;
    int amount = 1;
    if (args.containsKey("damage")) {
        damage = ((Number)args.get("damage")).shortValue();
    }

    Material type;
    if (version < 0) {
        type = Material.getMaterial("LEGACY_" + (String)args.get("type"));
        byte dataVal = type.getMaxDurability() == 0 ? (byte)damage : 0;
        type = Bukkit.getUnsafe().fromLegacy(new MaterialData(type, dataVal), true);
        if (dataVal != 0) {
            damage = 0;
        }
    } else {
        type = Material.getMaterial((String)args.get("type"));
    }

    if (args.containsKey("amount")) {
        amount = ((Number)args.get("amount")).intValue();
    }

    ItemStack result = new ItemStack(type, amount, damage);
    Object raw;
    if (args.containsKey("enchantments")) {
        raw = args.get("enchantments");
        if (raw instanceof Map) {
            Map<?, ?> map = (Map)raw;
            Iterator var9 = map.entrySet().iterator();

            while(var9.hasNext()) {
                Entry<?, ?> entry = (Entry)var9.next();
                Enchantment enchantment = Enchantment.getByName(entry.getKey().toString());
                if (enchantment != null && entry.getValue() instanceof Integer) {
                    result.addUnsafeEnchantment(enchantment, (Integer)entry.getValue());
                }
            }
        }
    } else if (args.containsKey("meta")) {
        raw = args.get("meta");
        if (raw instanceof ItemMeta) {
            result.setItemMeta((ItemMeta)raw);
        }
    }

    if (version < 0 && args.containsKey("damage")) {
        result.setDurability(damage);
    }

    return result;
}
 
Example 15
Source File: CustomGunItem.java    From QualityArmory with GNU General Public License v3.0 4 votes vote down vote up
@Override
public ItemStack getItem(MaterialStorage ms) {
	CustomBaseObject base = QualityArmory.getCustomItem(ms);
	if(base==null)
		return null;
	String displayname = base.getDisplayName();
	if (ms == null || ms.getMat() == null)
		return new ItemStack(Material.AIR);

	ItemStack is = new ItemStack(ms.getMat(),1,(short)ms.getData());
	if (ms.getData() < 0)
		is.setDurability((short) 0);
	ItemMeta im = is.getItemMeta();
	if (im == null)
		im = Bukkit.getServer().getItemFactory().getItemMeta(ms.getMat());
	if (im != null) {
		im.setDisplayName(displayname);
		List<String> lore = base.getCustomLore()!=null?new ArrayList<>(base.getCustomLore()):new ArrayList<>();

		if(base instanceof Gun)
			lore.addAll(Gun.getGunLore((Gun) base, null, ((Gun) base).getMaxBullets()));
		if (base instanceof ArmorObject)
			lore.addAll(OLD_ItemFact.getArmorLore((ArmorObject) base));

		OLD_ItemFact.addVariantData(im,lore,base);
		im.setLore(lore);
		if (QAMain.ITEM_enableUnbreakable) {
			try {
				im.setUnbreakable(true);
			} catch (Error | Exception e34) {
			}
		}
		try {
			if (QAMain.ITEM_enableUnbreakable) {
				im.addItemFlags(org.bukkit.inventory.ItemFlag.HIDE_UNBREAKABLE);
			}
			im.addItemFlags(org.bukkit.inventory.ItemFlag.HIDE_ATTRIBUTES);
			im.addItemFlags(org.bukkit.inventory.ItemFlag.HIDE_DESTROYS);
		} catch (Error e) {

		}
		if(ms.getVariant()!=0) {
			OLD_ItemFact.addVariantData(im, im.getLore(), ms.getVariant());
		}
		is.setItemMeta(im);
	} else {
		// Item meta is still null. Catch and report.
		QAMain.getInstance().getLogger()
				.warning(QAMain.prefix + " ItemMeta is null for " + base.getName() + ". I have");
	}
	is.setAmount(1);
	return is;

}
 
Example 16
Source File: Items.java    From CardinalPGM with MIT License 4 votes vote down vote up
public static ItemStack toMaxDurability(ItemStack item) {
    ItemStack item2 = item.clone();
    item2.setDurability((short)0);
    return item2;
}
 
Example 17
Source File: NoDurability.java    From civcraft with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onInventoryOpen(InventoryOpenEvent event, ItemStack stack) {
	stack.setDurability((short) 0);		
}
 
Example 18
Source File: MainMenuWindow.java    From Hawk with GNU General Public License v3.0 4 votes vote down vote up
public MainMenuWindow(Hawk hawk, Player player) {
    super(hawk, player, 1, ChatColor.GOLD + "Hawk Anticheat");
    HawkPlayer pp = hawk.getHawkPlayer(player);

    /*elements[0] = new Element(Material.SAND, "dummy") {
        @Override
        public void doAction(Player p, Hawk hawk) {
            Window testWindow = new TestWindow(hawk, p);
            hawk.getGuiManager().sendWindow(p, testWindow);
        }
    };*/

    elements[4] = new Element(Material.WORKBENCH, "Toggle Checks") {
        @Override
        public void doAction(Player p, Hawk hawk) {
            Window checks = new ToggleChecksWindow(hawk, p);
            hawk.getGuiManager().sendWindow(p, checks);
        }
    };

    elements[5] = new Element(Material.PAPER, "Reload Configuration") {
        @Override
        public void doAction(Player p, Hawk hawk) {
            Bukkit.dispatchCommand(p, "hawk reload");
        }
    };

    ItemStack notify = new ItemStack(Material.INK_SACK);
    notify.setDurability((short) (pp.canReceiveAlerts() ? 10 : 8));
    ItemMeta notifyName = notify.getItemMeta();
    notifyName.setDisplayName(pp.canReceiveAlerts() ? "Notifications: ON" : "Notifications: OFF");
    notify.setItemMeta(notifyName);
    elements[3] = new Element(notify) {
        @Override
        public void doAction(Player p, Hawk hawk) {
            pp.setReceiveNotifications(!pp.canReceiveAlerts());
            Window mainMenu = new MainMenuWindow(hawk, p);
            hawk.getGuiManager().sendWindow(p, mainMenu);
        }
    };

    elements[8] = new Element(Material.WOOD_DOOR, "Exit GUI") {
        @Override
        public void doAction(Player p, Hawk hawk) {
            p.closeInventory();
        }
    };

    prepareInventory();
}
 
Example 19
Source File: ItemBuilder.java    From Crazy-Crates with MIT License 4 votes vote down vote up
/**
 * Builder the item from all the information that was given to the builder.
 * @return The result of all the info that was given to the builder as an ItemStack.
 */
public ItemStack build() {
    if (nbtItem != null) {
        referenceItem = nbtItem.getItem();
    }
    ItemStack item = referenceItem != null ? referenceItem : new ItemStack(material);
    if (item.getType() != Material.AIR) {
        if (isHead) {//Has to go 1st due to it removing all data when finished.
            if (isHash) {//Sauce: https://github.com/deanveloper/SkullCreator
                if (isURL) {
                    SkullCreator.itemWithUrl(item, player);
                } else {
                    SkullCreator.itemWithBase64(item, player);
                }
            }
        }
        item.setAmount(amount);
        ItemMeta itemMeta = item.getItemMeta();
        itemMeta.setDisplayName(getUpdatedName());
        itemMeta.setLore(getUpdatedLore());
        if (version.isSame(Version.v1_8_R3)) {
            if (isHead && !isHash && player != null && !player.equals("")) {
                SkullMeta skullMeta = (SkullMeta) itemMeta;
                skullMeta.setOwner(player);
            }
        }
        if (version.isNewer(Version.v1_10_R1)) {
            itemMeta.setUnbreakable(unbreakable);
        }
        if (version.isNewer(Version.v1_12_R1)) {
            if (itemMeta instanceof org.bukkit.inventory.meta.Damageable) {
                ((org.bukkit.inventory.meta.Damageable) itemMeta).setDamage(damage);
            }
        } else {
            item.setDurability((short) damage);
        }
        if (isPotion && (potionType != null || potionColor != null)) {
            PotionMeta potionMeta = (PotionMeta) itemMeta;
            if (potionType != null) {
                potionMeta.setBasePotionData(new PotionData(potionType));
            }
            if (potionColor != null) {
                potionMeta.setColor(potionColor);
            }
        }
        if (isLeatherArmor && armorColor != null) {
            LeatherArmorMeta leatherMeta = (LeatherArmorMeta) itemMeta;
            leatherMeta.setColor(armorColor);
        }
        if (isBanner && !patterns.isEmpty()) {
            BannerMeta bannerMeta = (BannerMeta) itemMeta;
            bannerMeta.setPatterns(patterns);
        }
        if (isShield && !patterns.isEmpty()) {
            BlockStateMeta shieldMeta = (BlockStateMeta) itemMeta;
            Banner banner = (Banner) shieldMeta.getBlockState();
            banner.setPatterns(patterns);
            banner.update();
            shieldMeta.setBlockState(banner);
        }
        if (useCustomModelData) {
            itemMeta.setCustomModelData(customModelData);
        }
        itemFlags.forEach(itemMeta :: addItemFlags);
        item.setItemMeta(itemMeta);
        hideFlags(item);
        item.addUnsafeEnchantments(enchantments);
        addGlow(item);
        NBTItem nbt = new NBTItem(item);
        if (isHead) {
            if (!isHash && player != null && !player.equals("") && version.isNewer(Version.v1_8_R3)) {
                nbt.setString("SkullOwner", player);
            }
        }
        if (isMobEgg) {
            if (entityType != null) {
                nbt.addCompound("EntityTag").setString("id", "minecraft:" + entityType.name());
            }
        }
        if (version.isOlder(Version.v1_11_R1)) {
            if (unbreakable) {
                nbt.setBoolean("Unbreakable", true);
                nbt.setInteger("HideFlags", 4);
            }
        }
        if (!crateName.isEmpty()) {
            nbt.setString("CrazyCrates-Crate", crateName);
        }
        return nbt.getItem();
    } else {
        return item;
    }
}
 
Example 20
Source File: ItemsFixModule.java    From ExploitFixer with GNU General Public License v3.0 4 votes vote down vote up
public ItemStack fixItem(final ItemStack itemStack) {
	final Material material = Material.getMaterial(itemStack.getType().name());
	final ItemMeta itemMeta = itemStack.getItemMeta(),
			newItemMeta = plugin.getServer().getItemFactory().getItemMeta(material);
	final int maxStackSize = getMaxStackSize();
	final short durability = itemStack.getDurability();

	if (itemStack.hasItemMeta()) {
		final Map<Enchantment, Integer> enchantments = itemStack.getEnchantments();
		final String displayName = itemMeta.getDisplayName();
		final List<String> lore = itemMeta.getLore();

		if (enchantLimit > -1) {
			for (final Enchantment enchantment : enchantments.keySet()) {
				final int level = enchantments.get(enchantment);

				if (level <= enchantLimit && level > -1) {
					newItemMeta.addEnchant(enchantment, level, true);
				}
			}
		}

		if (newItemMeta instanceof BookMeta) {
			final BookMeta bookMeta = (BookMeta) itemMeta;
			final BookMeta newBookMeta = (BookMeta) newItemMeta;

			newBookMeta.setTitle(bookMeta.getTitle());
			newBookMeta.setAuthor(bookMeta.getAuthor());
			newBookMeta.setPages(bookMeta.getPages());
		} else if (newItemMeta instanceof SkullMeta) {
			final SkullMeta skullMeta = (SkullMeta) itemMeta;
			final SkullMeta newSkullMeta = (SkullMeta) newItemMeta;

			newSkullMeta.setOwner(skullMeta.getOwner());
		}

		if (displayName != null && displayName.getBytes().length < 128) {
			newItemMeta.setDisplayName(displayName);
		}

		if (lore != null && lore.toString().getBytes().length < 1024) {
			newItemMeta.setLore(lore);
		}
	}

	if (maxStackSize > 0 && itemStack.getAmount() > maxStackSize) {
		itemStack.setAmount(maxStackSize);
	}

	itemStack.setType(material);
	itemStack.setItemMeta(newItemMeta);
	itemStack.setDurability(durability);

	return itemStack;
}