Search in sources :

Example 1 with SerializerOptionsException

use of me.deecaad.core.file.SerializerOptionsException in project MechanicsMain by WeaponMechanics.

the class Factory method get.

/**
 * Returns a constructed object of who inherits from <code>T</code>,
 * constructed from the given <code>arguments</code>. In order to add a
 * new type, use {@link #set(String, Arguments)}.
 *
 * <p>The given <code>arguments</code> <i>MUST</i> explicitly contain
 * <i>ALL</i> objects defined by the {@link Arguments#arguments}. If an
 * argument is missing, a {@link SerializerException} is thrown. The given
 * objects are type-casted to their expected type. Ensure that the
 * constructors for your defined arguments exist.
 *
 * @param key The non-null, non-case-sensitive name of the class to instantiate.
 * @param arguments The non-null map of arguments.
 * @return Instantiated object.
 * @throws InternalError If no "good" constructor exists.
 * @throws SerializerException invalid key OR missing argument OR invalid argument type.
 */
public final T get(String key, Map<String, Object> arguments) throws SerializerException {
    key = key.trim().toUpperCase(Locale.ROOT);
    Arguments args = map.get(key);
    if (args == null) {
        String name = StringUtil.splitCapitalLetters(getClass().getSimpleName())[0];
        throw new SerializerOptionsException(name, clazz.getSimpleName(), getOptions(), key, "FILL_ME");
    }
    // Pull only the values that we need from the mapped arguments. The
    // order of the arguments will match the order defined by the
    // Arguments class.
    Object[] objects = new Object[args.arguments.length];
    for (int i = 0; i < args.arguments.length; i++) {
        String argument = args.arguments[i];
        Class<?> clazz = args.argumentTypes[i];
        if (!arguments.containsKey(argument)) {
            String name = StringUtil.splitCapitalLetters(args.manufacturedType.getSimpleName())[0];
            throw new SerializerMissingKeyException(name, argument, "FILL_ME").addMessage("You specified: " + arguments);
        }
        // The Integer.class should be allowed to be assigned to a Double.class
        if (clazz != null && !clazz.isAssignableFrom(arguments.get(argument).getClass())) {
            try {
                if (clazz == double.class)
                    objects[i] = Double.parseDouble(arguments.get(argument).toString());
                else if (clazz == int.class)
                    objects[i] = Integer.parseInt(arguments.get(argument).toString());
                else if (clazz == boolean.class)
                    objects[i] = Boolean.parseBoolean(arguments.get(argument).toString());
                else
                    throw new NumberFormatException();
            } catch (NumberFormatException ex) {
                String name = StringUtil.splitCapitalLetters(args.manufacturedType.getSimpleName())[0];
                throw new SerializerTypeException(name, clazz, arguments.get(argument).getClass(), arguments.get(argument), "FILL_ME");
            }
        } else {
            objects[i] = arguments.get(argument);
        }
    }
    return ReflectionUtil.newInstance(args.manufacturedType, objects);
}
Also used : SerializerTypeException(me.deecaad.core.file.SerializerTypeException) SerializerOptionsException(me.deecaad.core.file.SerializerOptionsException) SerializerMissingKeyException(me.deecaad.core.file.SerializerMissingKeyException)

Example 2 with SerializerOptionsException

use of me.deecaad.core.file.SerializerOptionsException in project MechanicsMain by WeaponMechanics.

the class PotionMechanic method serialize.

@Override
@Nonnull
public PotionMechanic serialize(SerializeData data) throws SerializerException {
    // Uses the format: <PotionEffectType>-<Duration>-<Amplifier>-<Ambient>-<Hide>-<Icon>
    List<String[]> stringPotionList = data.ofList().addArgument(PotionEffectType.class, true, true).addArgument(int.class, true).assertArgumentPositive().addArgument(int.class, true).assertArgumentPositive().addArgument(boolean.class, false).addArgument(boolean.class, false).addArgument(boolean.class, false).assertList().assertExists().get();
    List<PotionEffect> potionEffectList = new ArrayList<>();
    for (String[] split : stringPotionList) {
        PotionEffectType potionEffectType = PotionEffectType.getByName(split[0]);
        if (potionEffectType == null) {
            throw new SerializerOptionsException(this, "Potion Effect", Arrays.stream(PotionEffectType.values()).map(Object::toString).collect(Collectors.toList()), split[0], data.of().getLocation());
        }
        int duration = Integer.parseInt(split[1]);
        // subtract one since 0 is potion level 1
        int amplifier = Integer.parseInt(split[2]) - 1;
        if (amplifier < 1)
            amplifier = 1;
        boolean allowParticles = split.length <= 3 || Boolean.parseBoolean(split[3]);
        boolean produceMoreParticles = split.length > 4 && Boolean.parseBoolean(split[4]);
        boolean icon = split.length > 5 && Boolean.parseBoolean(split[5]);
        if (CompatibilityAPI.getVersion() < 1.14)
            potionEffectList.add(new PotionEffect(potionEffectType, duration, amplifier, produceMoreParticles, allowParticles));
        else
            potionEffectList.add(new PotionEffect(potionEffectType, duration, amplifier, produceMoreParticles, allowParticles, icon));
    }
    return new PotionMechanic(potionEffectList);
}
Also used : SerializerOptionsException(me.deecaad.core.file.SerializerOptionsException) PotionEffect(org.bukkit.potion.PotionEffect) PotionEffectType(org.bukkit.potion.PotionEffectType) ArrayList(java.util.ArrayList) Nonnull(javax.annotation.Nonnull)

Example 3 with SerializerOptionsException

use of me.deecaad.core.file.SerializerOptionsException in project MechanicsMain by WeaponMechanics.

the class ItemSerializer method serializeWithoutRecipe.

public ItemStack serializeWithoutRecipe(SerializeData data) throws SerializerException {
    // TODO Add byte data support using 'Data:' or 'Extra_Data:' key
    Material type = data.of("Type").assertExists().getEnum(Material.class);
    ItemStack itemStack = new ItemStack(type);
    ItemMeta itemMeta = itemStack.getItemMeta();
    if (itemMeta == null) {
        throw data.exception("Type", "Did you use air as a material? This is not allowed!", SerializerException.forValue(type));
    }
    String name = data.of("Name").assertType(String.class).get(null);
    if (name != null)
        itemMeta.setDisplayName(StringUtil.color(name));
    List<?> lore = data.of("Lore").assertType(List.class).get(null);
    if (lore != null && !lore.isEmpty()) {
        itemMeta.setLore(convertListObject(lore));
    }
    short durability = (short) data.of("Durability").assertPositive().getInt(-99);
    if (durability != -99) {
        if (CompatibilityAPI.getVersion() >= 1.132) {
            ((org.bukkit.inventory.meta.Damageable) itemMeta).setDamage(durability);
        } else {
            itemStack.setDurability(durability);
        }
    }
    boolean unbreakable = data.of("Unbreakable").getBool(false);
    if (CompatibilityAPI.getVersion() >= 1.11) {
        itemMeta.setUnbreakable(unbreakable);
    } else {
        setupUnbreakable();
        ReflectionUtil.invokeMethod(setUnbreakable, ReflectionUtil.invokeMethod(spigotMethod, itemMeta), true);
    }
    int customModelData = data.of("Custom_Model_Data").assertPositive().getInt(-99);
    if (customModelData != -99 && CompatibilityAPI.getVersion() >= 1.14) {
        itemMeta.setCustomModelData(customModelData);
    }
    boolean hideFlags = data.of("Hide_Flags").getBool(false);
    if (hideFlags) {
        itemMeta.addItemFlags(ItemFlag.values());
    }
    List<String[]> enchantments = data.ofList("Enchantments").addArgument(Enchantment.class, true, true).addArgument(int.class, true).get();
    if (enchantments != null) {
        for (String[] split : enchantments) {
            Enchantment enchant;
            if (CompatibilityAPI.getVersion() < 1.13) {
                enchant = Enchantment.getByName(split[0]);
            } else {
                enchant = Enchantment.getByKey(org.bukkit.NamespacedKey.minecraft(split[0]));
            }
            if (enchant == null) {
                throw new SerializerOptionsException("Item", "Enchantment", Arrays.stream(Enchantment.values()).map(Enchantment::getName).collect(Collectors.toList()), split[0], data.of("Enchantments").getLocation());
            }
            int enchantmentLevel = Integer.parseInt(split[1]);
            itemMeta.addEnchant(enchant, enchantmentLevel - 1, true);
        }
    }
    itemStack.setItemMeta(itemMeta);
    List<String[]> attributes = data.ofList("Attributes").addArgument(AttributeType.class, true).addArgument(double.class, true).addArgument(NBTCompatibility.AttributeSlot.class, false).get();
    if (attributes != null) {
        for (String[] split : attributes) {
            List<AttributeType> attributeTypes = EnumUtil.parseEnums(AttributeType.class, split[0]);
            List<NBTCompatibility.AttributeSlot> attributeSlots = split.length > 2 ? EnumUtil.parseEnums(NBTCompatibility.AttributeSlot.class, split[2]) : null;
            double amount = Double.parseDouble(split[1]);
            for (AttributeType attribute : attributeTypes) {
                if (attributeSlots == null) {
                    CompatibilityAPI.getNBTCompatibility().setAttribute(itemStack, attribute, null, amount);
                    continue;
                }
                for (NBTCompatibility.AttributeSlot slot : attributeSlots) {
                    CompatibilityAPI.getNBTCompatibility().setAttribute(itemStack, attribute, slot, amount);
                }
            }
        }
    }
    String owningPlayer = data.of("Skull_Owning_Player").assertType(String.class).get(null);
    if (owningPlayer != null) {
        try {
            SkullMeta skullMeta = (SkullMeta) itemStack.getItemMeta();
            UUID uuid;
            try {
                uuid = UUID.fromString(owningPlayer);
            } catch (IllegalArgumentException e) {
                uuid = null;
            }
            if (uuid != null) {
                if (CompatibilityAPI.getVersion() >= 1.12) {
                    skullMeta.setOwningPlayer(Bukkit.getServer().getOfflinePlayer(uuid));
                } else {
                    skullMeta.setOwner(Bukkit.getServer().getOfflinePlayer(uuid).getName());
                }
            } else {
                skullMeta.setOwner(owningPlayer);
            }
            itemStack.setItemMeta(skullMeta);
        } catch (ClassCastException e) {
            throw data.exception("Skull_Owning_Player", "Tried to use Skulls when the item wasn't a player head!", SerializerException.forValue(type));
        }
    }
    if (CompatibilityAPI.getVersion() >= 1.11 && data.config.contains(data.key + ".Potion_Color")) {
        try {
            Color color = data.of("Potion_Color").serializeNonStandardSerializer(new ColorSerializer());
            PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta();
            potionMeta.setColor(color);
            itemStack.setItemMeta(potionMeta);
        } catch (ClassCastException e) {
            throw data.exception("Potion_Color", "Tried to use Potion Color when the item wasn't a potion!", SerializerException.forValue(type));
        }
    }
    if (data.config.contains(data.key + ".Leather_Color")) {
        try {
            Color color = data.of("Leather_Color").serializeNonStandardSerializer(new ColorSerializer());
            LeatherArmorMeta meta = (LeatherArmorMeta) itemStack.getItemMeta();
            meta.setColor(color);
            itemStack.setItemMeta(meta);
        } catch (ClassCastException e) {
            throw data.exception("Leather_Color", "Tried to use Leather Color when the item wasn't leather armor!", SerializerException.forValue(type));
        }
    }
    if (data.config.contains(data.key + ".Firework")) {
        // <FireworkEffect.Type>-<Color>-<Boolean=Trail>-<Boolean=Flicker>-<Color=Fade>
        List<String[]> list = data.ofList("Firework.Effects").addArgument(FireworkEffect.Type.class, true).addArgument(ColorSerializer.class, true, true).addArgument(boolean.class, false).addArgument(boolean.class, false).addArgument(ColorSerializer.class, false).assertExists().assertList().get();
        FireworkMeta meta = (FireworkMeta) itemMeta;
        meta.setPower(data.of("Firework.Power").assertPositive().getInt(1));
        for (String[] split : list) {
            FireworkEffect.Builder builder = FireworkEffect.builder();
            builder.with(FireworkEffect.Type.valueOf(split[0]));
            // Handle initial colors
            String[] colors = split[1].split(", ?");
            for (String color : colors) builder.withColor(new ColorSerializer().fromString(data.move("Firework.Effects"), color));
            builder.trail(split.length > 2 && split[2].equalsIgnoreCase("true"));
            builder.flicker(split.length > 3 && split[3].equalsIgnoreCase("true"));
            // Handle the fade colors
            String[] fadeColors = split.length > 4 ? split[4].split(", ?") : new String[0];
            for (String color : fadeColors) builder.withFade(new ColorSerializer().fromString(data.move("Firework.Effects"), color));
            // Add the newly constructed firework effect to the list.
            meta.addEffect(builder.build());
        }
        itemStack.setItemMeta(meta);
    }
    if (data.of("Deny_Use_In_Crafting").getBool(false)) {
        CompatibilityAPI.getNBTCompatibility().setInt(itemStack, "MechanicsCore", "deny-crafting", 1);
    }
    return itemStack;
}
Also used : NBTCompatibility(me.deecaad.core.compatibility.nbt.NBTCompatibility) SkullMeta(org.bukkit.inventory.meta.SkullMeta) FireworkEffect(org.bukkit.FireworkEffect) AttributeType(me.deecaad.core.utils.AttributeType) ArrayList(java.util.ArrayList) List(java.util.List) UUID(java.util.UUID) ItemMeta(org.bukkit.inventory.meta.ItemMeta) Color(org.bukkit.Color) FireworkMeta(org.bukkit.inventory.meta.FireworkMeta) Material(org.bukkit.Material) PotionMeta(org.bukkit.inventory.meta.PotionMeta) SerializerOptionsException(me.deecaad.core.file.SerializerOptionsException) AttributeType(me.deecaad.core.utils.AttributeType) LeatherArmorMeta(org.bukkit.inventory.meta.LeatherArmorMeta) ItemStack(org.bukkit.inventory.ItemStack) Enchantment(org.bukkit.enchantments.Enchantment)

Aggregations

SerializerOptionsException (me.deecaad.core.file.SerializerOptionsException)3 ArrayList (java.util.ArrayList)2 List (java.util.List)1 UUID (java.util.UUID)1 Nonnull (javax.annotation.Nonnull)1 NBTCompatibility (me.deecaad.core.compatibility.nbt.NBTCompatibility)1 SerializerMissingKeyException (me.deecaad.core.file.SerializerMissingKeyException)1 SerializerTypeException (me.deecaad.core.file.SerializerTypeException)1 AttributeType (me.deecaad.core.utils.AttributeType)1 Color (org.bukkit.Color)1 FireworkEffect (org.bukkit.FireworkEffect)1 Material (org.bukkit.Material)1 Enchantment (org.bukkit.enchantments.Enchantment)1 ItemStack (org.bukkit.inventory.ItemStack)1 FireworkMeta (org.bukkit.inventory.meta.FireworkMeta)1 ItemMeta (org.bukkit.inventory.meta.ItemMeta)1 LeatherArmorMeta (org.bukkit.inventory.meta.LeatherArmorMeta)1 PotionMeta (org.bukkit.inventory.meta.PotionMeta)1 SkullMeta (org.bukkit.inventory.meta.SkullMeta)1 PotionEffect (org.bukkit.potion.PotionEffect)1