Java Code Examples for org.bukkit.enchantments.Enchantment#getByName()

The following examples show how to use org.bukkit.enchantments.Enchantment#getByName() . 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: ItemUtils.java    From FunnyGuilds with Apache License 2.0 6 votes vote down vote up
private static Enchantment matchEnchant(String enchantName) {
    if (BY_IN_GAME_NAME_ENCHANT != null && CREATE_NAMESPACED_KEY != null) {
        try {
            Object namespacedKey = CREATE_NAMESPACED_KEY.invoke(null, enchantName.toLowerCase());
            Object enchantment = BY_IN_GAME_NAME_ENCHANT.invoke(null, namespacedKey);

            if (enchantment != null) {
                return (Enchantment) enchantment;
            }
        }
        catch (IllegalAccessException | InvocationTargetException ignored) {
        }
    }

    return Enchantment.getByName(enchantName.toUpperCase());
}
 
Example 2
Source File: CraftMetaItem.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
static Map<Enchantment, Integer> buildEnchantments(Map<String, Object> map, ItemMetaKey key) {
    Map<?, ?> ench = SerializableMeta.getObject(Map.class, map, key.BUKKIT, true);
    if (ench == null) {
        return null;
    }

    Map<Enchantment, Integer> enchantments = new HashMap<Enchantment, Integer>(ench.size());
    for (Map.Entry<?, ?> entry : ench.entrySet()) {
        // Doctor older enchants
        String enchantKey = entry.getKey().toString();
        if (enchantKey.equals("SWEEPING")) {
            enchantKey = "SWEEPING_EDGE";
        }

        Enchantment enchantment = Enchantment.getByName(enchantKey);
        if ((enchantment != null) && (entry.getValue() instanceof Integer)) {
            enchantments.put(enchantment, (Integer) entry.getValue());
        }
    }

    return enchantments;
}
 
Example 3
Source File: Instruction.java    From BetonQuest with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public HashMap<Enchantment, Integer> getEnchantments(String string) throws InstructionParseException {
    if (string == null) {
        return null;
    }
    HashMap<Enchantment, Integer> enchants = new HashMap<>();
    String[] array = getArray(string);
    for (String enchant : array) {
        String[] enchParts = enchant.split(":");
        if (enchParts.length != 2) {
            throw new PartParseException("Wrong enchantment format: " + enchant);
        }
        Enchantment ID = Enchantment.getByName(enchParts[0]);
        if (ID == null) {
            throw new PartParseException("Unknown enchantment type: " + enchParts[0]);
        }
        Integer level;
        try {
            level = new Integer(enchParts[1]);
        } catch (NumberFormatException e) {
            throw new PartParseException("Could not parse level in enchant: " + enchant, e);
        }
        enchants.put(ID, level);
    }
    return enchants;
}
 
Example 4
Source File: AdminResCommand.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
public void enchant_cmd() throws CivException {
	Player player = getPlayer();
	String enchant = getNamedString(1, "Enchant name");
	int level = getNamedInteger(2);
	
	
	ItemStack stack = player.getItemInHand();
	Enchantment ench = Enchantment.getByName(enchant);
	if (ench == null) {
		String out ="";
		for (Enchantment ench2 : Enchantment.values()) {
			out += ench2.getName()+",";
		}
		throw new CivException("No enchantment called "+enchant+" Options:"+out);
	}
	
	stack.addUnsafeEnchantment(ench, level);
	CivMessage.sendSuccess(sender, "Enchanted.");
}
 
Example 5
Source File: VersionUtils_1_13.java    From UhcCore with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
@Override
public Enchantment getEnchantmentFromKey(String key){
    Enchantment enchantment = Enchantment.getByName(key);

    if (enchantment != null){
        Bukkit.getLogger().warning("[UhcCore] Using old deprecated enchantment names, replace: " + key + " with " + enchantment.getKey().getKey());
        return enchantment;
    }

    NamespacedKey namespace;

    try{
        namespace = NamespacedKey.minecraft(key);
    }catch (IllegalArgumentException ex){
        return null;
    }

    return Enchantment.getByKey(namespace);
}
 
Example 6
Source File: ItemStackParser.java    From BedwarsRel with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private void parseEnchants() {
  if (this.isMetarizable()) {
    Enchantment en = null;
    int level = 0;

    ConfigurationSection newSection = (ConfigurationSection) (this.configSection);
    ConfigurationSection enchantSection = (ConfigurationSection) newSection.get("enchants");

    for (String key : enchantSection.getKeys(false)) {
      if (Utils.isNumber(key)) {
        en = Enchantment.getById(Integer.parseInt(key));
        level = Integer.parseInt(enchantSection.get(key).toString());
      } else {
        en = Enchantment.getByName(key.toUpperCase());
        level = Integer.parseInt(enchantSection.get(key).toString());
      }

      if (en == null) {
        continue;
      }

      this.finalStack.addUnsafeEnchantment(en, level);
    }
  }
}
 
Example 7
Source File: EnchantObjective.java    From BetonQuest with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public static EnchantmentData convert(String string) throws InstructionParseException {
    String[] parts = string.split(":");
    if (parts.length != 2)
        throw new InstructionParseException("Could not parse enchantment: " + string);
    Enchantment enchantment = Enchantment.getByName(parts[0].toUpperCase());
    if (enchantment == null)
        throw new InstructionParseException("Enchantment type '" + parts[0] + "' does not exist");
    int level;
    try {
        level = Integer.parseInt(parts[1]);
    } catch (NumberFormatException e) {
        throw new InstructionParseException("Could not parse enchantment level: " + string, e);
    }
    return new EnchantmentData(enchantment, level);
}
 
Example 8
Source File: CraftMetaItem.java    From Thermos with GNU General Public License v3.0 6 votes vote down vote up
static Map<Enchantment, Integer> buildEnchantments(Map<String, Object> map, ItemMetaKey key) {
    Map<?, ?> ench = SerializableMeta.getObject(Map.class, map, key.BUKKIT, true);
    if (ench == null) {
        return null;
    }

    Map<Enchantment, Integer> enchantments = new HashMap<Enchantment, Integer>(ench.size());
    for (Map.Entry<?, ?> entry : ench.entrySet()) {
        Enchantment enchantment = Enchantment.getByName(entry.getKey().toString());

        if ((enchantment != null) && (entry.getValue() instanceof Integer)) {
            enchantments.put(enchantment, (Integer) entry.getValue());
        }
    }

    return enchantments;
}
 
Example 9
Source File: Items.java    From TabooLib with MIT License 5 votes vote down vote up
public static Enchantment asEnchantment(String enchant) {
    try {
        Enchantment enchantment = Enchantment.getByName(enchant);
        return enchantment != null ? enchantment : Enchantment.getById(NumberConversions.toInt(enchant));
    } catch (Throwable e) {
        return null;
    }
}
 
Example 10
Source File: XMLUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Enchantment parseEnchantment(Node node, String text) throws InvalidXMLException {
    Enchantment enchantment = Enchantment.getByName(text.toUpperCase().replace(" ", "_"));
    if(enchantment == null) enchantment = NMSHacks.getEnchantment(text);

    if(enchantment == null) {
        throw new InvalidXMLException("Unknown enchantment '" + text + "'", node);
    }

    return enchantment;
}
 
Example 11
Source File: ZEnchantment.java    From XSeries with MIT License 5 votes vote down vote up
/**
 * Gets an enchantment from Vanilla and bukkit names.
 * There are also some aliases available.
 *
 * @param enchant the name of the enchantment.
 * @return an enchantment.
 * @since 1.0.0
 */
@Nullable
public static Optional<Enchantment> getByName(@Nonnull String enchant) {
    Validate.notEmpty(enchant, "Enchantment name cannot be null or empty");
    Enchantment enchantment = null;
    enchant = StringUtils.deleteWhitespace(StringUtils.lowerCase(enchant, Locale.ENGLISH));

    if (ISFLAT) enchantment = Enchantment.getByKey(NamespacedKey.minecraft(enchant)); // 1.13+ only
    if (enchantment == null) enchantment = Enchantment.getByName(enchant);
    if (enchantment == null) enchantment = ENCHANTMENTS.get(enchant);
    if (enchantment == null) enchantment = ALIASENCHANTMENTS.get(enchant);

    return Optional.ofNullable(enchantment);
}
 
Example 12
Source File: EnchantmentsHandler.java    From BetonQuest with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
void set(String enchant) throws InstructionParseException {
    String[] parts;
    if (enchant == null || (parts = enchant.split(":")).length == 0) {
        throw new InstructionParseException("Missing value");
    }
    if (parts[0].startsWith("none-")) {
        ex = Existence.FORBIDDEN;
        parts[0] = parts[0].substring(5);
    }
    type = Enchantment.getByName(parts[0].toUpperCase());
    if (type == null) {
        throw new InstructionParseException("Unknown enchantment type: " + parts[0]);
    }
    if (ex == Existence.FORBIDDEN) {
        return;
    }
    ex = Existence.REQUIRED;
    if (parts.length != 2) {
        throw new InstructionParseException("Wrong enchantment format");
    }
    if (parts[1].equals("?")) {
        nr = Number.WHATEVER;
        parts[1] = "1";
    } else if (parts[1].endsWith("-")) {
        nr = Number.LESS;
        parts[1] = parts[1].substring(0, parts[1].length() - 1);
    } else if (parts[1].endsWith("+")) {
        nr = Number.MORE;
        parts[1] = parts[1].substring(0, parts[1].length() - 1);
    } else {
        nr = Number.EQUAL;
    }
    try {
        level = Integer.parseInt(parts[1]);
    } catch (NumberFormatException e) {
        throw new InstructionParseException("Could not parse enchantment level: " + parts[1], e);
    }
    if (level < 1) {
        throw new InstructionParseException("Enchantment level must be a positive integer");
    }
}
 
Example 13
Source File: ItemLine.java    From Holograms with MIT License 4 votes vote down vote up
private static ItemStack parseItem(String text) {
    Matcher matcher = linePattern.matcher(text);
    if (matcher.find()) {
        text = matcher.group(3);
    }
    String[] split = text.split(" ");
    short durability = -1;
    String data = split[0];

    if (data.contains(":")) {
        String[] datasplit = data.split(":");
        data = datasplit[0];
        durability = Short.parseShort(datasplit[1]);
    }

    Material material = data.matches("[0-9]+")
            ? Material.getMaterial(Integer.parseInt(data))
            : Material.getMaterial(data.toUpperCase());

    // Throw exception if the material provided was wrong
    if (material == null) {
        throw new IllegalArgumentException("Invalid material " + data);
    }

    int amount;
    try {
        amount = split.length == 1 ? 1 : Integer.parseInt(split[1]);
    } catch (NumberFormatException ex) {
        throw new IllegalArgumentException("Invalid amount \"" + split[1] + "\"", ex);
    }
    ItemStack item = new ItemStack(material, amount, (short) Math.max(0, durability));
    ItemMeta meta = item.getItemMeta();

    // No meta data was provided, we can return here
    if (split.length < 3) {
        return item;
    }

    // Go through all the item meta specified
    for (int i = 2 ; i < split.length ; i++) {
        String[] information = split[i].split(":");

        // Data, name, or lore has been specified
        switch (information[0].toLowerCase()) {
            case "name":
                // Replace '_' with spaces
                String name = information[1].replace(' ', ' ');
                meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));
                break;
            case "lore":
                // If lore was specified 2x for some reason, don't overwrite
                List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
                String[] loreLines = information[1].split("\\|");

                // Format all the lines and add them as lore
                for (String line : loreLines) {
                    line = line.replace('_', ' '); // Replace '_' with space
                    lore.add(ChatColor.translateAlternateColorCodes('&', line));
                }

                meta.setLore(lore);
                break;
            case "data":
                short dataValue = Short.parseShort(information[1]);
                item.setDurability(dataValue);
            default:
                // Try parsing enchantment if it was nothing else
                Enchantment ench = Enchantment.getByName(information[0].toUpperCase());
                int level = Integer.parseInt(information[1]);

                if (ench != null) {
                    meta.addEnchant(ench, level, true);
                } else {
                    throw new IllegalArgumentException("Invalid enchantment " + information[0]);
                }
                break;
        }
    }

    item.setItemMeta(meta);
    return item;
}
 
Example 14
Source File: TextUtil.java    From Holograms with MIT License 4 votes vote down vote up
/**
 * Parses an ItemStack from a string of text.
 *
 * @param text the text
 * @return the item
 * @throws NumberFormatException when an invalid amount or durability are provided
 * @throws IllegalArgumentException when an invalid material or enchantment is provided
 */
public static ItemStack parseItem(String text) {
    String[] split = text.split(" ");
    short durability = -1;
    String data = split[0];

    if (data.contains(":")) {
        String[] datasplit = data.split(":");
        data = datasplit[0];
        durability = Short.parseShort(datasplit[1]);
    }

    Material material = data.matches("[0-9]+")
            ? Material.getMaterial(Integer.parseInt(data))
            : Material.getMaterial(data.toUpperCase());

    // Throw exception if the material provided was wrong
    if (material == null) {
        throw new IllegalArgumentException("Invalid material " + data);
    }

    int amount;
    try {
        amount = split.length == 1 ? 1 : Integer.parseInt(split[1]);
    } catch (NumberFormatException ex) {
        throw new IllegalArgumentException("Invalid amount \"" + split[1] + "\"", ex);
    }
    ItemStack item = new ItemStack(material, amount, (short) Math.max(0, durability));
    ItemMeta meta = item.getItemMeta();

    // No meta data was provided, we can return here
    if (split.length < 3) {
        return item;
    }

    // Go through all the item meta specified
    for (int i = 2 ; i < split.length ; i++) {
        String[] information = split[i].split(":");

        // Data, name, or lore has been specified
        switch (information[0].toLowerCase()) {
            case "name":
                // Replace '_' with spaces
                String name = information[1].replace(' ', ' ');
                meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));
                break;
            case "lore":
                // If lore was specified 2x for some reason, don't overwrite
                List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
                String[] loreLines = information[1].split("\\|");

                // Format all the lines and add them as lore
                for (String line : loreLines) {
                    line = line.replace('_', ' '); // Replace '_' with space
                    lore.add(ChatColor.translateAlternateColorCodes('&', line));
                }

                meta.setLore(lore);
                break;
            case "data":
                short dataValue = Short.parseShort(information[1]);
                item.setDurability(dataValue);
            default:
                // Try parsing enchantment if it was nothing else
                Enchantment ench = Enchantment.getByName(information[0].toUpperCase());
                int level = Integer.parseInt(information[1]);

                if (ench != null) {
                    meta.addEnchant(ench, level, true);
                } else {
                    throw new IllegalArgumentException("Invalid enchantment " + information[0]);
                }
                break;
        }
    }

    // Set the meta and return created item line
    item.setItemMeta(meta);
    return item;
}
 
Example 15
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 16
Source File: VersionUtils_1_12.java    From UhcCore with GNU General Public License v3.0 4 votes vote down vote up
@Nullable
@Override
public Enchantment getEnchantmentFromKey(String key){
    return Enchantment.getByName(key);
}
 
Example 17
Source File: VersionUtils_1_8.java    From UhcCore with GNU General Public License v3.0 4 votes vote down vote up
@Nullable
@Override
public Enchantment getEnchantmentFromKey(String key){
    return Enchantment.getByName(key);
}
 
Example 18
Source File: ItemManager.java    From EnchantmentsEnhance with GNU General Public License v3.0 4 votes vote down vote up
public static boolean applyEnchantmentToItem(ItemStack item, String ench, int level) {
    if (PackageManager.getDisabled().contains(ench)) {
        return false;
    }
    ItemMeta meta = item.getItemMeta();
    List<String> newlore = (meta.hasLore() ? meta.getLore() : new ArrayList<>());
    Enchantment vanilla = Enchantment.getByName(ench.toUpperCase());

    if (vanilla != null) {
        int lvl = (item.getEnchantmentLevel(vanilla)) + level;
        if (lvl > 0) {
            item.addUnsafeEnchantment(Enchantment.getByName(ench.toUpperCase()), lvl);
        } else {
            item.removeEnchantment(vanilla);
        }
        return true;
    } else {
        if (ench.equalsIgnoreCase("random")) {
            String name = PackageManager.getEnabled().get(new Random().nextInt(PackageManager.getEnabled().size())).name();
            return applyEnchantmentToItem(item, name, level);
        }
        String enchantment = SettingsManager.lang.getString("enchantments." + ench.toLowerCase());
        int keptLevel = 0;
        if (enchantment != null) {
            String currEnch = ChatColor.stripColor(Util.toColor(enchantment));
            for (int i = 0; i < newlore.size(); i++) {
                String[] curr = ChatColor.stripColor(newlore.get(i)).split(
                        " ");
                if (curr.length == 2 && curr[0].equals(currEnch)) {
                    // Adds original level.
                    keptLevel += Util.romanToInt(curr[1]);
                    newlore.remove(i);
                    i--;
                }
            }
            int max = 1;
            try {
                max = Main.getApi().getEnchantmentMaxLevel(ench);
            } catch (NullPointerException ex) {
            }
            int finalLevel = ((level + keptLevel) > max) ? max : level + keptLevel;
            if (finalLevel > 0) {
                newlore.add(Util.UNIQUEID + Util.toColor("&7" + enchantment + " " + Util.intToRoman(finalLevel)));
                meta.setLore(newlore);
                item.setItemMeta(meta);
                if (item.getEnchantments().isEmpty()) {
                    CompatibilityManager.glow
                            .addGlow(item);
                }
                return true;
            } else {
                meta.setLore(newlore);
                item.setItemMeta(meta);
                if (item.getEnchantments().isEmpty()) {
                    CompatibilityManager.glow
                            .addGlow(item);
                }
            }
        }
        return false;
    }
}
 
Example 19
Source File: ItemGetter_Late_1_8.java    From Quests with MIT License 4 votes vote down vote up
@Override
public ItemStack getItem(String path, ConfigurationSection config, Quests plugin, Filter... excludes) {
    if (path != null && !path.equals("")) {
        path = path + ".";
    }
    List<Filter> filters = Arrays.asList(excludes);


    String cName = config.getString(path + "name", path + "name");
    String cType = config.getString(path + "item", config.getString(path + "type", path + "item"));
    List<String> cLore = config.getStringList(path + "lore");
    List<String> cItemFlags = config.getStringList(path + "itemflags");

    String name;
    Material type = null;
    int data = 0;

    // material
    ItemStack is = getItemStack(cType, plugin);
    ItemMeta ism = is.getItemMeta();

    // lore
    if (!filters.contains(Filter.LORE)) {
        List<String> lore = new ArrayList<>();
        if (cLore != null) {
            for (String s : cLore) {
                lore.add(ChatColor.translateAlternateColorCodes('&', s));
            }
        }
        ism.setLore(lore);
    }

    // name
    if (!filters.contains(Filter.DISPLAY_NAME)) {
        name = ChatColor.translateAlternateColorCodes('&', cName);
        ism.setDisplayName(name);
    }


    // item flags
    if (!filters.contains(Filter.ITEM_FLAGS)) {
        if (config.isSet(path + "itemflags")) {
            for (String flag : cItemFlags) {
                for (ItemFlag iflag : ItemFlag.values()) {
                    if (iflag.toString().equals(flag)) {
                        ism.addItemFlags(iflag);
                        break;
                    }
                }
            }
        }
    }

    // enchantments
    if (!filters.contains(Filter.ENCHANTMENTS)) {
        if (config.isSet(path + "enchantments")) {
            for (String key : config.getStringList(path + "enchantments")) {
                String[] split = key.split(":");
                String ench = split[0];
                String levelName;
                if (split.length >= 2) {
                    levelName = split[1];
                } else {
                    levelName = "1";
                }

                Enchantment enchantment;
                if ((enchantment = Enchantment.getByName(ench)) == null) {
                    plugin.getQuestsLogger().debug("Unrecognised enchantment: " + ench);
                    continue;
                }

                int level;
                try {
                    level = Integer.parseInt(levelName);
                } catch (NumberFormatException e) {
                    level = 1;
                }

                is.addUnsafeEnchantment(enchantment, level);
            }
        }
    }

    is.setItemMeta(ism);
    return is;
}
 
Example 20
Source File: EnchantmentConfigParser.java    From EliteMobs with GNU General Public License v3.0 3 votes vote down vote up
public static HashMap<Enchantment, Integer> parseEnchantments(Configuration configuration, String previousPath) {

        String path = automatedStringBuilder(previousPath, "Enchantments");
        List enchantments = configuration.getList(path);
        HashMap enchantmentMap = new HashMap();

        try {
            for (Object object : enchantments) {

                String string = (String) object;

//                Custom enchantments have their own parser
                if (CustomEnchantmentConfigParser.isCustomEnchantment(string)) continue;

                Enchantment enchantment = Enchantment.getByName(string.split(",")[0]);

                if (enchantment != null)
                    enchantmentMap.put(enchantment, Integer.parseInt(string.split(",")[1]));

            }

        } catch (Exception e) {
            Bukkit.getLogger().warning("Warning: something on ItemsCustomLootList.yml is invalid.");
            Bukkit.getLogger().warning("Make sure you add a valid enchantment type and a valid level for it!");
        }

        return enchantmentMap;

    }