From 537aecad016c6f0346203912d85b57b71b793f84 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 11 Jan 2021 04:37:30 +0000 Subject: [PATCH 001/143] NBTCompound # Allow saving of Mojang UUIDs --- .../civmodcore/serialization/NBTCompound.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java index 5015d8ec..2e88a2ea 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java @@ -349,12 +349,29 @@ public UUID getUUID(String key) { * @param value The value to set to the key. */ public void setUUID(String key, UUID value) { + setUUID(key, value, false); + } + + /** + * Sets a UUID value to a key. + * + * @param key The key to set to value to. + * @param value The value to set to the key. + * @param useMojangFormat Whether to save as Mojang's least+most, or the updated int array. + */ + public void setUUID(String key, UUID value, boolean useMojangFormat) { Preconditions.checkArgument(!Strings.isNullOrEmpty(key)); if (value == null) { removeUUID(key); } else { - this.tag.a(key, value); + if (useMojangFormat) { + this.tag.setLong(key + "Most", value.getMostSignificantBits()); + this.tag.setLong(key + "Least", value.getLeastSignificantBits()); + } + else { + this.tag.a(key, value); + } } } From 47a40d7a5ba77621123a873d072d465221dd2a9b Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 18 Jan 2021 10:41:58 +0000 Subject: [PATCH 002/143] Potential bug fix --- .../civmodcore/inventory/items/ItemUtils.java | 37 ++++++++++--- .../civmodcore/inventory/items/MetaUtils.java | 52 +++++++++++++++++++ .../mc/civmodcore/itemHandling/ItemMap.java | 3 +- 3 files changed, 85 insertions(+), 7 deletions(-) diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java index 744acf48..f2f9ef6f 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java @@ -146,22 +146,47 @@ public static boolean isValidItemMaterial(final Material material) { } /** - * Determines whether two item stacks are similar. (Will check both items against the other) + * Determines whether two item stacks are functionally identical. * * @param former The first item. * @param latter The second item. - * @return Returns true if both items are similar and not null. + * @return Returns true if both items are functionally identical. * * @see ItemStack#isSimilar(ItemStack) */ - public static boolean areItemsSimilar(final ItemStack former, final ItemStack latter) { - if (former != null && former.isSimilar(latter)) { + public static boolean areItemsEqual(final ItemStack former, final ItemStack latter) { + if (former == latter) { return true; } - if (latter != null && latter.isSimilar(former)) { + if ((former == null || latter == null) + || former.getAmount() != latter.getAmount() + || !areItemsSimilar(former, latter)) { + return false; + } + return true; + } + + /** + * Determines whether two item stacks are similar. + * + * @param former The first item. + * @param latter The second item. + * @return Returns true if both items are similar. + * + * @see ItemStack#isSimilar(ItemStack) + */ + public static boolean areItemsSimilar(final ItemStack former, final ItemStack latter) { + if (former == latter) { return true; } - return false; + if ((former == null || latter == null) + || former.getType() != latter.getType() + // I know this is deprecated, but it's present within item.isSimilar() so it's here too. + || former.getDurability() != latter.getDurability() + || former.hasItemMeta() != latter.hasItemMeta()) { + return false; + } + return MetaUtils.areMetasEqual(getItemMeta(former), getItemMeta(latter)); } /** diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MetaUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MetaUtils.java index 0533bfc6..32926c2b 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MetaUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MetaUtils.java @@ -1,16 +1,20 @@ package vg.civcraft.mc.civmodcore.inventory.items; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Predicate; import javax.annotation.Nonnull; +import net.md_5.bungee.api.chat.BaseComponent; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; +import org.bukkit.Bukkit; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; +import vg.civcraft.mc.civmodcore.util.NullUtils; /** * Class of static utilities for when you already have an instance of {@link ItemMeta}, such as @@ -19,6 +23,54 @@ */ public final class MetaUtils { + /** + * Determines whether two item metas are functionally identical. + * + * @param former The first item meta. + * @param latter The second item meta. + * @return Returns true if both item metas are functionally identical. + */ + public static boolean areMetasEqual(final ItemMeta former, final ItemMeta latter) { + if (former == latter) { + return true; + } + if (former == null || latter == null) { + return false; + } + // Create a version of the items that do not have display names or lore, since those are the pain points + final ItemMeta fakeFormer = former.clone(); + final ItemMeta fakeLatter = latter.clone(); + fakeFormer.setDisplayName(null); + fakeFormer.setLore(null); + fakeLatter.setDisplayName(null); + fakeLatter.setLore(null); + if (!Bukkit.getItemFactory().equals(fakeFormer, fakeLatter)) { + return false; + } + // And compare the display name and lore manually + if (former.hasDisplayName() != latter.hasDisplayName()) { + return false; + } + if (former.hasDisplayName()) { + final BaseComponent[] formerDisplayName = former.getDisplayNameComponent(); + final BaseComponent[] latterDisplayName = latter.getDisplayNameComponent(); + if (!Arrays.equals(formerDisplayName, latterDisplayName)) { + return false; + } + } + if (former.hasLore() != latter.hasLore()) { + return false; + } + if (former.hasLore()) { + final List formerLore = NullUtils.isNotNull(former.getLoreComponents()); + final List latterLore = NullUtils.isNotNull(latter.getLoreComponents()); + if (!formerLore.equals(latterLore)) { + return false; + } + } + return true; + } + /** * Retrieves the lore from a given item meta. * diff --git a/src/main/java/vg/civcraft/mc/civmodcore/itemHandling/ItemMap.java b/src/main/java/vg/civcraft/mc/civmodcore/itemHandling/ItemMap.java index fb6be0b6..79ed44e1 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/itemHandling/ItemMap.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/itemHandling/ItemMap.java @@ -19,6 +19,7 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils; +import vg.civcraft.mc.civmodcore.inventory.items.MetaUtils; /** * Allows the storage and comparison of itemstacks while ignoring their maximum @@ -302,7 +303,7 @@ public int getAmount(ItemStack is) { int amount = 0; for (Entry entry : matSubMap.getEntrySet()) { ItemStack current = entry.getKey(); - if (is.getItemMeta().equals(current.getItemMeta())) { + if (MetaUtils.areMetasEqual(is.getItemMeta(), current.getItemMeta())) { amount += entry.getValue(); } } From 9bb24f88de657192bf192038bab1ba2fdd472bf2 Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 24 Jan 2021 02:12:49 +0000 Subject: [PATCH 003/143] Chat / Item / Meta utilities update --- .../mc/civmodcore/chat/ChatUtils.java | 47 + .../civmodcore/inventory/items/ItemUtils.java | 262 ++++-- .../civmodcore/inventory/items/MetaUtils.java | 190 +++- .../mc/civmodcore/bukkit/PseudoServer.java | 869 ++++++++++++++++++ .../civcraft/mc/civmodcore/enums/Tester.java | 25 - .../mc/civmodcore/items/ItemMetaTester.java | 98 ++ .../{Tester.java => SerializationTester.java} | 2 +- .../uuid/{Tester.java => UuidTester.java} | 2 +- 8 files changed, 1387 insertions(+), 108 deletions(-) create mode 100644 src/test/java/vg/civcraft/mc/civmodcore/bukkit/PseudoServer.java delete mode 100644 src/test/java/vg/civcraft/mc/civmodcore/enums/Tester.java create mode 100644 src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java rename src/test/java/vg/civcraft/mc/civmodcore/serialization/{Tester.java => SerializationTester.java} (99%) rename src/test/java/vg/civcraft/mc/civmodcore/uuid/{Tester.java => UuidTester.java} (94%) diff --git a/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java index f87f8585..34970602 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java @@ -2,6 +2,7 @@ import com.google.common.base.Strings; import java.awt.Color; +import java.util.Arrays; import java.util.List; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; @@ -220,4 +221,50 @@ else if (format == ChatColor.MAGIC) { return component; } + /** + * Converts a given text component into a composite array of base components. + * + * @param component The text component to convert. + * @return Returns a composite array of base components. + */ + public static BaseComponent[] toBaseComponents(final TextComponent component) { + if (component == null) { + return null; + } + final var text = component.getText(); + if (!Strings.isNullOrEmpty(text) || component.hasFormatting()) { + return new BaseComponent[] { component }; + } + return component.getExtra().toArray(new BaseComponent[0]); + } + + /** + * Converts a given base component array into a text component. + * + * @param components The base components to convert. + * @return Returns a representative text component. + */ + public static TextComponent fromBaseComponents(final BaseComponent... components) { + if (ArrayUtils.isEmpty(components)) { + return null; + } + if (components.length == 1) { + final var component = components[0]; + if (component instanceof TextComponent) { + return (TextComponent) component; + } + final var text = new TextComponent(); + text.copyFormatting(component); + text.setExtra(component.getExtra()); + return text; + } + return new TextComponent(components); + } + + public static boolean areComponentsEqual(final TextComponent former, final TextComponent latter) { + return Arrays.equals( + toBaseComponents(former), + toBaseComponents(latter)); + } + } diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java index f2f9ef6f..5f75a264 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java @@ -9,6 +9,8 @@ import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; +import javax.annotation.Nonnull; +import net.md_5.bungee.api.chat.TextComponent; import org.apache.commons.collections4.CollectionUtils; import org.bukkit.Material; import org.bukkit.configuration.file.YamlConfiguration; @@ -17,7 +19,6 @@ import org.bukkit.inventory.meta.ItemMeta; import vg.civcraft.mc.civmodcore.CivModCorePlugin; import vg.civcraft.mc.civmodcore.chat.ChatUtils; -import vg.civcraft.mc.civmodcore.util.Chainer; /** * Class of static APIs for Items. Replaces ISUtils. @@ -73,7 +74,7 @@ public static String getItemName(final Material material) { if (material == null) { throw new IllegalArgumentException("Cannot retrieve name of invalid material."); } - return MATERIAL_NAMES.computeIfAbsent(material, (_material) -> material.name()); + return MATERIAL_NAMES.computeIfAbsent(material, (ignored) -> material.name()); } /** @@ -83,7 +84,10 @@ public static String getItemName(final Material material) { * @return Returns the item's name. */ public static String getItemName(final ItemStack item) { - return getItemName(Chainer.from(item).then(ItemStack::getType).get()); + if (item == null) { + return null; + } + return getItemName(item.getType()); } /** @@ -95,16 +99,9 @@ public static String getItemName(final ItemStack item) { * @return Returns true if the item is valid. */ public static boolean isValidItem(final ItemStack item) { - if (item == null) { - return false; - } - if (!isValidItemMaterial(item.getType())) { - return false; - } - if (!isValidItemAmount(item)) { - return false; - } - return true; + return item != null + && isValidItemMaterial(item.getType()) + && isValidItemAmount(item); } /** @@ -114,16 +111,9 @@ public static boolean isValidItem(final ItemStack item) { * @return Returns true if the item has a valid amount. */ public static boolean isValidItemAmount(ItemStack item) { - if (item == null) { - return false; - } - if (item.getAmount() <= 0) { - return false; - } - if (item.getAmount() > item.getMaxStackSize()) { - return false; - } - return true; + return item != null + && item.getAmount() > 0 + && item.getAmount() <= item.getMaxStackSize(); } /** @@ -133,16 +123,9 @@ public static boolean isValidItemAmount(ItemStack item) { * @return Returns true if the material would be considered a valid item. */ public static boolean isValidItemMaterial(final Material material) { - if (material == null) { - return false; - } - if (material.isAir()) { - return false; - } - if (!material.isItem()) { - return false; - } - return true; + return material != null + && !material.isAir() + && material.isItem(); } /** @@ -158,12 +141,9 @@ public static boolean areItemsEqual(final ItemStack former, final ItemStack latt if (former == latter) { return true; } - if ((former == null || latter == null) - || former.getAmount() != latter.getAmount() - || !areItemsSimilar(former, latter)) { - return false; - } - return true; + return (former != null && latter != null) + && former.getAmount() == latter.getAmount() + && areItemsSimilar(former, latter); } /** @@ -186,7 +166,7 @@ public static boolean areItemsSimilar(final ItemStack former, final ItemStack la || former.hasItemMeta() != latter.hasItemMeta()) { return false; } - return MetaUtils.areMetasEqual(getItemMeta(former), getItemMeta(latter)); + return MetaUtils.areMetasEqual(former.getItemMeta(), latter.getItemMeta()); } /** @@ -225,7 +205,10 @@ public static ItemStack normalizeItem(ItemStack item) { * @return Returns the item meta. */ public static ItemMeta getItemMeta(final ItemStack item) { - return Chainer.from(item).then(ItemStack::getItemMeta).get(); + if (item == null) { + return null; + } + return item.getItemMeta(); } /** @@ -235,7 +218,8 @@ public static ItemMeta getItemMeta(final ItemStack item) { * @return Returns true if the item has a display name. */ public static boolean hasDisplayName(final ItemStack item) { - return Strings.isNullOrEmpty(getDisplayName(item)); + final var meta = getItemMeta(item); + return meta != null && meta.hasDisplayName(); } /** @@ -245,7 +229,25 @@ public static boolean hasDisplayName(final ItemStack item) { * @return Returns the display name of an item. */ public static String getDisplayName(final ItemStack item) { - return Chainer.from(getItemMeta(item)).then(ItemMeta::getDisplayName).get(); + final var meta = getItemMeta(item); + if (meta == null) { + return null; + } + return meta.getDisplayName(); + } + + /** + * Retrieves the display name from an item. + * + * @param item The item to retrieve the display name from. + * @return Returns the display name of an item. + */ + public static TextComponent getComponentDisplayName(final ItemStack item) { + final var meta = getItemMeta(item); + if (meta == null) { + return null; + } + return MetaUtils.getComponentDisplayName(meta); } /** @@ -257,7 +259,7 @@ public static String getDisplayName(final ItemStack item) { * @throws IllegalArgumentException Throws when the given item has no meta. */ public static void setDisplayName(final ItemStack item, final String name) { - final ItemMeta meta = getItemMeta(item); + final var meta = getItemMeta(item); if (meta == null) { throw new IllegalArgumentException("Cannot set that display name: item has no meta."); } @@ -270,6 +272,23 @@ public static void setDisplayName(final ItemStack item, final String name) { item.setItemMeta(meta); } + /** + * Sets a display name to an item. A null or empty name will remove the display name from the item. + * + * @param item The item to set the display name to. + * @param name The display name to set on the item. + * + * @throws IllegalArgumentException Throws when the given item has no meta. + */ + public static void setComponentDisplayName(final ItemStack item, final TextComponent name) { + final var meta = getItemMeta(item); + if (meta == null) { + throw new IllegalArgumentException("Cannot set that display name: item has no meta."); + } + MetaUtils.setComponentDisplayName(meta, name); + item.setItemMeta(meta); + } + /** * Retrieves the lore from an item. * @@ -277,7 +296,26 @@ public static void setDisplayName(final ItemStack item, final String name) { * @return Returns the lore, which is never null. */ public static List getLore(final ItemStack item) { - return MetaUtils.getLore(getItemMeta(item)); + final var meta = getItemMeta(item); + if (meta == null) { + return new ArrayList<>(); + } + return MetaUtils.getLore(meta); + } + + /** + * Retrieves the lore from an item. + * + * @param item The item to retrieve the lore from. + * @return Returns the lore, which is never null. + */ + @Nonnull + public static List getComponentLore(final ItemStack item) { + final var meta = getItemMeta(item); + if (meta == null) { + return new ArrayList<>(); + } + return MetaUtils.getComponentLore(meta); } /** @@ -307,7 +345,7 @@ public static void setLore(final ItemStack item, final String... lines) { * @throws IllegalArgumentException Throws when the given item has no meta. */ public static void setLore(final ItemStack item, final List lines) { - final ItemMeta meta = getItemMeta(item); + final var meta = getItemMeta(item); if (meta == null) { throw new IllegalArgumentException("Cannot set that lore: item has no meta."); } @@ -315,6 +353,44 @@ public static void setLore(final ItemStack item, final List lines) { item.setItemMeta(meta); } + /** + * Sets the lore for an item, replacing any lore that may have already been set. + * + * @param item The item to set the lore to. + * @param lines The lore to set to the item. + * + * @see ItemUtils#clearLore(ItemStack) + * + * @throws IllegalArgumentException Throws when the given item has no meta. + */ + public static void setComponentLore(final ItemStack item, final TextComponent... lines) { + final var meta = getItemMeta(item); + if (meta == null) { + throw new IllegalArgumentException("Cannot set that lore: item has no meta."); + } + MetaUtils.setComponentLore(meta, lines); + item.setItemMeta(meta); + } + + /** + * Sets the lore for an item, replacing any lore that may have already been set. + * + * @param item The item to set the lore to. + * @param lines The lore to set to the item. + * + * @see ItemUtils#clearLore(ItemStack) + * + * @throws IllegalArgumentException Throws when the given item has no meta. + */ + public static void setComponentLore(final ItemStack item, final List lines) { + final var meta = getItemMeta(item); + if (meta == null) { + throw new IllegalArgumentException("Cannot set that lore: item has no meta."); + } + MetaUtils.setComponentLore(meta, lines); + item.setItemMeta(meta); + } + /** * Appends lore to an item. * @@ -349,10 +425,12 @@ public static void addLore(final ItemStack item, final List lines) { * @throws IllegalArgumentException Throws when the given item has no meta. */ public static void addLore(final ItemStack item, final boolean prepend, final String... lines) { - handleItemMeta(item, (ItemMeta meta) -> { - MetaUtils.addLore(meta, prepend, lines); - return true; - }); + final var meta = getItemMeta(item); + if (meta == null) { + throw new IllegalArgumentException("Cannot add that lore: item has no meta."); + } + MetaUtils.addLore(meta, prepend, lines); + item.setItemMeta(meta); } /** @@ -365,10 +443,12 @@ public static void addLore(final ItemStack item, final boolean prepend, final St * @throws IllegalArgumentException Throws when the given item has no meta. */ public static void addLore(final ItemStack item, final boolean prepend, final List lines) { - handleItemMeta(item, (ItemMeta meta) -> { - MetaUtils.addLore(meta, prepend, lines); - return true; - }); + final var meta = getItemMeta(item); + if (meta == null) { + throw new IllegalArgumentException("Cannot add that lore: item has no meta."); + } + MetaUtils.addLore(meta, prepend, lines); + item.setItemMeta(meta); } /** @@ -382,6 +462,70 @@ public static void clearLore(final ItemStack item) { setLore(item, (List) null); } + /** + * Appends lore to an item. + * + * @param item The item to append the lore to. + * @param lines The lore to append to the item. + * + * @throws IllegalArgumentException Throws when the given item has no meta. + */ + public static void addComponentLore(final ItemStack item, final TextComponent... lines) { + addComponentLore(item, false, lines); + } + + /** + * Appends lore to an item. + * + * @param item The item to append the lore to. + * @param lines The lore to append to the item. + * + * @throws IllegalArgumentException Throws when the given item has no meta. + */ + public static void addComponentLore(final ItemStack item, final List lines) { + addComponentLore(item, false, lines); + } + + /** + * Adds lore to an item, either by appending or prepending. + * + * @param item The item to append the lore to. + * @param prepend If set to true, the lore will be prepended instead of appended. + * @param lines The lore to append to the item. + * + * @throws IllegalArgumentException Throws when the given item has no meta. + */ + public static void addComponentLore(final ItemStack item, + final boolean prepend, + final TextComponent... lines) { + final var meta = getItemMeta(item); + if (meta == null) { + throw new IllegalArgumentException("Cannot add that lore: item has no meta."); + } + MetaUtils.addComponentLore(meta, prepend, lines); + item.setItemMeta(meta); + } + + /** + * Adds lore to an item, either by appending or prepending. + * + * @param item The item to append the lore to. + * @param prepend If set to true, the lore will be prepended instead of appended. + * @param lines The lore to append to the item. + * + * @throws IllegalArgumentException Throws when the given item has no meta. + */ + public static void addComponentLore(final ItemStack item, + final boolean prepend, + final List lines) { + final var meta = getItemMeta(item); + if (meta == null) { + throw new IllegalArgumentException("Cannot add that lore: item has no meta."); + } + MetaUtils.addComponentLore(meta, prepend, lines); + item.setItemMeta(meta); + } + /** * Retrieves the Damageable ItemMeta only if it's relevant to the item. This is necessary because [almost?] every * ItemMeta implements Damageable.. for some reason. And so this will only return a Damageable instance if the item @@ -395,13 +539,11 @@ public static Damageable getDamageable(final ItemStack item) { return null; } final Material material = item.getType(); - if (!isValidItemMaterial(material)) { - return null; - } - if (material.getMaxDurability() <= 0) { + if (!isValidItemMaterial(material) + || material.getMaxDurability() <= 0) { return null; } - final ItemMeta meta = item.getItemMeta(); + final var meta = getItemMeta(item); if (!(meta instanceof Damageable)) { return null; } @@ -448,7 +590,7 @@ public static boolean handleItemMeta(final ItemStack item, final Predicate formerLore = NullUtils.isNotNull(former.getLoreComponents()); - final List latterLore = NullUtils.isNotNull(latter.getLoreComponents()); - if (!formerLore.equals(latterLore)) { + if (!Objects.equals( + getComponentLore(former), + getComponentLore(latter))) { return false; } } return true; } + /** + * Retrieves the display name from a given meta. + * + * @param meta The meta to retrieve the display name from. + * @return Returns the display name of an item. + */ + public static TextComponent getComponentDisplayName(@Nonnull final ItemMeta meta) { + return ChatUtils.fromBaseComponents(meta.getDisplayNameComponent()); + } + + /** + * Sets a given display name to a given meta. + * @param meta The meta to set the display name to. + * @param component The display name to set. + */ + public static void setComponentDisplayName(@Nonnull final ItemMeta meta, final TextComponent component) { + if (ChatUtils.isNullOrEmpty(component)) { + meta.setDisplayName(null); + return; + } + meta.setDisplayNameComponent(ChatUtils.toBaseComponents(component)); + } + /** * Retrieves the lore from a given item meta. * @@ -86,32 +112,82 @@ public static List getLore(@Nonnull final ItemMeta meta) { return lore; } + + /** + * Retrieves the lore from a given item meta. + * + * @param meta The item meta to retrieve the lore from. + * @return Returns the lore, which is never null. + */ + @Nonnull + public static List getComponentLore(@Nonnull final ItemMeta meta) { + final List lore = meta.getLoreComponents(); + if (CollectionUtils.isEmpty(lore)) { + return new ArrayList<>(); + } + return lore.stream() + .map(ChatUtils::fromBaseComponents) + .collect(Collectors.toCollection(ArrayList::new)); + } + /** - * Appends lore to an item. + * Sets the lore to a given item meta. * - * @param meta The item to append the lore to. - * @param lines The lore to append to the item. + * @param meta The meta to set the lore to. + * @param lines The lore lines to set. + */ + public static void setComponentLore(@Nonnull final ItemMeta meta, final TextComponent... lines) { + if (ArrayUtils.isEmpty(lines)) { + meta.setLore(null); + return; + } + meta.setLoreComponents(Stream.of(lines) + .map(ChatUtils::toBaseComponents) + .collect(Collectors.toList())); + } + + /** + * Sets the lore to a given item meta. + * + * @param meta The meta to set the lore to. + * @param lines The lore lines to set. + */ + public static void setComponentLore(@Nonnull final ItemMeta meta, final List lines) { + if (CollectionUtils.isEmpty(lines)) { + meta.setLore(null); + return; + } + meta.setLoreComponents(lines.stream() + .map(ChatUtils::toBaseComponents) + .collect(Collectors.toList())); + } + + /** + * Appends lore to an item meta. + * + * @param meta The item meta to append the lore to. + * @param lines The lore to append to the item meta. */ public static void addLore(@Nonnull final ItemMeta meta, final String... lines) { addLore(meta, false, lines); } /** - * Appends lore to an item. + * Appends lore to an item meta. * - * @param meta The item to append the lore to. - * @param lines The lore to append to the item. + * @param meta The item meta to append the lore to. + * @param lines The lore to append to the item meta. */ public static void addLore(@Nonnull final ItemMeta meta, final List lines) { addLore(meta, false, lines); } /** - * Adds lore to an item, either by appending or prepending. + * Adds lore to an item meta, either by appending or prepending. * - * @param meta The item to append the lore to. + * @param meta The item meta to append the lore to. * @param prepend If set to true, the lore will be prepended instead of appended. - * @param lines The lore to append to the item. + * @param lines The lore to append to the item meta. */ public static void addLore(@Nonnull final ItemMeta meta, final boolean prepend, final String... lines) { if (ArrayUtils.isEmpty(lines)) { @@ -131,11 +207,11 @@ public static void addLore(@Nonnull final ItemMeta meta, final boolean prepend, } /** - * Adds lore to an item, either by appending or prepending. + * Adds lore to an item meta, either by appending or prepending. * - * @param meta The item to append the lore to. + * @param meta The item meta to append the lore to. * @param prepend If set to true, the lore will be prepended instead of appended. - * @param lines The lore to append to the item. + * @param lines The lore to append to the item meta. */ public static void addLore(@Nonnull final ItemMeta meta, final boolean prepend, final List lines) { if (CollectionUtils.isEmpty(lines)) { @@ -155,7 +231,7 @@ public static void addLore(@Nonnull final ItemMeta meta, final boolean prepend, } /** - * Clears the lore from an item. + * Clears the lore from an item meta. * * @param meta The item meta to clear the lore of. */ @@ -163,6 +239,78 @@ public static void clearLore(@Nonnull final ItemMeta meta) { meta.setLore(null); } + /** + * Appends lore to an item meta. + * + * @param meta The item meta to append the lore to. + * @param lines The lore to append to the item meta. + */ + public static void addComponentLore(@Nonnull final ItemMeta meta, final TextComponent... lines) { + addComponentLore(meta, false, lines); + } + + /** + * Appends lore to an item meta. + * + * @param meta The item meta to append the lore to. + * @param lines The lore to append to the item meta. + */ + public static void addComponentLore(@Nonnull final ItemMeta meta, final List lines) { + addComponentLore(meta, false, lines); + } + + /** + * Adds lore to an item meta, either by appending or prepending. + * + * @param meta The item meta to append the lore to. + * @param prepend If set to true, the lore will be prepended instead of appended. + * @param lines The lore to append to the item meta. + */ + public static void addComponentLore(@Nonnull final ItemMeta meta, + final boolean prepend, + final TextComponent... lines) { + if (ArrayUtils.isEmpty(lines)) { + return; + } + final List lore = getComponentLore(meta); + if (prepend) { + ArrayUtils.reverse(lines); + for (final TextComponent line : lines) { + lore.add(0, line); + } + } + else { + CollectionUtils.addAll(lore, lines); + } + setComponentLore(meta, lore); + } + + /** + * Adds lore to an item meta, either by appending or prepending. + * + * @param meta The item meta to append the lore to. + * @param prepend If set to true, the lore will be prepended instead of appended. + * @param lines The lore to append to the item meta. + */ + public static void addComponentLore(@Nonnull final ItemMeta meta, + final boolean prepend, + final List lines) { + if (CollectionUtils.isEmpty(lines)) { + return; + } + final List lore = getComponentLore(meta); + if (prepend) { + Collections.reverse(lines); + for (final TextComponent line : lines) { + lore.add(0, line); + } + } + else { + lore.addAll(lines); + } + setComponentLore(meta, lore); + } + /** * Makes an item glow by adding an enchantment and the flag for hiding enchantments, * so it has the enchantment glow without an enchantment being visible. Note that this diff --git a/src/test/java/vg/civcraft/mc/civmodcore/bukkit/PseudoServer.java b/src/test/java/vg/civcraft/mc/civmodcore/bukkit/PseudoServer.java new file mode 100644 index 00000000..46476357 --- /dev/null +++ b/src/test/java/vg/civcraft/mc/civmodcore/bukkit/PseudoServer.java @@ -0,0 +1,869 @@ +package vg.civcraft.mc.civmodcore.bukkit; + +import com.destroystokyo.paper.entity.ai.MobGoals; +import com.destroystokyo.paper.profile.PlayerProfile; +import java.awt.image.BufferedImage; +import java.io.File; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.apache.commons.lang3.NotImplementedException; +import org.bukkit.BanList; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Keyed; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.OfflinePlayer; +import org.bukkit.Server; +import org.bukkit.StructureType; +import org.bukkit.Tag; +import org.bukkit.UnsafeValues; +import org.bukkit.Warning; +import org.bukkit.World; +import org.bukkit.WorldCreator; +import org.bukkit.advancement.Advancement; +import org.bukkit.block.data.BlockData; +import org.bukkit.boss.BarColor; +import org.bukkit.boss.BarFlag; +import org.bukkit.boss.BarStyle; +import org.bukkit.boss.BossBar; +import org.bukkit.boss.KeyedBossBar; +import org.bukkit.command.CommandException; +import org.bukkit.command.CommandMap; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.command.PluginCommand; +import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftItemFactory; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.help.HelpMap; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemFactory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Merchant; +import org.bukkit.inventory.Recipe; +import org.bukkit.loot.LootTable; +import org.bukkit.map.MapView; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.ServicesManager; +import org.bukkit.plugin.messaging.Messenger; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scoreboard.ScoreboardManager; +import org.bukkit.util.CachedServerIcon; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class PseudoServer implements Server { + + public static final PseudoServer INSTANCE = new PseudoServer(); + private static final Logger LOGGER = Logger.getLogger(PseudoServer.class.getSimpleName()); + + public static void setup() { + final var previousLevel = LOGGER.getLevel(); + LOGGER.setLevel(Level.OFF); + Bukkit.setServer(INSTANCE); + LOGGER.setLevel(previousLevel); + } + + @NotNull + @Override + public Logger getLogger() { + return LOGGER; + } + + @NotNull + @Override + public ItemFactory getItemFactory() { + return CraftItemFactory.instance(); + } + + // ------------------------------------------------------------ + // Not implemented + // ------------------------------------------------------------ + + @NotNull + @Override + public String getName() { + return ""; + } + + @NotNull + @Override + public String getVersion() { + return ""; + } + + @NotNull + @Override + public String getBukkitVersion() { + return ""; + } + + @NotNull + @Override + public String getMinecraftVersion() { + return ""; + } + + @NotNull + @Override + public Collection getOnlinePlayers() { + throw new NotImplementedException(); + } + + @Override + public int getMaxPlayers() { + throw new NotImplementedException(); + } + + @Override + public void setMaxPlayers(final int i) { + throw new NotImplementedException(); + } + + @Override + public int getPort() { + throw new NotImplementedException(); + } + + @Override + public int getViewDistance() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public String getIp() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public String getWorldType() { + throw new NotImplementedException(); + } + + @Override + public boolean getGenerateStructures() { + throw new NotImplementedException(); + } + + @Override + public int getMaxWorldSize() { + throw new NotImplementedException(); + } + + @Override + public boolean getAllowEnd() { + throw new NotImplementedException(); + } + + @Override + public boolean getAllowNether() { + throw new NotImplementedException(); + } + + @Override + public boolean hasWhitelist() { + throw new NotImplementedException(); + } + + @Override + public void setWhitelist(final boolean b) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Set getWhitelistedPlayers() { + throw new NotImplementedException(); + } + + @Override + public void reloadWhitelist() { + throw new NotImplementedException(); + } + + @Override + public int broadcastMessage(@NotNull final String s) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public String getUpdateFolder() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public File getUpdateFolderFile() { + throw new NotImplementedException(); + } + + @Override + public long getConnectionThrottle() { + throw new NotImplementedException(); + } + + @Override + public int getTicksPerAnimalSpawns() { + throw new NotImplementedException(); + } + + @Override + public int getTicksPerMonsterSpawns() { + throw new NotImplementedException(); + } + + @Override + public int getTicksPerWaterSpawns() { + throw new NotImplementedException(); + } + + @Override + public int getTicksPerWaterAmbientSpawns() { + throw new NotImplementedException(); + } + + @Override + public int getTicksPerAmbientSpawns() { + throw new NotImplementedException(); + } + + @Nullable + @Override + public Player getPlayer(@NotNull final String s) { + throw new NotImplementedException(); + } + + @Nullable + @Override + public Player getPlayerExact(@NotNull final String s) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public List matchPlayer(@NotNull final String s) { + throw new NotImplementedException(); + } + + @Nullable + @Override + public Player getPlayer(@NotNull final UUID uuid) { + throw new NotImplementedException(); + } + + @Nullable + @Override + public UUID getPlayerUniqueId(@NotNull final String s) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public PluginManager getPluginManager() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public BukkitScheduler getScheduler() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public ServicesManager getServicesManager() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public List getWorlds() { + throw new NotImplementedException(); + } + + @Nullable + @Override + public World createWorld(@NotNull final WorldCreator worldCreator) { + throw new NotImplementedException(); + } + + @Override + public boolean unloadWorld(@NotNull final String s, final boolean b) { + throw new NotImplementedException(); + } + + @Override + public boolean unloadWorld(@NotNull final World world, final boolean b) { + throw new NotImplementedException(); + } + + @Nullable + @Override + public World getWorld(@NotNull final String s) { + throw new NotImplementedException(); + } + + @Nullable + @Override + public World getWorld(@NotNull final UUID uuid) { + throw new NotImplementedException(); + } + + @Nullable + @Override + public MapView getMap(final int i) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public MapView createMap(@NotNull final World world) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public ItemStack createExplorerMap(@NotNull final World world, @NotNull final Location location, @NotNull final StructureType structureType) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public ItemStack createExplorerMap(@NotNull final World world, @NotNull final Location location, @NotNull final StructureType structureType, final int i, final boolean b) { + throw new NotImplementedException(); + } + + @Override + public void reload() { + throw new NotImplementedException(); + } + + @Override + public void reloadData() { + throw new NotImplementedException(); + } + + @Nullable + @Override + public PluginCommand getPluginCommand(@NotNull final String s) { + throw new NotImplementedException(); + } + + @Override + public void savePlayers() { + throw new NotImplementedException(); + } + + @Override + public boolean dispatchCommand(@NotNull final CommandSender commandSender, @NotNull final String s) throws CommandException { + throw new NotImplementedException(); + } + + @Override + public boolean addRecipe(@Nullable final Recipe recipe) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public List getRecipesFor(@NotNull final ItemStack itemStack) { + throw new NotImplementedException(); + } + + @Nullable + @Override + public Recipe getRecipe(@NotNull final NamespacedKey namespacedKey) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Iterator recipeIterator() { + throw new NotImplementedException(); + } + + @Override + public void clearRecipes() { + throw new NotImplementedException(); + } + + @Override + public void resetRecipes() { + throw new NotImplementedException(); + } + + @Override + public boolean removeRecipe(@NotNull final NamespacedKey namespacedKey) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Map getCommandAliases() { + throw new NotImplementedException(); + } + + @Override + public int getSpawnRadius() { + throw new NotImplementedException(); + } + + @Override + public void setSpawnRadius(final int i) { + throw new NotImplementedException(); + } + + @Override + public boolean getOnlineMode() { + throw new NotImplementedException(); + } + + @Override + public boolean getAllowFlight() { + throw new NotImplementedException(); + } + + @Override + public boolean isHardcore() { + throw new NotImplementedException(); + } + + @Override + public void shutdown() { + throw new NotImplementedException(); + } + + @Override + public int broadcast(@NotNull final String s, @NotNull final String s1) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public OfflinePlayer getOfflinePlayer(@NotNull final String s) { + throw new NotImplementedException(); + } + + @Nullable + @Override + public OfflinePlayer getOfflinePlayerIfCached(@NotNull final String s) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public OfflinePlayer getOfflinePlayer(@NotNull final UUID uuid) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Set getIPBans() { + throw new NotImplementedException(); + } + + @Override + public void banIP(@NotNull final String s) { + throw new NotImplementedException(); + } + + @Override + public void unbanIP(@NotNull final String s) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Set getBannedPlayers() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public BanList getBanList(@NotNull final BanList.Type type) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Set getOperators() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public GameMode getDefaultGameMode() { + throw new NotImplementedException(); + } + + @Override + public void setDefaultGameMode(@NotNull final GameMode gameMode) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public ConsoleCommandSender getConsoleSender() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public File getWorldContainer() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public OfflinePlayer[] getOfflinePlayers() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Messenger getMessenger() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public HelpMap getHelpMap() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Inventory createInventory(@Nullable final InventoryHolder inventoryHolder, @NotNull final InventoryType inventoryType) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Inventory createInventory(@Nullable final InventoryHolder inventoryHolder, @NotNull final InventoryType inventoryType, @NotNull final String s) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Inventory createInventory(@Nullable final InventoryHolder inventoryHolder, final int i) throws IllegalArgumentException { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Inventory createInventory(@Nullable final InventoryHolder inventoryHolder, final int i, @NotNull final String s) throws IllegalArgumentException { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Merchant createMerchant(@Nullable final String s) { + throw new NotImplementedException(); + } + + @Override + public int getMonsterSpawnLimit() { + throw new NotImplementedException(); + } + + @Override + public int getAnimalSpawnLimit() { + throw new NotImplementedException(); + } + + @Override + public int getWaterAnimalSpawnLimit() { + throw new NotImplementedException(); + } + + @Override + public int getWaterAmbientSpawnLimit() { + throw new NotImplementedException(); + } + + @Override + public int getAmbientSpawnLimit() { + throw new NotImplementedException(); + } + + @Override + public boolean isPrimaryThread() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public String getMotd() { + throw new NotImplementedException(); + } + + @Nullable + @Override + public String getShutdownMessage() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Warning.WarningState getWarningState() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public ScoreboardManager getScoreboardManager() { + throw new NotImplementedException(); + } + + @Nullable + @Override + public CachedServerIcon getServerIcon() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public CachedServerIcon loadServerIcon(@NotNull final File file) throws IllegalArgumentException, Exception { + throw new NotImplementedException(); + } + + @NotNull + @Override + public CachedServerIcon loadServerIcon(@NotNull final BufferedImage bufferedImage) throws IllegalArgumentException, Exception { + throw new NotImplementedException(); + } + + @Override + public void setIdleTimeout(final int i) { + throw new NotImplementedException(); + } + + @Override + public int getIdleTimeout() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public ChunkGenerator.ChunkData createChunkData(@NotNull final World world) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public ChunkGenerator.ChunkData createVanillaChunkData(@NotNull final World world, final int i, final int i1) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public BossBar createBossBar(@Nullable final String s, @NotNull final BarColor barColor, @NotNull final BarStyle barStyle, @NotNull final BarFlag... barFlags) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public KeyedBossBar createBossBar(@NotNull final NamespacedKey namespacedKey, @Nullable final String s, @NotNull final BarColor barColor, @NotNull final BarStyle barStyle, @NotNull final BarFlag... barFlags) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Iterator getBossBars() { + throw new NotImplementedException(); + } + + @Nullable + @Override + public KeyedBossBar getBossBar(@NotNull final NamespacedKey namespacedKey) { + throw new NotImplementedException(); + } + + @Override + public boolean removeBossBar(@NotNull final NamespacedKey namespacedKey) { + throw new NotImplementedException(); + } + + @Nullable + @Override + public Entity getEntity(@NotNull final UUID uuid) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public double[] getTPS() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public long[] getTickTimes() { + throw new NotImplementedException(); + } + + @Override + public double getAverageTickTime() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public CommandMap getCommandMap() { + throw new NotImplementedException(); + } + + @Nullable + @Override + public Advancement getAdvancement(@NotNull final NamespacedKey namespacedKey) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Iterator advancementIterator() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public BlockData createBlockData(@NotNull final Material material) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public BlockData createBlockData(@NotNull final Material material, @Nullable final Consumer consumer) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public BlockData createBlockData(@NotNull final String s) throws IllegalArgumentException { + throw new NotImplementedException(); + } + + @NotNull + @Override + public BlockData createBlockData(@Nullable final Material material, @Nullable final String s) throws IllegalArgumentException { + throw new NotImplementedException(); + } + + @Override + public Tag getTag(@NotNull final String s, @NotNull final NamespacedKey namespacedKey, @NotNull final Class aClass) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Iterable> getTags(@NotNull final String s, @NotNull final Class aClass) { + throw new NotImplementedException(); + } + + @Nullable + @Override + public LootTable getLootTable(@NotNull final NamespacedKey namespacedKey) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public List selectEntities(@NotNull final CommandSender commandSender, @NotNull final String s) throws IllegalArgumentException { + throw new NotImplementedException(); + } + + @NotNull + @Override + public UnsafeValues getUnsafe() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Spigot spigot() { + throw new NotImplementedException(); + } + + @Override + public void reloadPermissions() { + throw new NotImplementedException(); + } + + @Override + public boolean reloadCommandAliases() { + throw new NotImplementedException(); + } + + @Override + public boolean suggestPlayerNamesWhenNullTabCompletions() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public String getPermissionMessage() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public PlayerProfile createProfile(@NotNull final UUID uuid) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public PlayerProfile createProfile(@NotNull final String s) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public PlayerProfile createProfile(@Nullable final UUID uuid, @Nullable final String s) { + throw new NotImplementedException(); + } + + @Override + public int getCurrentTick() { + throw new NotImplementedException(); + } + + @Override + public boolean isStopping() { + throw new NotImplementedException(); + } + + @NotNull + @Override + public MobGoals getMobGoals() { + throw new NotImplementedException(); + } + + @Override + public void sendPluginMessage(@NotNull final Plugin plugin, @NotNull final String s, @NotNull final byte[] bytes) { + throw new NotImplementedException(); + } + + @NotNull + @Override + public Set getListeningPluginChannels() { + throw new NotImplementedException(); + } + +} diff --git a/src/test/java/vg/civcraft/mc/civmodcore/enums/Tester.java b/src/test/java/vg/civcraft/mc/civmodcore/enums/Tester.java deleted file mode 100644 index 964f9bdc..00000000 --- a/src/test/java/vg/civcraft/mc/civmodcore/enums/Tester.java +++ /dev/null @@ -1,25 +0,0 @@ -package vg.civcraft.mc.civmodcore.enums; - -import org.junit.Assert; -import org.junit.Test; -import vg.civcraft.mc.civmodcore.util.EnumUtils; - -public class Tester { - - public enum Example { - ONE, - TWO, - THREE - } - - @Test - public void testStringSerialization() { - // Setup - String ENUM_KEY = EnumUtils.getSlug(Example.THREE); - // Process - Enum result = EnumUtils.fromSlug(Example.class, ENUM_KEY, false); - // Check - Assert.assertEquals(Example.THREE, result); - } - -} diff --git a/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java b/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java new file mode 100644 index 00000000..9b215e9e --- /dev/null +++ b/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java @@ -0,0 +1,98 @@ +package vg.civcraft.mc.civmodcore.items; + +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.chat.ComponentSerializer; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import vg.civcraft.mc.civmodcore.bukkit.PseudoServer; +import vg.civcraft.mc.civmodcore.chat.ChatUtils; +import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils; +import vg.civcraft.mc.civmodcore.serialization.NBTCompound; +import vg.civcraft.mc.civmodcore.util.NullUtils; + +public class ItemMetaTester { + + private static final ItemStack TEMPLATE_ITEM = new ItemStack(Material.STICK); + + @BeforeClass + public static void setupBukkit() { + PseudoServer.setup(); + } + + /** + *

Sometimes components will be stored out in different orders.

+ * + *

+ * For example: + *

    + *
  • {@code {"text":"","extra":[{"text":"Test!"}]}}
  • + *
  • {@code {"extra":[{"text":"Test!"}],"text":""}}
  • + *
+ *

+ */ + @Test + public void testComponentOrderEquality() { + // Setup + final String formerMessage = "{\"text\":\"\",\"extra\":[{\"text\":\"Test!\"}]}"; + final String latterMessage = "{\"extra\":[{\"text\":\"Test!\"}],\"text\":\"\"}"; + // Process + final BaseComponent[] formerParsed = ComponentSerializer.parse(formerMessage); + final BaseComponent[] latterParsed = ComponentSerializer.parse(latterMessage); + // Check + Assert.assertArrayEquals(formerParsed, latterParsed); + } + + /** + * + */ + @Test + public void testBasicDisplayNameEquality() { + // Setup + final var formerItem = NullUtils.isNotNull(NBTCompound.processItem(TEMPLATE_ITEM, (nbt) -> { + final var display = new NBTCompound(); + display.setString("Name", "\"Hello!\""); + nbt.setCompound("display", display); + })); + final var latterItem = TEMPLATE_ITEM.clone(); + ItemUtils.setDisplayName(latterItem, "Hello!"); + // Check + Assert.assertTrue(ChatUtils.areComponentsEqual( + ItemUtils.getComponentDisplayName(formerItem), + ItemUtils.getComponentDisplayName(latterItem))); + } + + /** + * + */ + @Test + public void testAdvancedDisplayNameEquality() { + // Setup + final var formerItem = TEMPLATE_ITEM.clone(); + ItemUtils.setDisplayName(formerItem, "Hello!"); + final var latterItem = TEMPLATE_ITEM.clone(); + ItemUtils.setComponentDisplayName(latterItem, new TextComponent("Hello!")); + // Check + Assert.assertTrue(ChatUtils.areComponentsEqual( + ItemUtils.getComponentDisplayName(formerItem), + ItemUtils.getComponentDisplayName(latterItem))); + } + + /** + * + */ + @Test + public void testCustomItemStackSimilarity() { + // Setup + final var formerItem = TEMPLATE_ITEM.clone(); + ItemUtils.setDisplayName(formerItem, "Hello!"); + final var latterItem = TEMPLATE_ITEM.clone(); + ItemUtils.setComponentDisplayName(latterItem, new TextComponent("Hello!")); + // Check + Assert.assertTrue(ItemUtils.areItemsSimilar(formerItem, latterItem)); + } + +} diff --git a/src/test/java/vg/civcraft/mc/civmodcore/serialization/Tester.java b/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTester.java similarity index 99% rename from src/test/java/vg/civcraft/mc/civmodcore/serialization/Tester.java rename to src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTester.java index ae78a001..1c945ea1 100644 --- a/src/test/java/vg/civcraft/mc/civmodcore/serialization/Tester.java +++ b/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTester.java @@ -7,7 +7,7 @@ import org.junit.Test; import vg.civcraft.mc.civmodcore.util.Validation; -public class Tester { +public class SerializationTester { @BeforeClass public static void beforeAll() { diff --git a/src/test/java/vg/civcraft/mc/civmodcore/uuid/Tester.java b/src/test/java/vg/civcraft/mc/civmodcore/uuid/UuidTester.java similarity index 94% rename from src/test/java/vg/civcraft/mc/civmodcore/uuid/Tester.java rename to src/test/java/vg/civcraft/mc/civmodcore/uuid/UuidTester.java index ba5bba2f..33e647e0 100644 --- a/src/test/java/vg/civcraft/mc/civmodcore/uuid/Tester.java +++ b/src/test/java/vg/civcraft/mc/civmodcore/uuid/UuidTester.java @@ -5,7 +5,7 @@ import org.junit.Test; import vg.civcraft.mc.civmodcore.util.UuidUtils; -public class Tester { +public class UuidTester { @Test public void testUuidSerialization() { From f1fb7b81d15012acef57a1abaab575a0cef5f4db Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 24 Jan 2021 02:20:07 +0000 Subject: [PATCH 004/143] Relocation PseudoServer to somewhere more appropriate --- .../civmodcore/bukkit => org/bukkit/pseudo}/PseudoServer.java | 4 ++-- .../java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename src/test/java/{vg/civcraft/mc/civmodcore/bukkit => org/bukkit/pseudo}/PseudoServer.java (99%) diff --git a/src/test/java/vg/civcraft/mc/civmodcore/bukkit/PseudoServer.java b/src/test/java/org/bukkit/pseudo/PseudoServer.java similarity index 99% rename from src/test/java/vg/civcraft/mc/civmodcore/bukkit/PseudoServer.java rename to src/test/java/org/bukkit/pseudo/PseudoServer.java index 46476357..ada193c6 100644 --- a/src/test/java/vg/civcraft/mc/civmodcore/bukkit/PseudoServer.java +++ b/src/test/java/org/bukkit/pseudo/PseudoServer.java @@ -1,4 +1,4 @@ -package vg.civcraft.mc.civmodcore.bukkit; +package org.bukkit.pseudo; import com.destroystokyo.paper.entity.ai.MobGoals; import com.destroystokyo.paper.profile.PlayerProfile; @@ -72,7 +72,7 @@ public class PseudoServer implements Server { public static void setup() { final var previousLevel = LOGGER.getLevel(); - LOGGER.setLevel(Level.OFF); + LOGGER.setLevel(Level.OFF); // This is to prevent unnecessary logging Bukkit.setServer(INSTANCE); LOGGER.setLevel(previousLevel); } diff --git a/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java b/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java index 9b215e9e..97a546f2 100644 --- a/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java +++ b/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java @@ -8,7 +8,7 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import vg.civcraft.mc.civmodcore.bukkit.PseudoServer; +import org.bukkit.pseudo.PseudoServer; import vg.civcraft.mc.civmodcore.chat.ChatUtils; import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils; import vg.civcraft.mc.civmodcore.serialization.NBTCompound; From 38078a163f46c46acbb1d274bb0e83f7ad80dd3b Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 24 Jan 2021 02:20:16 +0000 Subject: [PATCH 005/143] Update to 1.16.5 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index addbae0d..7c9fb3d5 100644 --- a/pom.xml +++ b/pom.xml @@ -32,7 +32,7 @@ com.destroystokyo.paper paper - 1.16.4-R0.1-SNAPSHOT + 1.16.5-R0.1-SNAPSHOT provided From 7aa253ef371d0cc67e84848a16d7413cad4ab348 Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 24 Jan 2021 02:51:13 +0000 Subject: [PATCH 006/143] javadoc update --- .../mc/civmodcore/items/ItemMetaTester.java | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java b/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java index 97a546f2..da2e60a0 100644 --- a/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java +++ b/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java @@ -5,10 +5,10 @@ import net.md_5.bungee.chat.ComponentSerializer; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; +import org.bukkit.pseudo.PseudoServer; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.bukkit.pseudo.PseudoServer; import vg.civcraft.mc.civmodcore.chat.ChatUtils; import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils; import vg.civcraft.mc.civmodcore.serialization.NBTCompound; @@ -24,15 +24,7 @@ public static void setupBukkit() { } /** - *

Sometimes components will be stored out in different orders.

- * - *

- * For example: - *

    - *
  • {@code {"text":"","extra":[{"text":"Test!"}]}}
  • - *
  • {@code {"extra":[{"text":"Test!"}],"text":""}}
  • - *
- *

+ * Tests whether two components of different order can match. */ @Test public void testComponentOrderEquality() { @@ -47,7 +39,7 @@ public void testComponentOrderEquality() { } /** - * + * Tests whether a primitive display name can match with a component. */ @Test public void testBasicDisplayNameEquality() { @@ -66,7 +58,7 @@ public void testBasicDisplayNameEquality() { } /** - * + * How do different API methods of setting the display name fare? */ @Test public void testAdvancedDisplayNameEquality() { @@ -82,7 +74,7 @@ public void testAdvancedDisplayNameEquality() { } /** - * + * Tries a full item similarity check. */ @Test public void testCustomItemStackSimilarity() { From 9beee742f946de338d2f2f32243bf2ac243142cd Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 24 Jan 2021 03:18:53 +0000 Subject: [PATCH 007/143] Add missing data --- .../civmodcore/inventory/items/MoreTags.java | 2 + .../inventory/items/SpawnEggUtils.java | 131 +++++++++--------- src/main/resources/materials.yml | 1 + 3 files changed, 69 insertions(+), 65 deletions(-) diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MoreTags.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MoreTags.java index dd427662..745041fe 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MoreTags.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MoreTags.java @@ -108,6 +108,8 @@ public final class MoreTags { .add(Material.PUMPKIN_STEM) .add(Material.SUGAR_CANE) .add(Material.SWEET_BERRY_BUSH) + .add(Material.TWISTING_VINES) + .add(Material.WEEPING_VINES) .add(Material.WHEAT) .build()); diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/SpawnEggUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/SpawnEggUtils.java index 54b00fac..9689dd93 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/SpawnEggUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/SpawnEggUtils.java @@ -16,71 +16,72 @@ */ public final class SpawnEggUtils { - private static final BiMap SPAWN_EGGS = ImmutableBiMap.builder(). - put(Material.BAT_SPAWN_EGG, EntityType.BAT). - put(Material.BEE_SPAWN_EGG, EntityType.BEE). - put(Material.BLAZE_SPAWN_EGG, EntityType.BLAZE). - put(Material.CAT_SPAWN_EGG, EntityType.CAT). - put(Material.CAVE_SPIDER_SPAWN_EGG, EntityType.CAVE_SPIDER). - put(Material.CHICKEN_SPAWN_EGG, EntityType.CHICKEN). - put(Material.COD_SPAWN_EGG, EntityType.COD). - put(Material.COW_SPAWN_EGG, EntityType.COW). - put(Material.CREEPER_SPAWN_EGG, EntityType.CREEPER). - put(Material.DOLPHIN_SPAWN_EGG, EntityType.DOLPHIN). - put(Material.DONKEY_SPAWN_EGG, EntityType.DONKEY). - put(Material.DROWNED_SPAWN_EGG, EntityType.DROWNED). - put(Material.ELDER_GUARDIAN_SPAWN_EGG, EntityType.ELDER_GUARDIAN). - put(Material.ENDERMAN_SPAWN_EGG, EntityType.ENDERMAN). - put(Material.ENDERMITE_SPAWN_EGG, EntityType.ENDERMITE). - put(Material.EVOKER_SPAWN_EGG, EntityType.EVOKER). - put(Material.FOX_SPAWN_EGG, EntityType.FOX). - put(Material.GHAST_SPAWN_EGG, EntityType.GHAST). - put(Material.GUARDIAN_SPAWN_EGG, EntityType.GUARDIAN). - put(Material.HOGLIN_SPAWN_EGG, EntityType.HOGLIN). - put(Material.HORSE_SPAWN_EGG, EntityType.HORSE). - put(Material.HUSK_SPAWN_EGG, EntityType.HUSK). - put(Material.LLAMA_SPAWN_EGG, EntityType.LLAMA). - put(Material.MAGMA_CUBE_SPAWN_EGG, EntityType.MAGMA_CUBE). - put(Material.MOOSHROOM_SPAWN_EGG, EntityType.MUSHROOM_COW). - put(Material.MULE_SPAWN_EGG, EntityType.MULE). - put(Material.OCELOT_SPAWN_EGG, EntityType.OCELOT). - put(Material.PANDA_SPAWN_EGG, EntityType.PANDA). - put(Material.PARROT_SPAWN_EGG, EntityType.PARROT). - put(Material.PHANTOM_SPAWN_EGG, EntityType.PHANTOM). - put(Material.PIG_SPAWN_EGG, EntityType.PIG). - put(Material.PIGLIN_SPAWN_EGG, EntityType.PIGLIN). - put(Material.PILLAGER_SPAWN_EGG, EntityType.PILLAGER). - put(Material.POLAR_BEAR_SPAWN_EGG, EntityType.POLAR_BEAR). - put(Material.PUFFERFISH_SPAWN_EGG, EntityType.PUFFERFISH). - put(Material.RABBIT_SPAWN_EGG, EntityType.RABBIT). - put(Material.RAVAGER_SPAWN_EGG, EntityType.RAVAGER). - put(Material.SALMON_SPAWN_EGG, EntityType.SALMON). - put(Material.SHEEP_SPAWN_EGG, EntityType.SHEEP). - put(Material.SHULKER_SPAWN_EGG, EntityType.SHULKER). - put(Material.SILVERFISH_SPAWN_EGG, EntityType.SILVERFISH). - put(Material.SKELETON_HORSE_SPAWN_EGG, EntityType.SKELETON_HORSE). - put(Material.SKELETON_SPAWN_EGG, EntityType.SKELETON). - put(Material.SLIME_SPAWN_EGG, EntityType.SLIME). - put(Material.SPIDER_SPAWN_EGG, EntityType.SPIDER). - put(Material.SQUID_SPAWN_EGG, EntityType.SQUID). - put(Material.STRAY_SPAWN_EGG, EntityType.STRAY). - put(Material.STRIDER_SPAWN_EGG, EntityType.STRIDER). - put(Material.TRADER_LLAMA_SPAWN_EGG, EntityType.TRADER_LLAMA). - put(Material.TROPICAL_FISH_SPAWN_EGG, EntityType.TROPICAL_FISH). - put(Material.TURTLE_SPAWN_EGG, EntityType.TURTLE). - put(Material.VEX_SPAWN_EGG, EntityType.VEX). - put(Material.VILLAGER_SPAWN_EGG, EntityType.VILLAGER). - put(Material.VINDICATOR_SPAWN_EGG, EntityType.VINDICATOR). - put(Material.WANDERING_TRADER_SPAWN_EGG, EntityType.WANDERING_TRADER). - put(Material.WITCH_SPAWN_EGG, EntityType.WITCH). - put(Material.WITHER_SKELETON_SPAWN_EGG, EntityType.WITHER_SKELETON). - put(Material.WOLF_SPAWN_EGG, EntityType.WOLF). - put(Material.ZOGLIN_SPAWN_EGG, EntityType.ZOGLIN). - put(Material.ZOMBIE_SPAWN_EGG, EntityType.ZOMBIE). - put(Material.ZOMBIE_HORSE_SPAWN_EGG, EntityType.ZOMBIE_HORSE). - put(Material.ZOMBIFIED_PIGLIN_SPAWN_EGG, EntityType.ZOMBIFIED_PIGLIN). - put(Material.ZOMBIE_VILLAGER_SPAWN_EGG, EntityType.ZOMBIE_VILLAGER). - build(); + private static final BiMap SPAWN_EGGS = ImmutableBiMap.builder() + .put(Material.BAT_SPAWN_EGG, EntityType.BAT) + .put(Material.BEE_SPAWN_EGG, EntityType.BEE) + .put(Material.BLAZE_SPAWN_EGG, EntityType.BLAZE) + .put(Material.CAT_SPAWN_EGG, EntityType.CAT) + .put(Material.CAVE_SPIDER_SPAWN_EGG, EntityType.CAVE_SPIDER) + .put(Material.CHICKEN_SPAWN_EGG, EntityType.CHICKEN) + .put(Material.COD_SPAWN_EGG, EntityType.COD) + .put(Material.COW_SPAWN_EGG, EntityType.COW) + .put(Material.CREEPER_SPAWN_EGG, EntityType.CREEPER) + .put(Material.DOLPHIN_SPAWN_EGG, EntityType.DOLPHIN) + .put(Material.DONKEY_SPAWN_EGG, EntityType.DONKEY) + .put(Material.DROWNED_SPAWN_EGG, EntityType.DROWNED) + .put(Material.ELDER_GUARDIAN_SPAWN_EGG, EntityType.ELDER_GUARDIAN) + .put(Material.ENDERMAN_SPAWN_EGG, EntityType.ENDERMAN) + .put(Material.ENDERMITE_SPAWN_EGG, EntityType.ENDERMITE) + .put(Material.EVOKER_SPAWN_EGG, EntityType.EVOKER) + .put(Material.FOX_SPAWN_EGG, EntityType.FOX) + .put(Material.GHAST_SPAWN_EGG, EntityType.GHAST) + .put(Material.GUARDIAN_SPAWN_EGG, EntityType.GUARDIAN) + .put(Material.HOGLIN_SPAWN_EGG, EntityType.HOGLIN) + .put(Material.HORSE_SPAWN_EGG, EntityType.HORSE) + .put(Material.HUSK_SPAWN_EGG, EntityType.HUSK) + .put(Material.LLAMA_SPAWN_EGG, EntityType.LLAMA) + .put(Material.MAGMA_CUBE_SPAWN_EGG, EntityType.MAGMA_CUBE) + .put(Material.MOOSHROOM_SPAWN_EGG, EntityType.MUSHROOM_COW) + .put(Material.MULE_SPAWN_EGG, EntityType.MULE) + .put(Material.OCELOT_SPAWN_EGG, EntityType.OCELOT) + .put(Material.PANDA_SPAWN_EGG, EntityType.PANDA) + .put(Material.PARROT_SPAWN_EGG, EntityType.PARROT) + .put(Material.PHANTOM_SPAWN_EGG, EntityType.PHANTOM) + .put(Material.PIG_SPAWN_EGG, EntityType.PIG) + .put(Material.PIGLIN_BRUTE_SPAWN_EGG, EntityType.PIGLIN_BRUTE) + .put(Material.PIGLIN_SPAWN_EGG, EntityType.PIGLIN) + .put(Material.PILLAGER_SPAWN_EGG, EntityType.PILLAGER) + .put(Material.POLAR_BEAR_SPAWN_EGG, EntityType.POLAR_BEAR) + .put(Material.PUFFERFISH_SPAWN_EGG, EntityType.PUFFERFISH) + .put(Material.RABBIT_SPAWN_EGG, EntityType.RABBIT) + .put(Material.RAVAGER_SPAWN_EGG, EntityType.RAVAGER) + .put(Material.SALMON_SPAWN_EGG, EntityType.SALMON) + .put(Material.SHEEP_SPAWN_EGG, EntityType.SHEEP) + .put(Material.SHULKER_SPAWN_EGG, EntityType.SHULKER) + .put(Material.SILVERFISH_SPAWN_EGG, EntityType.SILVERFISH) + .put(Material.SKELETON_HORSE_SPAWN_EGG, EntityType.SKELETON_HORSE) + .put(Material.SKELETON_SPAWN_EGG, EntityType.SKELETON) + .put(Material.SLIME_SPAWN_EGG, EntityType.SLIME) + .put(Material.SPIDER_SPAWN_EGG, EntityType.SPIDER) + .put(Material.SQUID_SPAWN_EGG, EntityType.SQUID) + .put(Material.STRAY_SPAWN_EGG, EntityType.STRAY) + .put(Material.STRIDER_SPAWN_EGG, EntityType.STRIDER) + .put(Material.TRADER_LLAMA_SPAWN_EGG, EntityType.TRADER_LLAMA) + .put(Material.TROPICAL_FISH_SPAWN_EGG, EntityType.TROPICAL_FISH) + .put(Material.TURTLE_SPAWN_EGG, EntityType.TURTLE) + .put(Material.VEX_SPAWN_EGG, EntityType.VEX) + .put(Material.VILLAGER_SPAWN_EGG, EntityType.VILLAGER) + .put(Material.VINDICATOR_SPAWN_EGG, EntityType.VINDICATOR) + .put(Material.WANDERING_TRADER_SPAWN_EGG, EntityType.WANDERING_TRADER) + .put(Material.WITCH_SPAWN_EGG, EntityType.WITCH) + .put(Material.WITHER_SKELETON_SPAWN_EGG, EntityType.WITHER_SKELETON) + .put(Material.WOLF_SPAWN_EGG, EntityType.WOLF) + .put(Material.ZOGLIN_SPAWN_EGG, EntityType.ZOGLIN) + .put(Material.ZOMBIE_SPAWN_EGG, EntityType.ZOMBIE) + .put(Material.ZOMBIE_HORSE_SPAWN_EGG, EntityType.ZOMBIE_HORSE) + .put(Material.ZOMBIFIED_PIGLIN_SPAWN_EGG, EntityType.ZOMBIFIED_PIGLIN) + .put(Material.ZOMBIE_VILLAGER_SPAWN_EGG, EntityType.ZOMBIE_VILLAGER) + .build(); public static void init() { // Determine if there's any enchants missing names diff --git a/src/main/resources/materials.yml b/src/main/resources/materials.yml index 5de03ee6..ff99994f 100644 --- a/src/main/resources/materials.yml +++ b/src/main/resources/materials.yml @@ -686,6 +686,7 @@ PETRIFIED_OAK_SLAB: "Petrified Oak Slab" PHANTOM_MEMBRANE: "Phantom Membrane" PHANTOM_SPAWN_EGG: "Phantom Spawn Egg" PIGLIN_BANNER_PATTERN: "Snout Banner Pattern" +PIGLIN_BRUTE_SPAWN_EGG: "Piglin Brute Spawn Egg" PIGLIN_SPAWN_EGG: "Piglin Spawn Egg" PIG_SPAWN_EGG: "Pig Spawn Egg" PILLAGER_SPAWN_EGG: "Pillager Spawn Egg" From fdd7aa65b9995f7c23ee9334baff4225be7c0441 Mon Sep 17 00:00:00 2001 From: Cola Date: Tue, 2 Mar 2021 07:58:52 +0000 Subject: [PATCH 008/143] Maybe fix getCenteredInOrder From my perspective, the counter wasn't accounting for the row offset from the top, we simply just add on the row length to account for that and aswell as in the counter we add 1 since that doesn't occur if i is equal to lastElementLastCompleteRow --- .../civmodcore/inventorygui/components/ContentAligners.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/components/ContentAligners.java b/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/components/ContentAligners.java index fbadfffd..4d61a567 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/components/ContentAligners.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/components/ContentAligners.java @@ -48,7 +48,7 @@ public static ContentAligner getCenteredInOrder(int contentAmount, int windowSiz if (contentAmount % rowLength == 0) { offset = 1; } - int lastElementLastCompleteRow = ((contentAmount / rowLength) + offset) * rowLength - 1; + int lastElementLastCompleteRow = (((contentAmount / rowLength) + offset) * rowLength - 1) + rowLength; return new Counter(i -> { // just increment until we reach the last element in the last full row @@ -56,10 +56,10 @@ public static ContentAligner getCenteredInOrder(int contentAmount, int windowSiz return i + 1; } else { // jump to offset start of last row - int lengthLastRow = contentAmount - lastElementLastCompleteRow - 1; + int lengthLastRow = (contentAmount + rowLength) - lastElementLastCompleteRow - 1; int emptySlots = rowLength - lengthLastRow; int leftOffset = Math.max(1, emptySlots / 2); - return i + leftOffset; + return (i + 1) + leftOffset; } }, defaultNum); } From 522f3ada5ebd8be9267face0d21a5e668e690e99 Mon Sep 17 00:00:00 2001 From: Cola Date: Sat, 13 Mar 2021 09:59:39 +0000 Subject: [PATCH 009/143] Fix tab completion error Courtesy of ponycau --- src/main/java/vg/civcraft/mc/civmodcore/command/Trie.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/vg/civcraft/mc/civmodcore/command/Trie.java b/src/main/java/vg/civcraft/mc/civmodcore/command/Trie.java index 8e2770e6..74e13c00 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/command/Trie.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/command/Trie.java @@ -64,7 +64,7 @@ public List complete(String [] args) { return matches; } int elementsToRemove = args.length - 1; - for (int i = 0; i < args.length; i++) { + for (int i = 0; i < matches.size(); i++) { String mod = matches.get(i); int startingSpot = StringUtils.ordinalIndexOf(mod, " ", elementsToRemove) + 1; matches.set(i, mod.substring(startingSpot)); From a2933d965a067d239f4b770a1673daabc27b4b66 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 29 Mar 2021 07:18:10 +0100 Subject: [PATCH 010/143] Remove unnecessary config reload The just-saved default config wont have suddenly changed between the save and the reload. All this does is force every serialisable object to be re-initialised, probably creating a whole bunch of unnecessary database connections, item stacks, etc. --- src/main/java/vg/civcraft/mc/civmodcore/CoreConfigManager.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/vg/civcraft/mc/civmodcore/CoreConfigManager.java b/src/main/java/vg/civcraft/mc/civmodcore/CoreConfigManager.java index 384ed0b5..db7b4aef 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/CoreConfigManager.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/CoreConfigManager.java @@ -37,7 +37,6 @@ public CoreConfigManager(ACivMod plugin) { public final boolean parse() { this.plugin.info(ChatColor.BLUE + "Parsing config."); this.plugin.saveDefaultConfig(); - this.plugin.reloadConfig(); FileConfiguration config = this.plugin.getConfig(); // Parse debug value this.debug = config.getBoolean("debug", false); From 309c107caa7fec754eab12c0f0eef9a67b9a3c9f Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 5 Apr 2021 16:41:20 +0100 Subject: [PATCH 011/143] Add EnumSetting --- .../playersettings/impl/EnumSetting.java | 95 +++++++++++++++++++ .../civmodcore/world/ChunkLoadedFilter.java | 2 +- 2 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/EnumSetting.java diff --git a/src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/EnumSetting.java b/src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/EnumSetting.java new file mode 100644 index 00000000..9c0b67f7 --- /dev/null +++ b/src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/EnumSetting.java @@ -0,0 +1,95 @@ +package vg.civcraft.mc.civmodcore.playersettings.impl; + +import java.util.Comparator; +import java.util.Objects; +import java.util.stream.Collectors; +import org.apache.commons.lang3.EnumUtils; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; +import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils; +import vg.civcraft.mc.civmodcore.inventorygui.Clickable; +import vg.civcraft.mc.civmodcore.inventorygui.IClickable; +import vg.civcraft.mc.civmodcore.inventorygui.MultiPageView; +import vg.civcraft.mc.civmodcore.playersettings.PlayerSetting; +import vg.civcraft.mc.civmodcore.playersettings.gui.MenuSection; + +public class EnumSetting> extends PlayerSetting { + + private final Class enumClass; + + public EnumSetting(final JavaPlugin owningPlugin, + final T defaultValue, + final String niceName, + final String identifier, + final ItemStack gui, + final String description, + final boolean canBeChangedByPlayer, + final Class enumClass) { + super(owningPlugin, defaultValue, niceName, identifier, gui, description, canBeChangedByPlayer); + this.enumClass = Objects.requireNonNull(enumClass); + } + + @Override + public T deserialize(final String raw) { + return EnumUtils.getEnum(this.enumClass, raw, getDefaultValue()); + } + + @Override + public boolean isValidValue(final String raw) { + return EnumUtils.isValidEnum(this.enumClass, raw); + } + + @Override + public String serialize(final T value) { + if (value == null) { + return null; + } + return value.name(); + } + + @Override + public String toText(final T value) { + if (value == null) { + return ""; + } + return value.name(); + } + + @Override + public void handleMenuClick(final Player player, final MenuSection menu) { + final T currentValue = getValue(player); + + final var view = new MultiPageView(player, + EnumUtils.getEnumList(this.enumClass).stream() + .sorted(Comparator.comparing(Enum::name)) + .map(value -> { + final var item = new ItemStack(value == currentValue ? Material.GREEN_DYE : Material.RED_DYE); + ItemUtils.setDisplayName(item, ChatColor.GOLD + toText(value)); + return new Clickable(item) { + @Override + protected void clicked(final Player ignored) { + setValue(player, value); + handleMenuClick(player, menu); + } + }; + }) + .collect(Collectors.toList()), + getNiceName(), + true); + + final var backButtonItem = new ItemStack(Material.ARROW); + ItemUtils.setDisplayName(backButtonItem, ChatColor.AQUA + "Go back to " + menu.getName()); + view.setMenuSlot(new Clickable(backButtonItem) { + @Override + public void clicked(final Player clicker) { + menu.showScreen(clicker); + } + }, 0); + + view.showScreen(); + } + +} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/world/ChunkLoadedFilter.java b/src/main/java/vg/civcraft/mc/civmodcore/world/ChunkLoadedFilter.java index 11a5f176..4c081df7 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/world/ChunkLoadedFilter.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/world/ChunkLoadedFilter.java @@ -11,7 +11,7 @@ /** * Utility to use with {@link java.util.stream.Stream} to efficiently remove elements from unloaded chunks. */ -public class ChunkLoadedFilter { +public final class ChunkLoadedFilter { /** * Creates a new filter function for a given world to remove elements representing blocks in unloaded chunks. From 5d16812611a2f3a4c3ac69946ba108f650b18960 Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 7 Apr 2021 22:52:45 +0100 Subject: [PATCH 012/143] Update PseudoServer to 1.16.5 --- .../java/org/bukkit/pseudo/PseudoServer.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/test/java/org/bukkit/pseudo/PseudoServer.java b/src/test/java/org/bukkit/pseudo/PseudoServer.java index ada193c6..12b6c8a6 100644 --- a/src/test/java/org/bukkit/pseudo/PseudoServer.java +++ b/src/test/java/org/bukkit/pseudo/PseudoServer.java @@ -13,6 +13,8 @@ import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; import org.apache.commons.lang3.NotImplementedException; import org.bukkit.BanList; import org.bukkit.Bukkit; @@ -62,6 +64,7 @@ import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scoreboard.ScoreboardManager; import org.bukkit.util.CachedServerIcon; +import org.checkerframework.checker.nullness.qual.NonNull; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -325,6 +328,11 @@ public World getWorld(@NotNull final UUID uuid) { throw new NotImplementedException(); } + @Override + public @Nullable World getWorld(@NotNull final NamespacedKey namespacedKey) { + throw new NotImplementedException(); + } + @Nullable @Override public MapView getMap(final int i) { @@ -454,6 +462,11 @@ public int broadcast(@NotNull final String s, @NotNull final String s1) { throw new NotImplementedException(); } + @Override + public int broadcast(@NotNull final Component component, @NotNull final String s) { + throw new NotImplementedException(); + } + @NotNull @Override public OfflinePlayer getOfflinePlayer(@NotNull final String s) { @@ -553,6 +566,11 @@ public Inventory createInventory(@Nullable final InventoryHolder inventoryHolder throw new NotImplementedException(); } + @Override + public @NotNull Inventory createInventory(@Nullable final InventoryHolder inventoryHolder, @NotNull final InventoryType inventoryType, @NotNull final Component component) { + throw new NotImplementedException(); + } + @NotNull @Override public Inventory createInventory(@Nullable final InventoryHolder inventoryHolder, @NotNull final InventoryType inventoryType, @NotNull final String s) { @@ -565,12 +583,22 @@ public Inventory createInventory(@Nullable final InventoryHolder inventoryHolder throw new NotImplementedException(); } + @Override + public @NotNull Inventory createInventory(@Nullable final InventoryHolder inventoryHolder, final int i, @NotNull final Component component) throws IllegalArgumentException { + throw new NotImplementedException(); + } + @NotNull @Override public Inventory createInventory(@Nullable final InventoryHolder inventoryHolder, final int i, @NotNull final String s) throws IllegalArgumentException { throw new NotImplementedException(); } + @Override + public @NotNull Merchant createMerchant(@Nullable final Component component) { + throw new NotImplementedException(); + } + @NotNull @Override public Merchant createMerchant(@Nullable final String s) { @@ -607,12 +635,22 @@ public boolean isPrimaryThread() { throw new NotImplementedException(); } + @Override + public @NotNull Component motd() { + throw new NotImplementedException(); + } + @NotNull @Override public String getMotd() { throw new NotImplementedException(); } + @Override + public @Nullable Component shutdownMessage() { + throw new NotImplementedException(); + } + @Nullable @Override public String getShutdownMessage() { @@ -866,4 +904,9 @@ public Set getListeningPluginChannels() { throw new NotImplementedException(); } + @Override + public @NonNull Iterable audiences() { + throw new NotImplementedException(); + } + } From 1fba6a5fa525e48db79fcd8bca8e73f0c21726e4 Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 8 Apr 2021 18:05:59 +0100 Subject: [PATCH 013/143] Remove a lot of deprecated clutter --- .../mc/civmodcore/CivModCorePlugin.java | 14 +- .../civcraft/mc/civmodcore/api/BlockAPI.java | 390 --------- .../civcraft/mc/civmodcore/api/ColourAPI.java | 84 -- .../mc/civmodcore/api/EnchantAPI.java | 155 ---- .../mc/civmodcore/api/EnchantNames.java | 94 --- .../civcraft/mc/civmodcore/api/EntityAPI.java | 66 -- .../mc/civmodcore/api/InventoryAPI.java | 279 ------ .../civcraft/mc/civmodcore/api/ItemAPI.java | 420 ---------- .../civcraft/mc/civmodcore/api/ItemNames.java | 37 - .../mc/civmodcore/api/LocationAPI.java | 156 ---- .../mc/civmodcore/api/MaterialAPI.java | 793 ------------------ .../mc/civmodcore/api/NamespaceAPI.java | 91 -- .../civcraft/mc/civmodcore/api/PotionAPI.java | 65 -- .../mc/civmodcore/api/PotionNames.java | 203 ----- .../civcraft/mc/civmodcore/api/RecipeAPI.java | 93 -- .../mc/civmodcore/api/SpawnEggAPI.java | 136 --- .../civcraft/mc/civmodcore/api/ToolAPI.java | 48 -- .../mc/civmodcore/api/TreeTypeAPI.java | 121 --- .../civcraft/mc/civmodcore/api/WorldAPI.java | 90 -- .../mc/civmodcore/api/package-info.java | 7 - .../civmodcore/chatDialog/ChatListener.java | 36 - .../mc/civmodcore/chatDialog/Dialog.java | 67 -- .../civmodcore/chatDialog/DialogManager.java | 45 - .../mc/civmodcore/chatDialog/LDialog.java | 36 - .../civmodcore/chatDialog/package-info.java | 4 - .../mc/civmodcore/command/MailBoxAPI.java | 56 -- .../mc/civmodcore/serialization/NBTCache.java | 20 - .../civmodcore/serialization/NBTCompound.java | 33 - .../serialization/NBTCompoundList.java | 79 -- .../mc/civmodcore/util/EnumUtils.java | 72 -- .../vg/civcraft/mc/civmodcore/util/Guard.java | 43 - .../mc/civmodcore/util/Iteration.java | 350 -------- .../civcraft/mc/civmodcore/util/MapUtils.java | 164 ---- .../mc/civmodcore/util/NullCoalescing.java | 185 ---- .../serialization/ExampleSerializable.java | 14 +- .../serialization/SerializationTester.java | 29 - 36 files changed, 15 insertions(+), 4560 deletions(-) delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/BlockAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/ColourAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/EnchantAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/EnchantNames.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/EntityAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/InventoryAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/ItemAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/ItemNames.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/LocationAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/MaterialAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/NamespaceAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/PotionAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/PotionNames.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/RecipeAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/SpawnEggAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/ToolAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/TreeTypeAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/WorldAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/package-info.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/chatDialog/ChatListener.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/chatDialog/Dialog.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/chatDialog/DialogManager.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/chatDialog/LDialog.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/chatDialog/package-info.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/command/MailBoxAPI.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCache.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompoundList.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/EnumUtils.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/Guard.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/Iteration.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/MapUtils.java delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/NullCoalescing.java diff --git a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java index 8321dc59..05e8b92b 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java @@ -5,9 +5,7 @@ import org.bukkit.Bukkit; import org.bukkit.configuration.serialization.ConfigurationSerialization; import org.bukkit.entity.HumanEntity; -import vg.civcraft.mc.civmodcore.api.PotionNames; import vg.civcraft.mc.civmodcore.chat.dialog.DialogManager; -import vg.civcraft.mc.civmodcore.chatDialog.ChatListener; import vg.civcraft.mc.civmodcore.command.AikarCommandManager; import vg.civcraft.mc.civmodcore.dao.ManagedDatasource; import vg.civcraft.mc.civmodcore.events.CustomEventMapper; @@ -34,17 +32,13 @@ import vg.civcraft.mc.civmodcore.world.WorldTracker; import vg.civcraft.mc.civmodcore.world.operations.ChunkOperationManager; -@SuppressWarnings("deprecation") public final class CivModCorePlugin extends ACivMod { private static CivModCorePlugin instance; private GlobalChunkMetaManager chunkMetaManager; - private ManagedDatasource database; - private WorldIDManager worldIdManager; - private AikarCommandManager manager; @Override @@ -83,7 +77,6 @@ public void onEnable() { registerListener(new ClickableInventoryListener()); registerListener(new PagedGUIManager()); registerListener(DialogManager.INSTANCE); - registerListener(new ChatListener()); registerListener(new ScoreBoardListener()); registerListener(new CustomEventMapper()); registerListener(new WorldTracker()); @@ -104,16 +97,13 @@ public void registerCommands() { SpawnEggUtils.init(); TreeTypeUtils.init(); BottomLineAPI.init(); - newCommandHandler.registerCommand(new ConfigSetAnyCommand()); - newCommandHandler.registerCommand(new ConfigGetAnyCommand()); - // Deprecated - PotionNames.loadPotionNames(); + this.newCommandHandler.registerCommand(new ConfigSetAnyCommand()); + this.newCommandHandler.registerCommand(new ConfigGetAnyCommand()); } @Override public void onDisable() { Bukkit.getOnlinePlayers().forEach(HumanEntity::closeInventory); - PotionNames.resetPotionNames(); ChunkMetaAPI.saveAll(); this.chunkMetaManager = null; // Disconnect database diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/BlockAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/BlockAPI.java deleted file mode 100644 index 1655203e..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/BlockAPI.java +++ /dev/null @@ -1,390 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import static vg.civcraft.mc.civmodcore.util.NullCoalescing.chain; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; -import net.minecraft.server.v1_16_R3.BlockProperties; -import net.minecraft.server.v1_16_R3.IBlockState; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.type.Chest; -import org.bukkit.block.data.type.Switch; -import org.bukkit.craftbukkit.v1_16_R3.CraftWorld; -import org.bukkit.craftbukkit.v1_16_R3.block.CraftBlock; -import org.bukkit.util.BlockIterator; -import vg.civcraft.mc.civmodcore.world.WorldUtils; - -/** - * Class of utility functions for Blocks, and BlockFaces referencing Blocks around a Block. - * - * @deprecated Use {@link WorldUtils} and {@link vg.civcraft.mc.civmodcore.world.BlockProperties} instead. - */ -@Deprecated -public final class BlockAPI { - - private BlockAPI() { } - - /** - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#ALL_SIDES} instead. - */ - @Deprecated - public static final List ALL_SIDES = ImmutableList.of( - BlockFace.UP, - BlockFace.DOWN, - BlockFace.NORTH, - BlockFace.SOUTH, - BlockFace.WEST, - BlockFace.EAST); - - /** - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#PLANAR_SIDES} instead. - */ - @Deprecated - public static final List PLANAR_SIDES = ImmutableList.of( - BlockFace.NORTH, - BlockFace.SOUTH, - BlockFace.WEST, - BlockFace.EAST); - - private static final Map> blockStateByIdentifier = new HashMap<>(); - - static { - for(Field field : BlockProperties.class.getFields()) { - if (!IBlockState.class.isAssignableFrom(field.getType())) { - continue; - } - field.setAccessible(true); - IBlockState bs; - try { - bs = (IBlockState)field.get(null); - } catch (IllegalArgumentException | IllegalAccessException e) { - e.printStackTrace(); - continue; - } - //when updating, search for the method returning the string given in the constructor - String key = bs.getName(); - blockStateByIdentifier.put(key, bs); - } - } - - /** - *

Checks whether this block is valid and so can be handled reasonably without error.

- * - *

Note: This will return true even if the block is air. Use {@link MaterialAPI#isAir(Material)} as an - * additional check if this is important to you.

- * - * @param block The block to check. - * @return Returns true if the block is valid. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#isValidBlock(Block)} instead. - */ - @Deprecated - public static boolean isValidBlock(Block block) { - if (block == null) { - return false; - } - if (block.getType() == null) { // Do not remove this, it's not necessarily certain - return false; - } - return LocationAPI.isValidLocation(block.getLocation()); - } - - /** - * Returns a map of a block's relatives. - * - * @param block The block to get the relatives of. - * @param faces An array of the faces, which will be the keys of the returned map. - * @return Returns an immutable map of the block's relatives. - * - * @deprecated Use - * {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getBlockSidesMapped(Block, Collection, boolean)} instead. - */ - @Deprecated - public static Map getBlockSidesMapped(Block block, BlockFace... faces) { - if (faces == null || faces.length < 1) { - return Collections.unmodifiableMap(new EnumMap<>(BlockFace.class)); - } - else { - return getBlockSidesMapped(block, Arrays.asList(faces)); - } - } - - /** - * Returns a map of a block's relatives. - * - * @param block The block to get the relatives of. - * @param faces A collection of the faces, which will be the keys of the returned map. - * @return Returns an immutable map of the block's relatives. - * - * @deprecated Use - * {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getBlockSidesMapped(Block, Collection, boolean)} instead. - */ - @Deprecated - public static Map getBlockSidesMapped(Block block, Collection faces) { - EnumMap results = new EnumMap<>(BlockFace.class); - if (block != null && faces != null) { - faces.forEach(face -> results.put(face, block.getRelative(face))); - } - return Collections.unmodifiableMap(results); - } - - /** - * Returns a map of a block's relatives. - * - * @param block The block to get the relatives of. - * @param faces A collection of the faces, which will be the keys of the returned map. - * @return Returns an immutable map of the block's relatives. - * - * @deprecated Use - * {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getBlockSides(Block, Collection, boolean)} instead. - */ - @Deprecated - public static List getBlockSides(Block block, Collection faces) { - if (block == null || faces == null) { - throw new IllegalArgumentException("One of the args passed was null"); - } - if (faces.isEmpty()) { - return Collections.emptyList(); - } - return faces.stream().map(block::getRelative).collect(Collectors.toList()); - } - - /** - * Returns a map of all the block's relatives. - * - * @param block The block to get all the relatives of. - * @return Returns an immutable map of all the block's relatives. - * - * @deprecated Use - * {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getAllBlockSidesMapped(Block, boolean)} instead. - */ - @Deprecated - public static Map getAllSidesMapped(Block block) { - return getBlockSidesMapped(block, ALL_SIDES); - } - - /** - * Returns a list of all the block's relatives. - * - * @param block The block to get all the relatives of. - * @return Returns an immutable list of all the block's relatives. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getAllBlockSides(Block, boolean)} instead. - */ - @Deprecated - public static List getAllSides(Block block) { - return getBlockSides(block, ALL_SIDES); - } - - /** - * Returns a map of all the block's planar relatives. - * - * @param block The block to get the planar relatives of. - * @return Returns an immutable map of all the block's planar relatives. - * - * @deprecated Use - * {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getPlanarBlockSidesMapped(Block, boolean)} instead. - */ - @Deprecated - public static Map getPlanarSidesMapped(Block block) { - return getBlockSidesMapped(block, PLANAR_SIDES); - } - - /** - * Returns a list of all the block's planar relatives. - * - * @param block The block to get the planar relatives of. - * @return Returns an immutable list of all the block's planar relatives. - * - * @deprecated Use - * {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getPlanarBlockSides(Block, boolean)} instead. - */ - @Deprecated - public static List getPlanarSides(Block block) { - return getBlockSides(block, PLANAR_SIDES); - } - - /** - * Turns once in a clockwise direction. - * - * @param face The starting face, which must exist and be planar. - * @return Returns the next planar face in a clockwise direction. - * - * @exception IllegalArgumentException Throws if the given face is null or non-planar. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#turnClockwise(BlockFace)} instead. - */ - @Deprecated - public static BlockFace turnClockwise(BlockFace face) { - Preconditions.checkArgument(face != null); - Preconditions.checkArgument(PLANAR_SIDES.contains(face)); - switch (face) { - default: - case NORTH: - return BlockFace.EAST; - case EAST: - return BlockFace.SOUTH; - case SOUTH: - return BlockFace.WEST; - case WEST: - return BlockFace.NORTH; - } - } - - /** - * Turns once in a anti-clockwise direction. - * - * @param face The starting face, which must exist and be planar. - * @return Returns the next planar face in a anti-clockwise direction. - * - * @exception IllegalArgumentException Throws if the given face is null or non-planar. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#turnAntiClockwise(BlockFace)} instead. - */ - @Deprecated - public static BlockFace turnAntiClockwise(BlockFace face) { - Preconditions.checkArgument(face != null); - Preconditions.checkArgument(PLANAR_SIDES.contains(face)); - switch (face) { - default: - case NORTH: - return BlockFace.WEST; - case EAST: - return BlockFace.NORTH; - case SOUTH: - return BlockFace.EAST; - case WEST: - return BlockFace.SOUTH; - } - } - - /** - * Gets the {@link BlockFace} this attachable is attached to. This exists as - * {@link org.bukkit.block.data.Directional} has odd behaviour whereby if attached to the top or bottom of a block, - * the direction is the rotation of the block, rather than the attached face. - * - * @param attachable The Switch, which is an instance of {@link BlockData}. So do your own checks beforehand. - * @return Returns the block face the given attachable is attached to, or null. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getAttachedFace(Switch)} instead. - */ - @Deprecated - public static BlockFace getAttachedFace(Switch attachable) { - if (attachable == null) { - return null; - } - switch (attachable.getAttachedFace()) { - case CEILING: - return BlockFace.DOWN; - case FLOOR: - return BlockFace.UP; - case WALL: - return attachable.getFacing().getOppositeFace(); - default: - return null; - } - } - - /** - * Attempts to get the other block of a double chest. - * - * @param block The block that represents the double chest block you already have. - * @return Returns the other block or null if none can be found, or if the given block isn't that of a double chest. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getOtherDoubleChestBlock(Block, boolean)} - * instead. - */ - @Deprecated - public static Block getOtherDoubleChestBlock(Block block) { - if (!isValidBlock(block)) { - return null; - } - Chest chest = chain(() -> (Chest) block.getBlockData()); - if (chest == null) { - return null; - } - switch (chest.getType()) { - case LEFT: // This block is left side - return block.getRelative(turnClockwise(chest.getFacing())); - case RIGHT: - return block.getRelative(turnAntiClockwise(chest.getFacing())); - default: - case SINGLE: - return null; - } - } - - /** - * Creates a {@link BlockIterator} from a block's perspective, which is lacking from its constructors, which are - * more focused on entities. Keep in mind that the first returned block will likely be the given block parameter. - * - * @param block The block to start the iterator from. - * @param face The direction at which the iterator should iterate. - * @param range The distance the iterator should iterate. - * @return Returns a new instance of an BlockIterator. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getBlockIterator(Block, BlockFace, int)} - * instead. - */ - @Deprecated - public static BlockIterator getBlockIterator(Block block, BlockFace face, int range) { - if (!BlockAPI.isValidBlock(block)) { - throw new IllegalArgumentException("Cannot create a block iterator from a null block."); - } - if (face == null || face == BlockFace.SELF) { - throw new IllegalArgumentException("Block iterator requires a valid direction."); - } - if (range <= 0) { - throw new IllegalArgumentException("Block iterator requires a range of 1 or higher."); - } - return new BlockIterator(block.getWorld(), block.getLocation().toVector(), face.getDirection(), 0, range); - } - - /** - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.BlockProperties#setBlockProperty(Block, String, String)} - * instead. - */ - @Deprecated - public static boolean setBlockProperty(Block block, String key, String value) { - //we need this wrapper method to trick the java generics - return innerSetBlockProperty(block, key, value); - } - - // WHY IS THIS PUBLIC IF IT'S INNER? - /** - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.BlockProperties#setBlockProperty(Block, String, String)} - * instead. - */ - @Deprecated - public static > boolean innerSetBlockProperty(Block block, String key, String value) { - @SuppressWarnings("unchecked") - IBlockState state = (IBlockState) blockStateByIdentifier.get(key); - if (state == null) { - return false; - } - Optional opt = state.b(value); - if (!opt.isPresent()) { - return false; - } - V valueToSet = state.b(value).get(); - CraftBlock cb = (CraftBlock) block; - CraftWorld world = (CraftWorld) block.getWorld(); - //no idea what the last integer parameter does, I found 2 and 3 being used in NMS code and stuck to that - world.getHandle().setTypeAndData(cb.getPosition(), cb.getNMS().set( state, valueToSet), 2); - return true; - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/ColourAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/ColourAPI.java deleted file mode 100644 index 4b810645..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/ColourAPI.java +++ /dev/null @@ -1,84 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import java.awt.Color; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import net.md_5.bungee.api.ChatColor; -import vg.civcraft.mc.civmodcore.chat.ChatUtils; - -/** - * @deprecated Use {@link ChatUtils} instead. - */ -public class ColourAPI { - - /** - * This is necessary as {@link ChatColor#values()} has all colours and all formats. - * - * @deprecated Use {@link ChatUtils#COLOURS} instead. - */ - @Deprecated - public static final List COLOURS = Collections.unmodifiableList(Arrays.asList( - ChatColor.BLACK, - ChatColor.DARK_BLUE, - ChatColor.DARK_GREEN, - ChatColor.DARK_AQUA, - ChatColor.DARK_RED, - ChatColor.DARK_PURPLE, - ChatColor.GOLD, - ChatColor.GRAY, - ChatColor.DARK_GRAY, - ChatColor.BLUE, - ChatColor.GREEN, - ChatColor.AQUA, - ChatColor.RED, - ChatColor.LIGHT_PURPLE, - ChatColor.YELLOW - )); - - /** - * Converts an RGB value into a Bungee ChatColor. - * - * @param r The red value. - * @param g The green value. - * @param b The blue value. - * @return Returns a valid Bungee ChatColor. - * - * @deprecated Use {@link ChatUtils#fromRGB(byte, byte, byte)} instead. - */ - @Deprecated - public static ChatColor fromRGB(final byte r, final byte g, final byte b) { - return ChatColor.of(new Color(r, g, b)); - } - - /** - * Attempts to collapse an RGB colour to established Minecraft colours. - * - * @param colour The given RGB colour. - * @return Returns the closest Minecraft match, or null. - * - * @deprecated Use {@link ChatUtils#collapseColour(ChatColor)} instead. - */ - @Deprecated - public static ChatColor collapseColour(final ChatColor colour) { - if (colour == null) { - return null; - } - final Color color = colour.getColor(); - ChatColor nearestColour = null; - double nearestDistance = Double.MAX_VALUE; - for (final ChatColor currentColour : COLOURS) { - final Color currentColor = currentColour.getColor(); - final double distance = Math.sqrt( - Math.pow(color.getRed() - currentColor.getRed(), 2) - - Math.pow(color.getGreen() - currentColor.getGreen(), 2) - - Math.pow(color.getBlue() - currentColor.getBlue(), 2)); - if (nearestDistance > distance) { - nearestDistance = distance; - nearestColour = currentColour; - } - } - return nearestColour; - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/EnchantAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/EnchantAPI.java deleted file mode 100644 index b458bb80..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/EnchantAPI.java +++ /dev/null @@ -1,155 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import java.util.Map; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import vg.civcraft.mc.civmodcore.inventory.items.EnchantUtils; - -/** - * Class of static APIs for Enchantments. - * - * @deprecated Use {@link EnchantUtils} instead. - */ -@Deprecated -public final class EnchantAPI { - - /** - * Determines whether an enchantment is considered safe. - * - * @param enchantment The enchantment to validate. - * @param level The enchantment level to validate. - * @return Returns true if the enchantment is not null, and the level is within the acceptable bounds. - * - * @see Enchantment#getStartLevel() The starting level. A valid level cannot be below this. - * @see Enchantment#getMaxLevel() The maximum level. A valid level cannot be above this. - * - * @deprecated Use {@link EnchantUtils#isSafeEnchantment(Enchantment, int)} instead. - */ - @Deprecated - public static boolean isSafeEnchantment(Enchantment enchantment, int level) { - return enchantment != null && level >= enchantment.getStartLevel() && level <= enchantment.getMaxLevel(); - } - - /** - * Attempts to retrieve an enchantment by its slug, display name, and abbreviation. - * - * @param value The value to search for a matching enchantment by. - * @return Returns a matched enchantment or null. - * - * @deprecated Use {@link EnchantUtils#getEnchantment(String)} instead. - */ - @Deprecated - @SuppressWarnings("deprecation") - public static Enchantment getEnchantment(String value) { - if (Strings.isNullOrEmpty(value)) { - return null; - } - Enchantment enchantment = Enchantment.getByKey(NamespaceAPI.fromString(value)); - if (enchantment != null) { - return enchantment; - } - enchantment = Enchantment.getByName(value.toUpperCase()); - if (enchantment != null) { - return enchantment; - } - EnchantNames.SearchResult search = EnchantNames.findByDisplayName(value); - if (search != null) { - return search.getEnchantment(); - } - search = EnchantNames.findByAbbreviation(value); - if (search != null) { - return search.getEnchantment(); - } - return null; - } - - /** - * Gets the enchantments from an item. - * - * @param item The item to retrieve the enchantments from. - * @return Returns the item's enchantments, which are never null. - * - * @deprecated Use {@link EnchantUtils#getEnchantments(ItemStack)} instead. - */ - @Deprecated - public static Map getEnchantments(ItemStack item) { - Preconditions.checkArgument(ItemAPI.isValidItem(item)); - return item.getEnchantments(); - } - - /** - * Adds a safe enchantment to an item. - * - * @param item The item to add the enchantment to. - * @param enchantment The enchantment to add to the item. - * @param level The level of the enchantment to add to the item. - * @return Returns true if the enchantment was successfully added. - * - * @see EnchantAPI#isSafeEnchantment(Enchantment, int) - * - * @deprecated Use {@link EnchantUtils#addEnchantment(ItemStack, Enchantment, int)} instead. - */ - @Deprecated - public static boolean addEnchantment(ItemStack item, Enchantment enchantment, int level) { - return addEnchantment(item, enchantment, level, true); - } - - /** - * Adds an enchantment to an item. - * - * @param item The item to add the enchantment to. - * @param enchantment The enchantment to add to the item. - * @param level The level of the enchantment to add to the item. - * @param onlyAllowSafeEnchantments Requires enchantments to be safe if set to true. - * @return Returns true if the enchantment was successfully added. - * - * @see EnchantAPI#isSafeEnchantment(Enchantment, int) - * - * @deprecated Use {@link EnchantUtils#addEnchantment(ItemStack, Enchantment, int, boolean)} instead. - */ - @Deprecated - public static boolean addEnchantment(ItemStack item, Enchantment enchantment, int level, - boolean onlyAllowSafeEnchantments) { - Preconditions.checkArgument(ItemAPI.isValidItem(item)); - return ItemAPI.handleItemMeta(item, (ItemMeta meta) -> - meta.addEnchant(enchantment, level, !onlyAllowSafeEnchantments)); - } - - /** - * Removes an enchantment from an item. - * - * @param item The item to remove the enchantment from. - * @param enchant The enchantment to remove from the item. - * @return Returns true if the enchantment was successfully removed. - * - * @deprecated Use {@link EnchantUtils#removeEnchantment(ItemStack, Enchantment)} instead. - */ - @Deprecated - public static boolean removeEnchantment(ItemStack item, Enchantment enchant) { - Preconditions.checkArgument(ItemAPI.isValidItem(item)); - if (enchant == null) { - return true; - } - return ItemAPI.handleItemMeta(item, (ItemMeta meta) -> meta.removeEnchant(enchant)); - } - - /** - * Removes all enchantments from an item. - * - * @param item The item to clear enchantment from. - * - * @deprecated Use {@link EnchantUtils#clearEnchantments(ItemStack)} instead. - */ - @Deprecated - public static void clearEnchantments(ItemStack item) { - Preconditions.checkArgument(ItemAPI.isValidItem(item)); - ItemAPI.handleItemMeta(item, (ItemMeta meta) -> { - meta.getEnchants().forEach((key, value) -> meta.removeEnchant(key)); - return true; - }); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/EnchantNames.java b/src/main/java/vg/civcraft/mc/civmodcore/api/EnchantNames.java deleted file mode 100644 index 56bff356..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/EnchantNames.java +++ /dev/null @@ -1,94 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import com.google.common.base.Strings; -import java.util.Objects; -import org.bukkit.enchantments.Enchantment; -import vg.civcraft.mc.civmodcore.inventory.items.EnchantUtils; - -/** - * @deprecated Use {@link EnchantUtils} instead. - */ -@Deprecated -public final class EnchantNames { - - @Deprecated - public static SearchResult findByEnchantment(Enchantment enchant) { - if (enchant == null) { - return null; - } - return new SearchResult(enchant, - EnchantUtils.getEnchantAbbreviation(enchant), - EnchantUtils.getEnchantNiceName(enchant)); - } - - @Deprecated - public static SearchResult findByAbbreviation(String abbreviation) { - if (Strings.isNullOrEmpty(abbreviation)) { - return null; - } - final Enchantment found = EnchantUtils.getEnchantment(abbreviation); - if (found == null) { - return null; - } - return new SearchResult(found, abbreviation, EnchantUtils.getEnchantNiceName(found)); - } - - @Deprecated - public static SearchResult findByDisplayName(String displayName) { - if (Strings.isNullOrEmpty(displayName)) { - return null; - } - final Enchantment found = EnchantUtils.getEnchantment(displayName); - if (found == null) { - return null; - } - return new SearchResult(found, EnchantUtils.getEnchantAbbreviation(found), displayName); - } - - /** - * This class represents a data set for a particular enchantment. - */ - @Deprecated - public static final class SearchResult { - - private final Enchantment enchantment; - - private final String abbreviation; - - private final String displayName; - - private SearchResult(Enchantment enchantment, String abbreviation, String displayName) { - this.enchantment = enchantment; - this.abbreviation = abbreviation; - this.displayName = displayName; - } - - /** - * @return Returns the enchantment itself. - */ - public Enchantment getEnchantment() { - return this.enchantment; - } - - /** - * @return Returns the enchantment's official abbreviation. - */ - public String getAbbreviation() { - return this.abbreviation; - } - - /** - * @return Returns the enchantment's official display name. - */ - public String getDisplayName() { - return this.displayName; - } - - @Override - public int hashCode() { - return Objects.hash(this.enchantment, this.displayName, this.abbreviation); - } - - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/EntityAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/EntityAPI.java deleted file mode 100644 index 82d16df1..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/EntityAPI.java +++ /dev/null @@ -1,66 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import com.google.common.base.Strings; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import vg.civcraft.mc.civmodcore.entities.EntityUtils; - -/** - * Class of static APIs for Entities. - * - * @deprecated Use {@link EntityUtils} instead. - */ -@Deprecated -public final class EntityAPI { - - /** - * Attempts to retrieve an entity type by its slug or id. - * - * @param value The value to search for a matching entity type by. - * @return Returns a matched entity type or null. - * - * @deprecated Use {@link EntityUtils#getEntityType(String)} instead. - */ - @Deprecated - public static EntityType getEntityType(String value) { - if (Strings.isNullOrEmpty(value)) { - return null; - } - try { - return EntityType.valueOf(value.toUpperCase()); - } - catch (Exception ignored) { } - try { - EntityType type = EntityType.fromId(Short.parseShort(value)); - if (type != null) { - return type; - } - } - catch (Exception ignored) { } - return null; - } - - /** - * Checks whether an entity is a player. - * - * @param entity The entity to test. - * @return Returns true if the entity is a player. - * - * @deprecated Use {@link EntityUtils#isPlayer(Entity)} instead. - */ - @Deprecated - public static boolean isPlayer(Entity entity) { - if (entity == null) { - return false; - } - if (entity.getType() != EntityType.PLAYER) { - return false; - } - if (!(entity instanceof Player)) { - return false; - } - return true; - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/InventoryAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/InventoryAPI.java deleted file mode 100644 index c1ad9007..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/InventoryAPI.java +++ /dev/null @@ -1,279 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; -import org.apache.commons.lang3.ArrayUtils; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import vg.civcraft.mc.civmodcore.inventory.ClonedInventory; -import vg.civcraft.mc.civmodcore.inventory.InventoryUtils; -import vg.civcraft.mc.civmodcore.util.Iteration; - -/** - * @deprecated Use {@link InventoryUtils} instead. - */ -@Deprecated -public final class InventoryAPI { - - /** - * Tests an inventory to see if it's valid. - * - * @param inventory The inventory to test. - * @return Returns true if it's more likely than not valid. - * - * @deprecated Use {@link InventoryUtils#isValidInventory(Inventory)} instead. - */ - @Deprecated - public static boolean isValidInventory(Inventory inventory) { - if (inventory == null) { - return false; - } - if (inventory.getSize() <= 0) { - return false; - } - return true; - } - - /** - * Get the players viewing an inventory. - * - * @param inventory The inventory to get the viewers of. - * @return Returns a list of players. Returns an empty list if the inventory is null. - * - * @deprecated Use {@link InventoryUtils#isValidInventory(Inventory)} instead. - */ - @Deprecated - public static List getViewingPlayers(Inventory inventory) { - if (!isValidInventory(inventory)) { - return new ArrayList<>(); - } - return inventory.getViewers().stream(). - map((entity) -> EntityAPI.isPlayer(entity) ? (Player) entity : null). - filter(Objects::nonNull). - collect(Collectors.toCollection(ArrayList::new)); - } - - /** - *

Attempts to find the first safe place to put an item.

- * - * @param inventory The inventory to attempt to find a slot in. - * @param item The item to find a place for. - * @return Returns an index of a slot that it's safe to add to. A return value of -1 means no safe place. Even if - * the return value is -1 it may still be possible to add the item stack to the inventory, as this - * function attempts to find the first slot that the given item stack can fit into wholly; that if it can - * technically fit but has to be distributed then there's no "first empty". - * - * @deprecated Use {@link InventoryUtils#firstEmpty(Inventory, ItemStack)} instead. - */ - @Deprecated - public static int firstEmpty(Inventory inventory, ItemStack item) { - if (inventory == null) { - return -1; - } - // If there's a slot free, then just return that. Otherwise if - // the item is invalid, just return whatever slot was returned. - int index = inventory.firstEmpty(); - if (index >= 0 || !ItemAPI.isValidItem(item)) { - return index; - } - // If gets here, then we're certain that there's no stacks free. - // If the amount of the item to add is larger than a stack, then - // it can't be merged with another stack. So just back out. - int remainder = item.getMaxStackSize() - item.getAmount(); - if (remainder <= 0) { - return -1; - } - // Find all items that match with the given item to see if there's - // a stack that can be merged with. If none can be found, back out. - for (Map.Entry entry : inventory.all(item).entrySet()) { - if (entry.getValue().getAmount() <= remainder) { - return entry.getKey(); - } - } - return -1; - } - - /** - * Clears an inventory of items. - * - * @param inventory The inventory to clear of items. - * - * @deprecated Use {@link InventoryUtils#clearInventory(Inventory)} instead. - */ - @Deprecated - public static void clearInventory(Inventory inventory) { - Preconditions.checkArgument(isValidInventory(inventory)); - inventory.setContents(Iteration.fill(inventory.getContents(), null)); - } - - /** - * Checks whether an inventory has more than one viewer. - * - * @param inventory The inventory to check. - * @return Returns true if an inventory has multiple viewers. - * - * @deprecated Use {@link InventoryUtils#hasOtherViewers(Inventory)} instead. - */ - @Deprecated - public static boolean hasOtherViewers(Inventory inventory) { - if (!isValidInventory(inventory)) { - return false; - } - return inventory.getViewers().size() > 1; - } - - /** - * Checks whether a certain amount of slots would be considered a valid chest inventory. - * - * @param slots The slot amount to check. - * @return Returns true if the slot count is or between 1-6 multiples of 9. - * - * @deprecated Use {@link InventoryUtils#isValidChestSize(int)} instead. - */ - @Deprecated - public static boolean isValidChestSize(int slots) { - if (slots <= 0 || slots > 54) { - return false; - } - if ((slots % 9) > 0) { - return false; - } - return true; - } - - /** - * Will safely add a set of items to an inventory. If not all items are added, it's not committed to the inventory. - * - * @param inventory The inventory to add the items to. - * @param items The items to add to the inventory. - * @return Returns true if the items were safely added. - * - * @deprecated Use {@link InventoryUtils#safelyAddItemsToInventory(Inventory, ItemStack[])} instead. - */ - @Deprecated - public static boolean safelyAddItemsToInventory(Inventory inventory, ItemStack[] items) { - Preconditions.checkArgument(isValidInventory(inventory)); - if (ArrayUtils.isEmpty(items)) { - return true; - } - Inventory clone = cloneInventory(inventory); - for (ItemStack itemToAdd : items) { - if (firstEmpty(clone, itemToAdd) < 0) { - return false; - } - if (!clone.addItem(itemToAdd).isEmpty()) { - return false; - } - } - inventory.setContents(clone.getContents()); - return true; - } - - /** - * Will safely remove a set of items from an inventory. If not all items are removed, it's not committed to the - * inventory. - * - * @param inventory The inventory to remove the items from. - * @param items The items to remove to the inventory. - * @return Returns true if the items were safely removed. - * - * @deprecated Use {@link InventoryUtils#safelyRemoveItemsFromInventory(Inventory, ItemStack[])} instead. - */ - @Deprecated - public static boolean safelyRemoveItemsFromInventory(Inventory inventory, ItemStack[] items) { - Preconditions.checkArgument(isValidInventory(inventory)); - if (ArrayUtils.isEmpty(items)) { - return true; - } - Inventory clone = cloneInventory(inventory); - for (ItemStack itemToRemove : items) { - if (!clone.removeItem(itemToRemove).isEmpty()) { - return false; - } - } - inventory.setContents(clone.getContents()); - return true; - } - - /** - * Will safely transact a set of items from one inventory to another inventory. If not all items are transacted, the - * transaction is not committed. - * - * @param from The inventory to move the given items from. - * @param items The items to transact. - * @param to The inventory to move the given items to. - * @return Returns true if the items were successfully transacted. - * - * @deprecated Use {@link InventoryUtils#safelyTransactBetweenInventories(Inventory, Inventory, ItemStack[])} - * instead. - */ - @Deprecated - public static boolean safelyTransactBetweenInventories(Inventory from, ItemStack[] items, Inventory to) { - Preconditions.checkArgument(isValidInventory(from)); - Preconditions.checkArgument(isValidInventory(to)); - if (ArrayUtils.isEmpty(items)) { - return true; - } - Inventory fromClone = cloneInventory(from); - Inventory toClone = cloneInventory(to); - if (!safelyRemoveItemsFromInventory(fromClone, items)) { - return false; - } - if (!safelyAddItemsToInventory(toClone, items)) { - return false; - } - from.setContents(fromClone.getContents()); - to.setContents(toClone.getContents()); - return true; - } - - /** - * Will safely trade items between inventories. If not all items are traded, the trade is cancelled. - * - * @param formerInventory The first inventory. - * @param formerItems The items to trade from the first inventory to give to the second inventory. - * @param latterInventory The second inventory. - * @param latterItems The items to trade from the second inventory to give to the first inventory. - * @return Returns true if the trade succeeded. - * - * @deprecated Use - * {@link InventoryUtils#safelyTradeBetweenInventories(Inventory, Inventory, ItemStack[], ItemStack[])} instead. - */ - @Deprecated - public static boolean safelyTradeBetweenInventories(Inventory formerInventory, ItemStack[] formerItems, - Inventory latterInventory, ItemStack[] latterItems) { - Preconditions.checkArgument(isValidInventory(formerInventory)); - Preconditions.checkArgument(isValidInventory(latterInventory)); - Inventory formerClone = InventoryAPI.cloneInventory(formerInventory); - Inventory latterClone = InventoryAPI.cloneInventory(latterInventory); - if (!safelyRemoveItemsFromInventory(formerClone, formerItems)) { - return false; - } - if (!safelyRemoveItemsFromInventory(latterClone, latterItems)) { - return false; - } - if (!safelyAddItemsToInventory(formerClone, latterItems)) { - return false; - } - if (!safelyAddItemsToInventory(latterClone, formerItems)) { - return false; - } - formerInventory.setContents(formerClone.getContents()); - latterInventory.setContents(latterClone.getContents()); - return true; - } - - /** - * @deprecated Use {@link ClonedInventory#cloneInventory(Inventory)} instead. - */ - @Deprecated - public static Inventory cloneInventory(Inventory inventory) { - return ClonedInventory.cloneInventory(inventory); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/ItemAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/ItemAPI.java deleted file mode 100644 index 96215223..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/ItemAPI.java +++ /dev/null @@ -1,420 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import static vg.civcraft.mc.civmodcore.util.NullCoalescing.castOrNull; - -import com.google.common.base.Objects; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.function.Predicate; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils; -import vg.civcraft.mc.civmodcore.util.Iteration; - -/** - * Class of static APIs for Items. Replaces ISUtils. - * - * @deprecated Use {@link ItemUtils} instead. - */ -@Deprecated -public final class ItemAPI { - - /** - * Checks if an ItemStack is valid. An ItemStack is considered valid if when added to an inventory, it shows as an - * item with an amount within appropriate bounds. Therefore {@code new ItemStack(Material.AIR)} will not be - * considered valid, nor will {@code new ItemStack(Material.STONE, 80)} - * - * @param item The item to validate. - * @return Returns true if the item is valid. - * - * @deprecated Use {@link ItemUtils#isValidItem(ItemStack)} instead. - */ - @Deprecated - public static boolean isValidItem(ItemStack item) { - if (item == null) { - return false; - } - if (!MaterialAPI.isValidItemMaterial(item.getType())) { - return false; - } - if (!isValidItemAmount(item)) { - return false; - } - return true; - } - - /** - * Checks if an ItemStack has a valid amount. - * - * @param item The item to validate. - * @return Returns true if the item has a valid amount. - * - * @deprecated Use {@link ItemUtils#isValidItemAmount(ItemStack)} instead. - */ - @Deprecated - public static boolean isValidItemAmount(ItemStack item) { - if (item == null) { - return false; - } - if (item.getAmount() <= 0) { - return false; - } - if (item.getAmount() > item.getMaxStackSize()) { - return false; - } - return true; - } - - /** - * Determines whether two item stacks are functionally identical. (Will check both items against the other) - * - * @param former The first item. - * @param latter The second item. - * @return Returns true if both items are equal and not null. - * - * @see ItemStack#equals(Object) - * - * @deprecated Use {@link Objects#equal(Object, Object)} instead. - */ - @Deprecated - public static boolean areItemsEqual(ItemStack former, ItemStack latter) { - if (former != null && former.equals(latter)) { - return true; - } - if (latter != null && latter.equals(former)) { - return true; - } - return false; - } - - /** - * Determines whether two item stacks are similar. (Will check both items against the other) - * - * @param former The first item. - * @param latter The second item. - * @return Returns true if both items are similar and not null. - * - * @see ItemStack#isSimilar(ItemStack) - * - * @deprecated Use {@link ItemUtils#areItemsSimilar(ItemStack, ItemStack)} instead. - */ - @Deprecated - public static boolean areItemsSimilar(ItemStack former, ItemStack latter) { - if (former != null && former.isSimilar(latter)) { - return true; - } - if (latter != null && latter.isSimilar(former)) { - return true; - } - return false; - } - - /** - * Decrements an item's amount, or returns null if the amount reaches zero. - * - * @param item The item to decrement in amount. - * @return Returns the given item with a decremented amount, or null. - * - * @deprecated Use {@link ItemUtils#decrementItem(ItemStack)} instead. - */ - @Deprecated - public static ItemStack decrementItem(ItemStack item) { - if (item == null || item.getAmount() <= 1) { - return null; - } - item.setAmount(item.getAmount() - 1); - return item; - } - - /** - * Normalizes an item. - * - * @param item The item to normalize. - * @return The normalized item. - * - * @deprecated Use {@link ItemUtils#normalizeItem(ItemStack)} instead. - */ - @Deprecated - public static ItemStack normalizeItem(ItemStack item) { - if (item == null) { - return null; - } - item = item.clone(); - item.setAmount(1); - return item; - } - - /** - * Retrieves the ItemMeta from an item. - * - * @param item The item to retrieve meta from. - * @return Returns the item meta, which is never null. - * - * @deprecated Use {@link ItemUtils#getItemMeta(ItemStack)} instead. - */ - @Deprecated - public static ItemMeta getItemMeta(ItemStack item) { - if (item == null) { - throw new IllegalArgumentException("Cannot retrieve the item's meta; the item is null."); - } - ItemMeta meta = item.getItemMeta(); - if (meta == null) { - throw new IllegalArgumentException("Cannot retrieve item meta; it has no meta nor was any generated."); - } - return meta; - } - - /** - * Retrieves the display name from an item. - * - * @param item The item to retrieve the display name from. - * @return Returns the display name of an item. Will return null if there's no display name, or if it's empty. - * - * @deprecated Use {@link ItemUtils#getDisplayName(ItemStack)} instead. - */ - @Deprecated - public static String getDisplayName(ItemStack item) { - ItemMeta meta = getItemMeta(item); - String name = meta.getDisplayName(); - if (StringUtils.isEmpty(name)) { - return null; - } - return name; - } - - /** - * Sets a display name to an item. A null or empty name will remove the display name from the item. - * - * @param item The item to set the display name to. - * @param name The display name to set on the item. - * - * @deprecated Use {@link ItemUtils#setDisplayName(ItemStack, String)} instead. - */ - @Deprecated - public static void setDisplayName(ItemStack item, String name) { - ItemMeta meta = getItemMeta(item); - if (StringUtils.isEmpty(name)) { - meta.setDisplayName(null); - } - else { - meta.setDisplayName(name); - } - item.setItemMeta(meta); - } - - /** - * Retrieves the lore from an item. - * - * @param item The item to retrieve the lore from. - * @return Returns the lore, which is never null. - * - * @deprecated Use {@link ItemUtils#getLore(ItemStack)} instead. - */ - @Deprecated - public static List getLore(ItemStack item) { - ItemMeta meta = getItemMeta(item); - List lore = meta.getLore(); - if (lore == null) { - return new ArrayList<>(); - } - return lore; - } - - /** - * Sets the lore for an item, replacing any lore that may have already been set. - * - * @param item The item to set the lore to. - * @param lines The lore to set to the item. - * - * @see ItemAPI#clearLore(ItemStack) - * - * @deprecated Use {@link ItemUtils#setLore(ItemStack, String...)} instead. - */ - @Deprecated - public static void setLore(ItemStack item, String... lines) { - if (ArrayUtils.isEmpty(lines)) { - clearLore(item); - } - else { - setLore(item, Iteration.collect(ArrayList::new, lines)); - } - } - - /** - * Sets the lore for an item, replacing any lore that may have already been set. - * - * @param item The item to set the lore to. - * @param lines The lore to set to the item. - * - * @see ItemAPI#clearLore(ItemStack) - * - * @deprecated Use {@link ItemUtils#setLore(ItemStack, List)} instead. - */ - @Deprecated - public static void setLore(ItemStack item, List lines) { - ItemMeta meta = getItemMeta(item); - meta.setLore(lines); - item.setItemMeta(meta); - } - - /** - * Appends lore to an item. - * - * @param item The item to append the lore to. - * @param lines The lore to append to the item. - * - * @deprecated Use {@link ItemUtils#addLore(ItemStack, String...)} instead. - */ - @Deprecated - public static void addLore(ItemStack item, String... lines) { - addLore(item, Iteration.collect(ArrayList::new, lines)); - } - - /** - * Appends lore to an item. - * - * @param item The item to append the lore to. - * @param lines The lore to append to the item. - * - * @deprecated Use {@link ItemUtils#addLore(ItemStack, List)} instead. - */ - @Deprecated - public static void addLore(ItemStack item, List lines) { - addLore(item, false, lines); - } - - /** - * Adds lore to an item, either by appending or prepending. - * - * @param item The item to append the lore to. - * @param prepend If set to true, the lore will be prepended instead of appended. - * @param lines The lore to append to the item. - * - * @deprecated Use {@link ItemUtils#addLore(ItemStack, boolean, String...)} instead. - */ - @Deprecated - public static void addLore(ItemStack item, boolean prepend, String... lines) { - addLore(item, prepend, Iteration.collect(ArrayList::new, lines)); - } - - /** - * Adds lore to an item, either by appending or prepending. - * - * @param item The item to append the lore to. - * @param prepend If set to true, the lore will be prepended instead of appended. - * @param lines The lore to append to the item. - * - * @deprecated Use {@link ItemUtils#addLore(ItemStack, boolean, List)} instead. - */ - @Deprecated - public static void addLore(ItemStack item, boolean prepend, List lines) { - if (Iteration.isNullOrEmpty(lines)) { - throw new IllegalArgumentException("Cannot add to the item's lore; the lore is null."); - } - ItemMeta meta = getItemMeta(item); - List lore = meta.getLore(); - if (lore == null) { - lore = new ArrayList<>(); - } - if (prepend) { - Collections.reverse(lines); - for (String line : lines) { - lore.add(0, line); - } - } - else { - lore.addAll(lines); - } - setLore(item, lore); - } - - /** - * Clears the lore from an item. - * - * @param item The item to clear lore of. - * - * @deprecated Use {@link ItemUtils#clearLore(ItemStack)} instead. - */ - @Deprecated - public static void clearLore(ItemStack item) { - setLore(item, (List) null); - } - - /** - * Retrieves the Damageable ItemMeta only if it's relevant to the item. This is necessary because [almost?] every - * ItemMeta implements Damageable.. for some reason. And so this will only return a Damageable instance if the item - * material actually has a maximum durability above zero. - * - * @param item The item to get the Damageable meta from. - * @return Returns an instance of Damageable, or null. - * - * @deprecated Use {@link ItemUtils#getDamageable(ItemStack)} instead. - */ - @Deprecated - public static Damageable getDamageable(ItemStack item) { - if (item == null) { - return null; - } - short maxDurability = item.getType().getMaxDurability(); - if (maxDurability <= 0) { - return null; - } - return castOrNull(Damageable.class, item.getItemMeta()); - } - - /** - * Makes an item glow by adding an enchantment and the flag for hiding enchantments, - * so it has the enchantment glow without an enchantment being visible. Note that this - * does actually apply an enchantment to an item. - * - * @param item Item to apply glow to. - * - * @deprecated Use {@link ItemUtils#addGlow(ItemStack)} instead. - */ - @Deprecated - public static void addGlow(ItemStack item) { - ItemMeta meta = getItemMeta(item); - meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - item.setItemMeta(meta); - item.addUnsafeEnchantment(Enchantment.DURABILITY, 1); - } - - /** - * Handles an item's metadata. - * - * @param The item meta type, which might not extend ItemMeta (Damageable for example) - * @param item The item to handle the metadata of. - * @param handler The item metadata handler, which should return true if modifications were made. - * @return Returns true if the metadata was successfully handled. - * - * @see ItemStack#getItemMeta() - * - * @deprecated Use {@link ItemUtils#handleItemMeta(ItemStack, Predicate)} instead. - */ - @Deprecated - @SuppressWarnings("unchecked") - public static boolean handleItemMeta(ItemStack item, Predicate handler) { - if (item == null || handler == null) { - return false; - } - T meta; - try { - meta = (T) item.getItemMeta(); - if (meta == null) { - return false; - } - if (handler.test(meta)) { - return item.setItemMeta((ItemMeta) meta); - } - } - catch (ClassCastException ignored) { } - return false; - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/ItemNames.java b/src/main/java/vg/civcraft/mc/civmodcore/api/ItemNames.java deleted file mode 100644 index 460d4c0e..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/ItemNames.java +++ /dev/null @@ -1,37 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils; - -/** - * @deprecated Use {@link ItemUtils} instead. - */ -@Deprecated -public final class ItemNames { - - /** - * @deprecated Use {@link ItemUtils#getItemName(Material)} instead. - */ - @Deprecated - public static String getItemName(Material material) { - return ItemUtils.getItemName(material); - } - - /** - * @deprecated Use {@link ItemUtils#getItemName(ItemStack)} instead. - */ - @Deprecated - public static String getItemName(ItemStack item) { - return ItemUtils.getItemName(item); - } - - /** - * @deprecated Use {@link ItemUtils#hasDisplayName(ItemStack)} instead. - */ - @Deprecated - public static boolean hasDisplayName(ItemStack item) { - return ItemUtils.hasDisplayName(item); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/LocationAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/LocationAPI.java deleted file mode 100644 index 16b3d11f..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/LocationAPI.java +++ /dev/null @@ -1,156 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import org.bukkit.Location; -import org.bukkit.World; -import vg.civcraft.mc.civmodcore.util.NullCoalescing; - -/** - * Class of utility functions for Locations. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils} instead. - */ -@Deprecated -public final class LocationAPI { - - /** - * Retrieves the world from a location. - * - * @param location The location to retrieve the world from. - * @return Returns the world if loaded, or null. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getLocationWorld(Location)} instead. - */ - @Deprecated - public static World getLocationWorld(Location location) { - if (location == null) { - return null; - } - try { - return location.getWorld(); - } - catch (IllegalArgumentException ignored) { // Will be thrown if the world is not loaded - return null; - } - } - - /** - * Determines whether a location is valid and safe to use. - * - * @param location The location to check. - * @return Returns true if the location exists, is valid, and safe to use. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#isValidLocation(Location)} instead. - */ - @Deprecated - public static boolean isValidLocation(Location location) { - if (location == null) { - return false; - } - if (!location.isWorldLoaded()) { - return false; - } - return true; - } - - /** - * Converts a location into a block location. (Yaw and Pitch values are lost) - * - * @param location The location to convert. - * @return Returns a block location, or null if the given location was null. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getBlockLocation(Location)} instead. - */ - @Deprecated - public static Location getBlockLocation(Location location) { - if (location == null) { - return null; - } - return new Location(getLocationWorld(location), - location.getBlockX(), - location.getBlockY(), - location.getBlockZ()); - } - - /** - * Converts a location into a block's mid point. (Yaw and Pitch values are lost) - * - * @param location The location to convert. - * @return Returns a block's mid point, or null if the given location was null. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#getMidBlockLocation(Location)} instead. - */ - @Deprecated - public static Location getMidBlockLocation(Location location) { - if (location == null) { - return null; - } - return getBlockLocation(location).add(0.5d, 0.5d, 0.5d); - } - - /** - * Determines whether two locations share the same world. - * - * @param former The first location. - * @param latter The second location. - * @return Returns true if the two locations are not null and share the same world. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#doLocationsHaveSameWorld(Location, Location)} - * instead. - */ - @Deprecated - public static boolean areLocationsSameWorld(Location former, Location latter) { - if (former == null || latter == null) { - return false; - } - return NullCoalescing.equalsNotNull(getLocationWorld(former), getLocationWorld(latter)); - } - - /** - * Returns the largest axis distance. - * - * @param latter The first location. - * @param former The second location. - * @param consider2D Whether only the X and Z axis should be considered. (true if yes) - * @return Returns the largest axis distance, or -1 if there's a problem, - * like the two locations being in two different worlds. - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#blockDistance(Location, Location, boolean)} - * instead. - */ - @Deprecated - public static int blockDistance(final Location former, final Location latter, final boolean consider2D) { - if (!LocationAPI.areLocationsSameWorld(former, latter)) { - return -1; - } - final int x = Math.abs(former.getBlockX() - latter.getBlockX()); - final int z = Math.abs(former.getBlockZ() - latter.getBlockZ()); - if (consider2D) { - return Math.max(x, z); - } - else { - final int y = Math.abs(former.getBlockY() - latter.getBlockY()); - return Math.max(x, Math.max(y, z)); - } - } - - /** - * Checks whether a location's Y coordinate is a valid block location. - * - * @param location The location to check. - * @return Returns true if the Y coordinate is a valid block location. (False if given location is null!) - * - * @deprecated Use {@link vg.civcraft.mc.civmodcore.world.WorldUtils#isWithinBounds(Location)} instead. - */ - @Deprecated - public static boolean isWithinBounds(final Location location) { - if (location == null) { - return false; - } - final double y = location.getY(); - if (y < 0 || y >= 256) { - return false; - } - return true; - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/MaterialAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/MaterialAPI.java deleted file mode 100644 index 3dae6419..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/MaterialAPI.java +++ /dev/null @@ -1,793 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import com.google.common.base.Strings; -import com.google.common.math.IntMath; -import java.util.ArrayList; -import java.util.List; -import org.bukkit.Material; -import org.bukkit.Tag; -import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils; -import vg.civcraft.mc.civmodcore.inventory.items.MaterialUtils; -import vg.civcraft.mc.civmodcore.inventory.items.MoreTags; -import vg.civcraft.mc.civmodcore.inventory.items.SpawnEggUtils; -import vg.civcraft.mc.civmodcore.inventory.items.TreeTypeUtils; - -/** - *

See BukkitReports.

- * - *
    - * - *
  • {@link SpawnEggUtils SpawnEggAPI}
  • - *
  • {@link TreeTypeUtils TreeTypeAPI}
  • - *
- * - * @deprecated Use {@link MaterialUtils}, {@link ItemUtils}, and {@link MoreTags} instead. - */ -@Deprecated -public final class MaterialAPI { - - private static final List hashMaterials = new ArrayList<>(); - - static { - hashMaterials.addAll(Tag.WOOL.getValues()); - hashMaterials.add(Material.BLACK_STAINED_GLASS); - hashMaterials.add(Material.WHITE_STAINED_GLASS); - hashMaterials.add(Material.YELLOW_STAINED_GLASS); - hashMaterials.add(Material.RED_STAINED_GLASS); - hashMaterials.add(Material.LIME_STAINED_GLASS); - hashMaterials.add(Material.GRAY_STAINED_GLASS); - hashMaterials.add(Material.BLUE_STAINED_GLASS); - hashMaterials.add(Material.LIGHT_GRAY_STAINED_GLASS); - hashMaterials.add(Material.LIGHT_BLUE_STAINED_GLASS); - hashMaterials.add(Material.GREEN_STAINED_GLASS); - hashMaterials.add(Material.BROWN_STAINED_GLASS); - hashMaterials.add(Material.PINK_STAINED_GLASS); - hashMaterials.add(Material.PURPLE_STAINED_GLASS); - hashMaterials.add(Material.CYAN_STAINED_GLASS); - hashMaterials.add(Material.MAGENTA_STAINED_GLASS); - hashMaterials.add(Material.ORANGE_STAINED_GLASS); - hashMaterials.add(Material.BLACK_STAINED_GLASS_PANE); - hashMaterials.add(Material.WHITE_STAINED_GLASS_PANE); - hashMaterials.add(Material.YELLOW_STAINED_GLASS_PANE); - hashMaterials.add(Material.RED_STAINED_GLASS_PANE); - hashMaterials.add(Material.LIME_STAINED_GLASS_PANE); - hashMaterials.add(Material.GRAY_STAINED_GLASS_PANE); - hashMaterials.add(Material.BLUE_STAINED_GLASS_PANE); - hashMaterials.add(Material.LIGHT_GRAY_STAINED_GLASS_PANE); - hashMaterials.add(Material.LIGHT_BLUE_STAINED_GLASS_PANE); - hashMaterials.add(Material.GREEN_STAINED_GLASS_PANE); - hashMaterials.add(Material.BROWN_STAINED_GLASS_PANE); - hashMaterials.add(Material.PINK_STAINED_GLASS_PANE); - hashMaterials.add(Material.PURPLE_STAINED_GLASS_PANE); - hashMaterials.add(Material.CYAN_STAINED_GLASS_PANE); - hashMaterials.add(Material.MAGENTA_STAINED_GLASS_PANE); - hashMaterials.add(Material.ORANGE_STAINED_GLASS_PANE); - hashMaterials.add(Material.BLACK_CONCRETE); - hashMaterials.add(Material.WHITE_CONCRETE); - hashMaterials.add(Material.YELLOW_CONCRETE); - hashMaterials.add(Material.RED_CONCRETE); - hashMaterials.add(Material.LIME_CONCRETE); - hashMaterials.add(Material.GRAY_CONCRETE); - hashMaterials.add(Material.BLUE_CONCRETE); - hashMaterials.add(Material.LIGHT_GRAY_CONCRETE); - hashMaterials.add(Material.LIGHT_BLUE_CONCRETE); - hashMaterials.add(Material.GREEN_CONCRETE); - hashMaterials.add(Material.BROWN_CONCRETE); - hashMaterials.add(Material.PINK_CONCRETE); - hashMaterials.add(Material.PURPLE_CONCRETE); - hashMaterials.add(Material.CYAN_CONCRETE); - hashMaterials.add(Material.MAGENTA_CONCRETE); - hashMaterials.add(Material.ORANGE_CONCRETE); - } - - /** - * Checks whether a material would be considered a valid item. - * - * @param material The material to check. - * @return Returns true if the material would be considered a valid item. - * - * @deprecated Use {@link ItemUtils#isValidItemMaterial(Material)} instead. - */ - @Deprecated - public static boolean isValidItemMaterial(Material material) { - if (material == null) { - return false; - } - if (material.isAir()) { - return false; - } - if (!material.isItem()) { - return false; - } - return true; - } - - /** - * Attempts to retrieve a material by its slug. - * - * @param value The value to search for a matching material by. - * @return Returns a matched material or null. - * - * @deprecated Use {@link MaterialUtils#getMaterial(String)} instead. - */ - @Deprecated - public static Material getMaterial(String value) { - if (Strings.isNullOrEmpty(value)) { - return null; - } - return Material.getMaterial(value.toUpperCase()); - } - - /** - * Checks whether a material is air. - * Will also return true if the given material is null. - * - * @param material The material to check. - * @return Returns true if the material is air. - * - * @deprecated Use {@link MaterialUtils#isAir(Material)} instead. - */ - @Deprecated - public static boolean isAir(Material material) { - if (material == null) { - return true; - } - return material.isAir(); - } - - /** - * Checks whether a material is a non-stripped log. - * - * @param material The material to check. - * @return Returns true if the material is a log. - * - * @deprecated Please use {@code MoreTags.LOGS.isTagged(material);} - */ - @Deprecated - public static boolean isLog(Material material) { - if (material == null) { - return false; - } - if (isStrippedLog(material)) { - return true; - } - switch (material) { - case ACACIA_LOG: - case BIRCH_LOG: - case DARK_OAK_LOG: - case JUNGLE_LOG: - case OAK_LOG: - case SPRUCE_LOG: - return true; - default: - return false; - } - } - - /** - * @deprecated Please use {@code Tag.PLANKS.isTagged(material);} - */ - @Deprecated - public static boolean isPlank(Material material) { - return Tag.PLANKS.isTagged(material); - } - - /** - * Checks whether a material is a stripped log or wood plank. - * - * @param material The material to check. - * @return Returns true if the material is a stripped log or wood plank. - * - * @deprecated Please use {@code MoreTags.STRIPPED_ALL.isTagged(material);} - */ - @Deprecated - public static boolean isStripped(Material material) { - if (material == null) { - return false; - } - if (isStrippedLog(material)) { - return true; - } - if (isStrippedPlank(material)) { - return true; - } - return false; - } - - /** - * Checks whether a material is a stripped log. - * - * @param material The material to check. - * @return Returns true if the material is a stripped log. - * - * @deprecated Please use {@code MoreTags.STRIPPED_LOGS.isTagged(material);} - */ - @Deprecated - public static boolean isStrippedLog(Material material) { - if (material == null) { - return false; - } - switch (material) { - case STRIPPED_ACACIA_LOG: - case STRIPPED_BIRCH_LOG: - case STRIPPED_DARK_OAK_LOG: - case STRIPPED_JUNGLE_LOG: - case STRIPPED_OAK_LOG: - case STRIPPED_SPRUCE_LOG: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a stripped plank. - * - * @param material The material to check. - * @return Returns true if the material is a stripped plank. - * - * @deprecated Please use {@code MoreTags.STRIPPED_PLANKS.isTagged(material);} - */ - @Deprecated - public static boolean isStrippedPlank(Material material) { - if (material == null) { - return false; - } - switch (material) { - case STRIPPED_ACACIA_WOOD: - case STRIPPED_BIRCH_WOOD: - case STRIPPED_DARK_OAK_WOOD: - case STRIPPED_JUNGLE_WOOD: - case STRIPPED_OAK_WOOD: - case STRIPPED_SPRUCE_WOOD: - return true; - default: - return false; - } - } - - /** - * Checks whether a material can be placed into a pot. - * - * @param material The material to check. - * @return Returns true if the material can be potted. - * - * @deprecated Please use {@code MoreTags.POTTABLE.isTagged(material);} - */ - @Deprecated - public static boolean isPottable(Material material) { - if (material == null) { - return false; - } - switch (material) { - case ACACIA_SAPLING: - case ALLIUM: - case AZURE_BLUET: - case BAMBOO: - case BIRCH_SAPLING: - case BLUE_ORCHID: - case BROWN_MUSHROOM: - case CACTUS: - case CORNFLOWER: - case CRIMSON_FUNGUS: - case CRIMSON_ROOTS: - case DANDELION: - case DARK_OAK_SAPLING: - case DEAD_BUSH: - case FERN: - case JUNGLE_SAPLING: - case LILY_OF_THE_VALLEY: - case OAK_SAPLING: - case ORANGE_TULIP: - case OXEYE_DAISY: - case PINK_TULIP: - case POPPY: - case RED_MUSHROOM: - case RED_TULIP: - case SPRUCE_SAPLING: - case WARPED_FUNGUS: - case WARPED_ROOTS: - case WHITE_TULIP: - case WITHER_ROSE: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a crop. Something is a crop if it's a plant that can grow, excluding Saplings. - * - * @param material The material to check. - * @return Returns true if the material is a crop. - * - * @see org.bukkit.block.data.Ageable Check if the Block's data is an instance of this Ageable, though be aware that - * {@link Material#FIRE fire} and {@link Material#FROSTED_ICE frosted ice} also implement Ageable. - * - * @deprecated Please use {@code MoreTags.CROPS.isTagged(material);} - */ - @Deprecated - public static boolean isCrop(Material material) { - if (material == null) { - return false; - } - switch (material) { - case BAMBOO: - case BEETROOTS: - case CACTUS: - case CARROTS: - case CHORUS_FLOWER: - case CHORUS_PLANT: - case COCOA: - case KELP: - case MELON_STEM: - case NETHER_WART: - case POTATOES: - case PUMPKIN_STEM: - case SUGAR_CANE: - case SWEET_BERRY_BUSH: - case WHEAT: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a skull/head. - * - * @param material The material to check. - * @return Returns true if the material is a skull/head. - * - * @deprecated Please use {@code MaterialTags.SKULLS.isTagged(material);} - */ - @Deprecated - public static boolean isSkull(Material material) { - if (material == null) { - return false; - } - switch (material) { - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a glass block, coloured or otherwise. - * - * @param material The material to check. - * @return Returns true if the material is a glass block. - * - * @see Tag#IMPERMEABLE This functionally fulfils glass checking, however the name doesn't incidate that the tag - * is specific to glass, thus the switch remains. - * - * @deprecated Please use {@code MaterialTags.GLASS.isTagged(material);} - */ - @Deprecated - public static boolean isGlassBlock(Material material) { - if (material == null) { - return false; - } - switch (material) { - case BLACK_STAINED_GLASS: - case BLUE_STAINED_GLASS: - case BROWN_STAINED_GLASS: - case CYAN_STAINED_GLASS: - case GRAY_STAINED_GLASS: - case GLASS: - case GREEN_STAINED_GLASS: - case LIGHT_BLUE_STAINED_GLASS: - case LIGHT_GRAY_STAINED_GLASS: - case LIME_STAINED_GLASS: - case MAGENTA_STAINED_GLASS: - case ORANGE_STAINED_GLASS: - case PINK_STAINED_GLASS: - case PURPLE_STAINED_GLASS: - case RED_STAINED_GLASS: - case WHITE_STAINED_GLASS: - case YELLOW_STAINED_GLASS: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a glass pane, coloured or otherwise. - * - * @param material The material to check. - * @return Returns true if the material is a glass pane. - * - * @deprecated Please use {@code MaterialTags.GLASS_PANES.isTagged(material);} - */ - @Deprecated - public static boolean isGlassPane(Material material) { - if (material == null) { - return false; - } - switch (material) { - case BLACK_STAINED_GLASS_PANE: - case BLUE_STAINED_GLASS_PANE: - case BROWN_STAINED_GLASS_PANE: - case CYAN_STAINED_GLASS_PANE: - case GRAY_STAINED_GLASS_PANE: - case GLASS_PANE: - case GREEN_STAINED_GLASS_PANE: - case LIGHT_BLUE_STAINED_GLASS_PANE: - case LIGHT_GRAY_STAINED_GLASS_PANE: - case LIME_STAINED_GLASS_PANE: - case MAGENTA_STAINED_GLASS_PANE: - case ORANGE_STAINED_GLASS_PANE: - case PINK_STAINED_GLASS_PANE: - case PURPLE_STAINED_GLASS_PANE: - case RED_STAINED_GLASS_PANE: - case WHITE_STAINED_GLASS_PANE: - case YELLOW_STAINED_GLASS_PANE: - return true; - default: - return false; - } - } - - /** - * @deprecated Please use {@code Tag.DRAGON_IMMUNE.isTagged(material);} - */ - @Deprecated - public static boolean isDragonImmune(Material material) { - return Tag.DRAGON_IMMUNE.isTagged(material); - } - - /** - * @deprecated Please use {@code Tag.WITHER_IMMUNE.isTagged(material);} - */ - @Deprecated - public static boolean isWitherImmune(Material material) { - return Tag.WITHER_IMMUNE.isTagged(material); - } - - /** - * @deprecated Please use {@code Tag.FENCE_GATES.isTagged(material);} - */ - @Deprecated - public static boolean isWoodenFenceGate(Material material) { - return Tag.FENCE_GATES.isTagged(material); - } - - /** - * Checks whether a material is an infested block. This is what used to be referred to as Monster Egg blocks. - * - * @param material The material to check. - * @return Returns true if the material is infested. - * - * @deprecated Please use {@code MaterialTags.INFESTED_BLOCKS.isTagged(material);} - */ - @Deprecated - public static boolean isInfested(Material material) { - if (material == null) { - return false; - } - switch (material) { - case INFESTED_STONE: - case INFESTED_COBBLESTONE: - case INFESTED_STONE_BRICKS: - case INFESTED_MOSSY_STONE_BRICKS: - case INFESTED_CRACKED_STONE_BRICKS: - case INFESTED_CHISELED_STONE_BRICKS: - return true; - default: - return false; - } - } - - /** - * Duplicate of {@link #isWoodenFenceGate(Material)} - * - * @deprecated Please use {@code Tag.FENCE_GATES.isTagged(material);} - */ - @Deprecated - public static boolean isFenceGate(Material material) { - return isWoodenFenceGate(material); - } - - /** - * Checks whether a material is a dirt like block. - * - * @param material The material to check. - * @return Returns true if the material is dirty. - * - * @deprecated Please use {@code MoreTags.DIRT.isTagged(material);} - */ - @Deprecated - public static boolean isDirt(Material material) { - if (material == null) { - return false; - } - switch (material) { - case FARMLAND: - case GRASS_PATH: - case GRASS_BLOCK: - case DIRT: - case COARSE_DIRT: - case PODZOL: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a potion of some sort. - * - * @param material The material to check. - * @return Returns true if the material is a potion. - * - * @deprecated Please use {@code MoreTags.POTIONS.isTagged(material);} - */ - @Deprecated - public static boolean isPotion(Material material) { - if (material == null) { - return false; - } - switch (material) { - case POTION: - case SPLASH_POTION: - case LINGERING_POTION: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a type of sword. - * - * @param material The material to check. - * @return Returns true if the material is a sword. - * - * @deprecated Please use {@code MaterialTags.SWORDS.isTagged(material);} - */ - @Deprecated - public static boolean isSword(Material material) { - if (material == null) { - return false; - } - switch (material) { - case WOODEN_SWORD: - case STONE_SWORD: - case IRON_SWORD: - case GOLDEN_SWORD: - case DIAMOND_SWORD: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a type of pick axe. - * - * @param material The material to check. - * @return Returns true if the material is a pick axe. - * - * @deprecated Please use {@code MaterialTags.PICKAXES.isTagged(material);} - */ - @Deprecated - public static boolean isPickaxe(Material material) { - if (material == null) { - return false; - } - switch (material) { - case WOODEN_PICKAXE: - case STONE_PICKAXE: - case IRON_PICKAXE: - case GOLDEN_PICKAXE: - case DIAMOND_PICKAXE: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a type of axe. - * - * @param material The material to check. - * @return Returns true if the material is a axe. - * - * @deprecated Please use {@code MaterialTags.AXES.isTagged(material);} - */ - @Deprecated - public static boolean isAxe(Material material) { - if (material == null) { - return false; - } - switch (material) { - case WOODEN_AXE: - case STONE_AXE: - case IRON_AXE: - case GOLDEN_AXE: - case DIAMOND_AXE: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a type of spade. - * - * @param material The material to check. - * @return Returns true if the material is a spade. - * - * @deprecated Please use {@code MaterialTags.SHOVELS.isTagged(material);} - */ - @Deprecated - public static boolean isShovel(Material material) { - if (material == null) { - return false; - } - switch (material) { - case WOODEN_SHOVEL: - case STONE_SHOVEL: - case IRON_SHOVEL: - case GOLDEN_SHOVEL: - case DIAMOND_SHOVEL: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a type of hoe. - * - * @param material The material to check. - * @return Returns true if the material is a hoe. - * - * @deprecated Please use {@code MaterialTags.HOES.isTagged(material);} - */ - @Deprecated - public static boolean isHoe(Material material) { - if (material == null) { - return false; - } - switch (material) { - case WOODEN_HOE: - case STONE_HOE: - case IRON_HOE: - case GOLDEN_HOE: - case DIAMOND_HOE: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a type of helmet. - * - * @param material The material to check. - * @return Returns true if the material is a helmet. - * - * @deprecated Please use {@code MaterialTags.HELMETS.isTagged(material);} - */ - @Deprecated - public static boolean isHelmet(Material material) { - if (material == null) { - return false; - } - switch (material) { - case LEATHER_HELMET: - case CHAINMAIL_HELMET: - case IRON_HELMET: - case GOLDEN_HELMET: - case DIAMOND_HELMET: - case TURTLE_HELMET: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a type of chest plate. - * - * @param material The material to check. - * @return Returns true if the material is a chest plate. - * - * @deprecated Please use {@code MaterialTags.CHESTPLATES.isTagged(material);} - */ - @Deprecated - public static boolean isChestplate(Material material) { - if (material == null) { - return false; - } - switch (material) { - case LEATHER_CHESTPLATE: - case CHAINMAIL_CHESTPLATE: - case IRON_CHESTPLATE: - case GOLDEN_CHESTPLATE: - case DIAMOND_CHESTPLATE: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a type of leggings. - * - * @param material The material to check. - * @return Returns true if the material is a pair of leggings. - * - * @deprecated Please use {@code MaterialTags.LEGGINGS.isTagged(material);} - */ - @Deprecated - public static boolean areLeggings(Material material) { - if (material == null) { - return false; - } - switch (material) { - case LEATHER_LEGGINGS: - case CHAINMAIL_LEGGINGS: - case IRON_LEGGINGS: - case GOLDEN_LEGGINGS: - case DIAMOND_LEGGINGS: - return true; - default: - return false; - } - } - - /** - * Checks whether a material is a type of boots. - * - * @param material The material to check. - * @return Returns true if the material is a pair of boots. - * - * @deprecated Please use {@code MaterialTags.BOOTS.isTagged(material);} - */ - @Deprecated - public static boolean areBoots(Material material) { - if (material == null) { - return false; - } - switch (material) { - case LEATHER_BOOTS: - case CHAINMAIL_BOOTS: - case IRON_BOOTS: - case GOLDEN_BOOTS: - case DIAMOND_BOOTS: - return true; - default: - return false; - } - } - - /** - * Gets a random material based on the given objects hashcode. - * - * @param object Object to base returned material on - * @return Material hash of the given object - * - * @deprecated Use {@link MaterialUtils#getMaterialHash(Object)} instead. - */ - @Deprecated - public static Material getMaterialHash(Object object) { - if (object == null) { - return hashMaterials.get(0); - } - int index = IntMath.mod(object.hashCode(), hashMaterials.size()); - return hashMaterials.get(index); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/NamespaceAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/NamespaceAPI.java deleted file mode 100644 index 3439f47b..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/NamespaceAPI.java +++ /dev/null @@ -1,91 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import com.google.common.base.Strings; -import org.bukkit.Keyed; -import org.bukkit.NamespacedKey; -import vg.civcraft.mc.civmodcore.util.KeyedUtils; - -/** - * Utility class to make dealing with namespace keys easier. - * - * @deprecated Use {@link KeyedUtils} instead. - */ -@Deprecated -public final class NamespaceAPI { - - /** - * Converts a stringified namespace back into a {@link NamespacedKey}. - * - * @param key The stringified namespace, which MUST be formatted as {@code namespace:name} - * @return Returns a valid {@link NamespacedKey}, or null. - * - * @exception IllegalArgumentException Will throw if the stringified key fails a "[a-z0-9._-]+" check, or if the - * total length is longer than 256. - * - * @deprecated Use {@link KeyedUtils#fromString(String)} instead. - */ - @Deprecated - public static NamespacedKey fromString(String key) { - if (Strings.isNullOrEmpty(key)) { - return null; - } - String[] parts = key.split(":"); - if (parts.length != 2) { - return null; - } - return fromParts(parts[0], parts[1]); - } - - /** - * Converts a namespace and a key into a {@link NamespacedKey}. - * - * @param namespace The namespace name. - * @param key The namespaced key. - * @return Returns a valid {@link NamespacedKey}, or null. - * - * @exception IllegalArgumentException Will throw if either part fails a "[a-z0-9._-]+" check, or if the total - * combined length is longer than 256. - * - * @deprecated Use {@link KeyedUtils#fromParts(String, String)} instead. - */ - @Deprecated - public static NamespacedKey fromParts(String namespace, String key) { - if (Strings.isNullOrEmpty(namespace) || Strings.isNullOrEmpty(key)) { - return null; - } - return new NamespacedKey(namespace, key); - } - - /** - * Converts a {@link NamespacedKey} into a string. - * - * @param key The {@link NamespacedKey} to convert. - * @return Returns the stringified {@link NamespacedKey}, or null. - * - * @deprecated Use {@link KeyedUtils#getString(NamespacedKey)} instead. - */ - @Deprecated - public static String getString(NamespacedKey key) { - if (key == null) { - return null; - } - return key.toString(); - } - - /** - * Retrieves a {@link Keyed}'s {@link NamespacedKey} and converts it to a string. - * - * @param keyed The {@link Keyed} instance. - * @return Returns the stringified {@link Keyed}'s {@link NamespacedKey}, or null. - * - * @deprecated Use {@link KeyedUtils#getString(Keyed)} instead. - */ - @Deprecated - public static String getString(Keyed keyed) { - if (keyed == null) { - return null; - } - return getString(keyed.getKey()); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/PotionAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/PotionAPI.java deleted file mode 100644 index 797f8feb..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/PotionAPI.java +++ /dev/null @@ -1,65 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import java.util.HashMap; -import java.util.Map; -import org.bukkit.potion.PotionEffectType; -import vg.civcraft.mc.civmodcore.inventory.items.PotionUtils; - -/** - * @deprecated Use {@link PotionUtils} instead. - */ -@Deprecated -public final class PotionAPI { - - private PotionAPI() { - - } - - private static Map potionEffectNameMapping; - - - static { - potionEffectNameMapping = new HashMap<>(); - potionEffectNameMapping.put(PotionEffectType.ABSORPTION, "Absorption"); - potionEffectNameMapping.put(PotionEffectType.BAD_OMEN, "Bad Omen"); - potionEffectNameMapping.put(PotionEffectType.BLINDNESS, "Blindness"); - potionEffectNameMapping.put(PotionEffectType.CONDUIT_POWER, "Conduit Power"); - potionEffectNameMapping.put(PotionEffectType.CONFUSION, "Nausea"); - potionEffectNameMapping.put(PotionEffectType.DAMAGE_RESISTANCE, "Resistance"); - potionEffectNameMapping.put(PotionEffectType.DOLPHINS_GRACE, "Dolphin's Grace"); - potionEffectNameMapping.put(PotionEffectType.FAST_DIGGING, "Haste"); - potionEffectNameMapping.put(PotionEffectType.FIRE_RESISTANCE, "Fire Resistance "); - potionEffectNameMapping.put(PotionEffectType.GLOWING, "Glowing"); - potionEffectNameMapping.put(PotionEffectType.HARM, "Instant Damage"); - potionEffectNameMapping.put(PotionEffectType.HEAL, "Instant Health"); - potionEffectNameMapping.put(PotionEffectType.HEALTH_BOOST, "Health Boost"); - potionEffectNameMapping.put(PotionEffectType.HERO_OF_THE_VILLAGE, "Hero of the Village"); - potionEffectNameMapping.put(PotionEffectType.HUNGER, "Hunger"); - potionEffectNameMapping.put(PotionEffectType.INCREASE_DAMAGE, "Strength"); - potionEffectNameMapping.put(PotionEffectType.INVISIBILITY, "Invisibility"); - potionEffectNameMapping.put(PotionEffectType.JUMP, "Jump Boost"); - potionEffectNameMapping.put(PotionEffectType.LEVITATION, "Levitation"); - potionEffectNameMapping.put(PotionEffectType.LUCK, "Luck"); - potionEffectNameMapping.put(PotionEffectType.NIGHT_VISION, "Night Vision"); - potionEffectNameMapping.put(PotionEffectType.POISON, "Poison"); - potionEffectNameMapping.put(PotionEffectType.REGENERATION, "Regeneration"); - potionEffectNameMapping.put(PotionEffectType.SATURATION, "Saturation"); - potionEffectNameMapping.put(PotionEffectType.SLOW, "Slowness"); - potionEffectNameMapping.put(PotionEffectType.SLOW_DIGGING, "Mining Fatigue"); - potionEffectNameMapping.put(PotionEffectType.SLOW_FALLING, "Slow Falling"); - potionEffectNameMapping.put(PotionEffectType.SPEED, "Speed"); - potionEffectNameMapping.put(PotionEffectType.UNLUCK, "Bad Luck"); - potionEffectNameMapping.put(PotionEffectType.WATER_BREATHING, "Haste"); - potionEffectNameMapping.put(PotionEffectType.WEAKNESS, "Weakness"); - potionEffectNameMapping.put(PotionEffectType.WITHER, "Wither"); - } - - /** - * @deprecated Use {@link PotionUtils#getEffectNiceName(PotionEffectType)} instead. - */ - @Deprecated - public static String getNiceName(PotionEffectType pet) { - return potionEffectNameMapping.get(pet); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/PotionNames.java b/src/main/java/vg/civcraft/mc/civmodcore/api/PotionNames.java deleted file mode 100644 index 629ec333..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/PotionNames.java +++ /dev/null @@ -1,203 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import com.google.common.base.Strings; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.potion.PotionType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import vg.civcraft.mc.civmodcore.CivModCorePlugin; -import vg.civcraft.mc.civmodcore.inventory.items.PotionUtils; -import vg.civcraft.mc.civmodcore.util.TextUtil; - -/** - * Class that loads and store potion names. - * - * @deprecated Use {@link PotionUtils} instead. - * */ -@Deprecated -public final class PotionNames { - - private static final Logger LOGGER = LoggerFactory.getLogger(PotionNames.class.getSimpleName()); - - private static final Set POTION_DETAILS = new HashSet<>(); - - /** - * Resets all item names, custom item names included. - * */ - public static void resetPotionNames() { - POTION_DETAILS.clear(); - } - - /** - * Loads item names from configurable files and requests any custom item names programmatically from plugins. - * */ - public static void loadPotionNames() { - resetPotionNames(); - InputStream enchantmentsCSV = CivModCorePlugin.class.getResourceAsStream("/potions.csv"); - if (enchantmentsCSV != null) { - try { - BufferedReader reader = new BufferedReader(new InputStreamReader(enchantmentsCSV)); - String line = reader.readLine(); - while (line != null) { - String[] values = line.split(","); - // If there's not at least three values (slug, abbreviation, display name) then skip - if (values.length != 3) { - LOGGER.warn("[Config] This potion row is corrupted: " + line); - // Go to the next line - line = reader.readLine(); - continue; - } - // If the potion type cannot be found by the given slug, then skip - PotionType type; - try { - type = PotionType.valueOf(values[0]); - } - catch (Exception ignored) { - LOGGER.warn("[Config] Could not find a potion type on this line: " + line); - // Go to the next line - line = reader.readLine(); - continue; - } - // If the line specifies an effect type, then try to find it or skip if not found - PotionEffectType effectType = null; - if (!Strings.isNullOrEmpty(values[1])) { - effectType = PotionEffectType.getByName(values[1]); - if (effectType == null) { - LOGGER.warn("[Config] Could not find potion effect type type on this line: " + line); - // Go to the next line - line = reader.readLine(); - continue; - } - } - // Get the potion's name - String name = values[2]; - if (Strings.isNullOrEmpty(name)) { - LOGGER.warn("[Config] Could not find potion name on this line: " + line); - // Go to the next line - line = reader.readLine(); - continue; - } - // Put the enchantment and name into the system - POTION_DETAILS.add(new SearchResult(type, effectType, name)); - line = reader.readLine(); - } - reader.close(); - } - catch (IOException error) { - LOGGER.warn("[Config] Could not load potions from potions.csv"); - error.printStackTrace(); - } - } - else { - LOGGER.warn("[Config] Could not load potions from potions.csv as the file does not exist."); - } - } - - /** - * Attempts to match a potion type with a set of details. - * - * @param type The potion type to search with. - * @return The potion details, or null. - */ - public static SearchResult findByType(PotionType type) { - if (type == null) { - return null; - } - for (SearchResult details : POTION_DETAILS) { - if (details.type == type) { - return details; - } - } - return null; - } - - /** - * Attempts to match a potion effect type with a set of details. This is a less desirable search as some potion - * do not have an effect. If you're checking with a static value, best to take a look at {@link PotionType}. - * - * @param type The potion effect type to search with. - * @return The potion details, or null. - */ - public static SearchResult findByEffect(PotionEffectType type) { - if (type == null) { - return null; - } - for (SearchResult details : POTION_DETAILS) { - if (details.effectType == type) { - return details; - } - } - return null; - } - - /** - * Attempts to match a potion name with a set of details. - * - * @param name The potion name to search with. - * @return The potion details, or null. - */ - public static SearchResult findByName(String name) { - if (Strings.isNullOrEmpty(name)) { - return null; - } - for (SearchResult details : POTION_DETAILS) { - if (TextUtil.stringEqualsIgnoreCase(details.name, name)) { - return details; - } - } - return null; - } - - /** - * This class represents a data set for a particular enchantment. - */ - public static final class SearchResult { - - private final PotionType type; - - private final PotionEffectType effectType; - - private final String name; - - private SearchResult(PotionType type, PotionEffectType effectType, String name) { - this.type = type; - this.effectType = effectType; - this.name = name; - } - - /** - * @return Returns the potion type. - */ - public PotionType getPotionType() { - return this.type; - } - - /** - * @return Returns the potion's effect type. - */ - public PotionEffectType getEffectType() { - return this.effectType; - } - - /** - * @return Returns the potion's name. - */ - public String getName() { - return this.name; - } - - @Override - public int hashCode() { - return Objects.hash(this.type, this.effectType, this.name); - } - - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/RecipeAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/RecipeAPI.java deleted file mode 100644 index 2ef837a7..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/RecipeAPI.java +++ /dev/null @@ -1,93 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import java.util.Iterator; -import org.bukkit.Bukkit; -import org.bukkit.Keyed; -import org.bukkit.inventory.Recipe; -import vg.civcraft.mc.civmodcore.inventory.RecipeManager; -import vg.civcraft.mc.civmodcore.util.NullCoalescing; - -/** - * Class of utility functions for Recipes. - * - * @deprecated Use {@link RecipeManager} instead. - */ -@Deprecated -public final class RecipeAPI { - - /** - *

Determines whether a recipe matches another recipe.

- * - *

Note: This matcher pretty much assumes that all recipes are keyed. If other kinds of recipes come up that - * aren't keyed, then support here can be added. But until then? /shrug

- * - * @param base The base recipe to base the matching upon. - * @param other The other recipe, the unknown. - * @return Returns true if the other recipe matches the base. - * - * @deprecated Use {@link RecipeManager#matchRecipe(Recipe, Recipe)} instead. - */ - @Deprecated - public static boolean matchRecipe(Recipe base, Recipe other) { - if (base == null) { - return false; - } - if (base instanceof Keyed && other instanceof Keyed) { - return NullCoalescing.equalsNotNull( - ((Keyed) base).getKey(), - ((Keyed) other).getKey()); - } - return false; - } - - /** - *

Registers a recipe to the Bukkit server.

- * - *

This is to prevent thrown exceptions for re-registered recipes. Since registrations often happen within a - * plugin's onEnable() method, an exception here will actually disable the plugin entirely, which is a bit - * disproportionate. You should check the returned boolean to see whether the registration was successful and - * handle that accordingly.

- * - * @param recipe The recipe to register. - * @return Returns true if the recipe was registered. - * - * @deprecated Use {@link RecipeManager#registerRecipe(Recipe)} instead. - */ - @Deprecated - public static boolean registerRecipe(Recipe recipe) { - if (recipe == null) { - return false; - } - try { - return Bukkit.getServer().addRecipe(recipe); - } - catch (Exception exception) { - return false; - } - } - - /** - * Removes a recipe from Bukkit's registered recipes list. - * - * @param recipe The shaped recipe to deregister. - * @return Returns true if the recipe was de-registered, or wasn't ever registered. - * - * @deprecated Use {@link RecipeManager#registerRecipe(Recipe)} instead. - */ - @Deprecated - public static boolean removeRecipe(Recipe recipe) { - if (recipe == null) { - return false; - } - Iterator iterator = Bukkit.getServer().recipeIterator(); - while (iterator.hasNext()) { - if (!matchRecipe(recipe, iterator.next())) { - continue; - } - iterator.remove(); - return true; - } - return true; - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/SpawnEggAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/SpawnEggAPI.java deleted file mode 100644 index d4a5f88d..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/SpawnEggAPI.java +++ /dev/null @@ -1,136 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import com.google.common.collect.BiMap; -import com.google.common.collect.ImmutableBiMap; -import javax.annotation.Nullable; -import org.bukkit.Material; -import org.bukkit.entity.EntityType; -import vg.civcraft.mc.civmodcore.inventory.items.SpawnEggUtils; - -/** - * Class of static APIs for Spawn Eggs. - * - * @deprecated Use {@link SpawnEggUtils} instead. - */ -@Deprecated -public final class SpawnEggAPI { - - private SpawnEggAPI() {} - - private static final BiMap spawnEggs = ImmutableBiMap.builder(). - put(Material.BAT_SPAWN_EGG, EntityType.BAT). - put(Material.BEE_SPAWN_EGG, EntityType.BEE). - put(Material.BLAZE_SPAWN_EGG, EntityType.BLAZE). - put(Material.CAT_SPAWN_EGG, EntityType.CAT). - put(Material.CAVE_SPIDER_SPAWN_EGG, EntityType.CAVE_SPIDER). - put(Material.CHICKEN_SPAWN_EGG, EntityType.CHICKEN). - put(Material.COD_SPAWN_EGG, EntityType.COD). - put(Material.COW_SPAWN_EGG, EntityType.COW). - put(Material.CREEPER_SPAWN_EGG, EntityType.CREEPER). - put(Material.DOLPHIN_SPAWN_EGG, EntityType.DOLPHIN). - put(Material.DONKEY_SPAWN_EGG, EntityType.DONKEY). - put(Material.DROWNED_SPAWN_EGG, EntityType.DROWNED). - put(Material.ELDER_GUARDIAN_SPAWN_EGG, EntityType.ELDER_GUARDIAN). - put(Material.ENDERMAN_SPAWN_EGG, EntityType.ENDERMAN). - put(Material.ENDERMITE_SPAWN_EGG, EntityType.ENDERMITE). - put(Material.EVOKER_SPAWN_EGG, EntityType.EVOKER). - put(Material.FOX_SPAWN_EGG, EntityType.FOX). - put(Material.GHAST_SPAWN_EGG, EntityType.GHAST). - put(Material.GUARDIAN_SPAWN_EGG, EntityType.GUARDIAN). - put(Material.HOGLIN_SPAWN_EGG, EntityType.HOGLIN). - put(Material.HORSE_SPAWN_EGG, EntityType.HORSE). - put(Material.HUSK_SPAWN_EGG, EntityType.HUSK). - put(Material.LLAMA_SPAWN_EGG, EntityType.LLAMA). - put(Material.MAGMA_CUBE_SPAWN_EGG, EntityType.MAGMA_CUBE). - put(Material.MOOSHROOM_SPAWN_EGG, EntityType.MUSHROOM_COW). - put(Material.MULE_SPAWN_EGG, EntityType.MULE). - put(Material.OCELOT_SPAWN_EGG, EntityType.OCELOT). - put(Material.PANDA_SPAWN_EGG, EntityType.PANDA). - put(Material.PARROT_SPAWN_EGG, EntityType.PARROT). - put(Material.PHANTOM_SPAWN_EGG, EntityType.PHANTOM). - put(Material.PIG_SPAWN_EGG, EntityType.PIG). - put(Material.PIGLIN_SPAWN_EGG, EntityType.PIGLIN). - put(Material.PILLAGER_SPAWN_EGG, EntityType.PILLAGER). - put(Material.POLAR_BEAR_SPAWN_EGG, EntityType.POLAR_BEAR). - put(Material.PUFFERFISH_SPAWN_EGG, EntityType.PUFFERFISH). - put(Material.RABBIT_SPAWN_EGG, EntityType.RABBIT). - put(Material.RAVAGER_SPAWN_EGG, EntityType.RAVAGER). - put(Material.SALMON_SPAWN_EGG, EntityType.SALMON). - put(Material.SHEEP_SPAWN_EGG, EntityType.SHEEP). - put(Material.SHULKER_SPAWN_EGG, EntityType.SHULKER). - put(Material.SILVERFISH_SPAWN_EGG, EntityType.SILVERFISH). - put(Material.SKELETON_HORSE_SPAWN_EGG, EntityType.SKELETON_HORSE). - put(Material.SKELETON_SPAWN_EGG, EntityType.SKELETON). - put(Material.SLIME_SPAWN_EGG, EntityType.SLIME). - put(Material.SPIDER_SPAWN_EGG, EntityType.SPIDER). - put(Material.SQUID_SPAWN_EGG, EntityType.SQUID). - put(Material.STRAY_SPAWN_EGG, EntityType.STRAY). - put(Material.STRIDER_SPAWN_EGG, EntityType.STRIDER). - put(Material.TRADER_LLAMA_SPAWN_EGG, EntityType.TRADER_LLAMA). - put(Material.TROPICAL_FISH_SPAWN_EGG, EntityType.TROPICAL_FISH). - put(Material.TURTLE_SPAWN_EGG, EntityType.TURTLE). - put(Material.VEX_SPAWN_EGG, EntityType.VEX). - put(Material.VILLAGER_SPAWN_EGG, EntityType.VILLAGER). - put(Material.VINDICATOR_SPAWN_EGG, EntityType.VINDICATOR). - put(Material.WANDERING_TRADER_SPAWN_EGG, EntityType.WANDERING_TRADER). - put(Material.WITCH_SPAWN_EGG, EntityType.WITCH). - put(Material.WITHER_SKELETON_SPAWN_EGG, EntityType.WITHER_SKELETON). - put(Material.WOLF_SPAWN_EGG, EntityType.WOLF). - put(Material.ZOGLIN_SPAWN_EGG, EntityType.ZOGLIN). - put(Material.ZOMBIE_HORSE_SPAWN_EGG, EntityType.ZOMBIE_HORSE). - put(Material.ZOMBIE_SPAWN_EGG, EntityType.ZOMBIE). - put(Material.ZOMBIE_VILLAGER_SPAWN_EGG, EntityType.ZOMBIE_VILLAGER). - put(Material.ZOMBIFIED_PIGLIN_SPAWN_EGG, EntityType.ZOMBIFIED_PIGLIN). - build(); - - /** - * Tests if a material is that of a spawn egg. - * - * @param material The material to test. - * @return Returns true if the material is that of a spawn egg. - * - * @deprecated Use {@link SpawnEggUtils#isSpawnEgg(Material)} instead. - */ - @Deprecated - public static boolean isSpawnEgg(Material material) { - if (material == null) { - return false; - } - return spawnEggs.containsKey(material); - } - - /** - * Gets the spawned entity type for a spawn egg. - * - * @param material The material, must be a spawn egg otherwise it's a guaranteed null. - * @return Returns the entity type that will be spawned from the spawn egg, or null. - * - * @deprecated Use {@link SpawnEggUtils#getEntityType(Material)} instead. - */ - @Deprecated - @Nullable - public static EntityType getEntityType(Material material) { - if (material == null) { - return null; - } - return spawnEggs.get(material); - } - - /** - * Gets the spawn egg material from an entity type. - * - * @param entityType The type of entity to match to the spawn egg. - * @return Returns a spawn egg material, or null. - * - * @deprecated Use {@link SpawnEggUtils#getSpawnEgg(EntityType)} instead. - */ - @Deprecated - @Nullable - public static Material getSpawnEgg(EntityType entityType) { - if (entityType == null) { - return null; - } - return spawnEggs.inverse().get(entityType); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/ToolAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/ToolAPI.java deleted file mode 100644 index 077e4a75..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/ToolAPI.java +++ /dev/null @@ -1,48 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import org.bukkit.Material; - -@Deprecated(forRemoval = true) -public final class ToolAPI { - - /** - * @deprecated Use {@link MaterialAPI#isSword(Material)} instead. - */ - @Deprecated - public static boolean isSword(Material material) { - return MaterialAPI.isSword(material); - } - - /** - * @deprecated Use {@link MaterialAPI#isShovel(Material)} instead. - */ - @Deprecated - public static boolean isShovel(Material material) { - return MaterialAPI.isShovel(material); - } - - /** - * @deprecated Use {@link MaterialAPI#isPickaxe(Material)} instead. - */ - @Deprecated - public static boolean isPickaxe(Material material) { - return MaterialAPI.isPickaxe(material); - } - - /** - * @deprecated Use {@link MaterialAPI#isAxe(Material)} instead. - */ - @Deprecated - public static boolean isAxe(Material material) { - return MaterialAPI.isAxe(material); - } - - /** - * @deprecated Use {@link MaterialAPI#isHoe(Material)} instead. - */ - @Deprecated - public static boolean isHoe(Material material) { - return MaterialAPI.isHoe(material); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/TreeTypeAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/TreeTypeAPI.java deleted file mode 100644 index 4a5cde30..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/TreeTypeAPI.java +++ /dev/null @@ -1,121 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import org.bukkit.Material; -import org.bukkit.TreeType; -import vg.civcraft.mc.civmodcore.inventory.items.TreeTypeUtils; - -/** - * @deprecated Use {@link TreeTypeUtils} instead. - */ -@Deprecated -public final class TreeTypeAPI { - - /** - * @deprecated Use {@link TreeTypeUtils#getMatchingTreeType(Material)} instead. - */ - @Deprecated - public static TreeType getMatchingTreeType(Material material) { - if (material == null) { - return null; - } - switch (material) { - case ACACIA_SAPLING: - case ACACIA_WOOD: - case ACACIA_LOG: - case ACACIA_LEAVES: - case STRIPPED_ACACIA_LOG: - case STRIPPED_ACACIA_WOOD: - return TreeType.ACACIA; - case BIRCH_SAPLING: - case BIRCH_WOOD: - case BIRCH_LOG: - case BIRCH_LEAVES: - case STRIPPED_BIRCH_LOG: - case STRIPPED_BIRCH_WOOD: - return TreeType.BIRCH; - case OAK_SAPLING: - case OAK_WOOD: - case OAK_LOG: - case OAK_LEAVES: - case STRIPPED_OAK_LOG: - case STRIPPED_OAK_WOOD: - return TreeType.TREE; - case JUNGLE_SAPLING: - case JUNGLE_WOOD: - case JUNGLE_LOG: - case JUNGLE_LEAVES: - case STRIPPED_JUNGLE_LOG: - case STRIPPED_JUNGLE_WOOD: - return TreeType.JUNGLE; - case DARK_OAK_SAPLING: - case DARK_OAK_WOOD: - case DARK_OAK_LOG: - case DARK_OAK_LEAVES: - case STRIPPED_DARK_OAK_LOG: - case STRIPPED_DARK_OAK_WOOD: - return TreeType.DARK_OAK; - case SPRUCE_SAPLING: - case SPRUCE_WOOD: - case SPRUCE_LOG: - case SPRUCE_LEAVES: - case STRIPPED_SPRUCE_LOG: - case STRIPPED_SPRUCE_WOOD: - return TreeType.REDWOOD; - case CHORUS_FLOWER: - case CHORUS_PLANT: - return TreeType.CHORUS_PLANT; - case RED_MUSHROOM: - case RED_MUSHROOM_BLOCK: - return TreeType.RED_MUSHROOM; - case BROWN_MUSHROOM: - case BROWN_MUSHROOM_BLOCK: - return TreeType.BROWN_MUSHROOM; - case COCOA: - return TreeType.COCOA_TREE; - default: - return null; - } - } - - /** - * @deprecated Use {@link TreeTypeUtils#getMatchingSapling(TreeType)} instead. - */ - @Deprecated - public static Material getMatchingSapling(TreeType type) { - if (type == null) { - return null; - } - switch(type) { - case ACACIA: - return Material.ACACIA_SAPLING; - case BIG_TREE: - case TREE: - case SWAMP: - return Material.OAK_SAPLING; - case BIRCH: - case TALL_BIRCH: - return Material.BIRCH_SAPLING; - case BROWN_MUSHROOM: - return Material.BROWN_MUSHROOM; - case CHORUS_PLANT: - return Material.CHORUS_PLANT; - case COCOA_TREE: - return Material.COCOA; - case DARK_OAK: - return Material.DARK_OAK_SAPLING; - case JUNGLE: - case SMALL_JUNGLE: - case JUNGLE_BUSH: - return Material.JUNGLE_SAPLING; - case MEGA_REDWOOD: - case REDWOOD: - case TALL_REDWOOD: - return Material.SPRUCE_SAPLING; - case RED_MUSHROOM: - return Material.RED_MUSHROOM; - default: - return null; - } - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/WorldAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/WorldAPI.java deleted file mode 100644 index 3cac1652..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/WorldAPI.java +++ /dev/null @@ -1,90 +0,0 @@ -package vg.civcraft.mc.civmodcore.api; - -import java.util.Objects; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.World; -import vg.civcraft.mc.civmodcore.world.WorldUtils; - -/** - * Class of utility functions for Worlds. - * - * @deprecated Use {@link WorldUtils} instead. - */ -@Deprecated -public final class WorldAPI { - - /** - * Determines if a world is currently loaded. - * - * @param world World to test. - * @return Returns true if the world is loaded. - * - * @deprecated Use {@link WorldUtils#isWorldLoaded(World)} instead. - */ - @Deprecated - public static boolean isWorldLoaded(World world) { - if (world == null) { - return false; - } - // Same method in Location.isWorldLoaded() - return Bukkit.getWorld(world.getUID()) != null; - } - - /** - * Determines if a chunk is loaded in an efficient manner without loading any chunks. - * - * @param world The world the target chunk is located within. - * @param x The (CHUNK) X coordinate. - * @param z The (CHUNK) Z coordinate. - * @return Returns true if the chunk is loaded. - * - * @deprecated Use {@link WorldUtils#isChunkLoaded(World, int, int)} instead. - */ - @Deprecated - public static boolean isChunkLoaded(World world, int x, int z) { - if (!isWorldLoaded(world)) { - return false; - } - return world.isChunkLoaded(x, z); - } - - /** - * Retrieves a chunk only if it's loaded. - * - * @param world The world the target chunk is located within. - * @param x The (CHUNK) X coordinate. - * @param z The (CHUNK) Z coordinate. - * @return Returns the loaded chunk, or null. - * - * @deprecated Use {@link WorldUtils#getLoadedChunk(World, int, int)} instead. - */ - @Deprecated - public static Chunk getLoadedChunk(final World world, final int x, final int z) { - if (!isChunkLoaded(world, x, z)) { - return null; - } - return world.getChunkAt(x, z); - } - - /** - * Determines if a block is loaded by nature of whether the chunk it's in is loaded. - * - * @param location The block location. - * @return Returns true if the block is laoded. - * - * @deprecated Use {@link WorldUtils#isBlockLoaded(Location)} instead. - */ - @Deprecated - public static boolean isBlockLoaded(Location location) { - if (!LocationAPI.isValidLocation(location)) { - return false; - } - World world = Objects.requireNonNull(location.getWorld()); - int chunkX = location.getBlockX() >> 4; - int chunkZ = location.getBlockZ() >> 4; - return world.isChunkLoaded(chunkX, chunkZ); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/package-info.java b/src/main/java/vg/civcraft/mc/civmodcore/api/package-info.java deleted file mode 100644 index 41b27c19..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/api/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * This package was created as a sort of island of tranquility for standardised, standalone functions... however it's - * gotten a little unwieldy and so the plan is to deprecate and disperse the functionality to more sensible locations. - * - * The plan is to remove the "api" package completely. - */ -package vg.civcraft.mc.civmodcore.api; diff --git a/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/ChatListener.java b/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/ChatListener.java deleted file mode 100644 index 596783bd..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/ChatListener.java +++ /dev/null @@ -1,36 +0,0 @@ -package vg.civcraft.mc.civmodcore.chatDialog; - -import java.util.Collections; -import java.util.List; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.server.TabCompleteEvent; - -@Deprecated -public class ChatListener implements Listener { - - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) - public void tabComplete(TabCompleteEvent e) { - if (!(e.getSender() instanceof Player)) { - return; - } - Dialog dia = DialogManager.getDialog((Player) e.getSender()); - if (dia != null) { - String[] split = e.getBuffer().split(" "); - List complet = dia.onTabComplete(split.length > 0 ? split[split.length - 1] : "", split); - if (complet == null) { - complet = Collections.emptyList(); - } - e.setCompletions(complet); - } - } - - @EventHandler - public void logoff(PlayerQuitEvent e) { - DialogManager.forceEndDialog(e.getPlayer()); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/Dialog.java b/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/Dialog.java deleted file mode 100644 index 9aa61ed7..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/Dialog.java +++ /dev/null @@ -1,67 +0,0 @@ -package vg.civcraft.mc.civmodcore.chatDialog; - -import java.util.List; -import org.bukkit.Bukkit; -import org.bukkit.conversations.Conversation; -import org.bukkit.conversations.ConversationContext; -import org.bukkit.conversations.ConversationFactory; -import org.bukkit.conversations.Prompt; -import org.bukkit.conversations.StringPrompt; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - -/** - * @deprecated Use {@link vg.civcraft.mc.civmodcore.chat.dialog.Dialog} instead. - */ -@Deprecated -public abstract class Dialog { - - protected Player player; - - private Conversation convo; - - public Dialog(Player player, JavaPlugin plugin) { - this(player, plugin, null); - } - - public Dialog(Player player, JavaPlugin plugin, final String toDisplay) { - DialogManager.registerDialog(player, this); - this.player = player; - - Bukkit.getScheduler().runTask(plugin, (Runnable) player::closeInventory); - - convo = new ConversationFactory(plugin).withModality(false).withLocalEcho(false) - .withFirstPrompt(new StringPrompt() { - - @Override - public String getPromptText(ConversationContext arg0) { - if (toDisplay != null) { - return toDisplay; - } - return ""; - } - - @Override - public Prompt acceptInput(ConversationContext arg0, String arg1) { - onReply(arg1.split(" ")); - return Prompt.END_OF_CONVERSATION; - } - - }).buildConversation(player); - - convo.begin(); - } - - public abstract void onReply(String[] message); - - public abstract List onTabComplete(String wordCompleted, String[] fullMessage); - - public Player getPlayer() { - return player; - } - - public void end() { - convo.abandon(); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/DialogManager.java b/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/DialogManager.java deleted file mode 100644 index 9cbcc598..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/DialogManager.java +++ /dev/null @@ -1,45 +0,0 @@ -package vg.civcraft.mc.civmodcore.chatDialog; - -import java.util.Map; -import java.util.TreeMap; -import java.util.UUID; -import org.bukkit.entity.Player; - -/** - * @deprecated Use {@link vg.civcraft.mc.civmodcore.chat.dialog.DialogManager} instead. - */ -@Deprecated -public class DialogManager { - - private static Map dialogs = new TreeMap<>(); - - private DialogManager() {} - - public static Dialog getDialog(Player p) { - return getDialog(p.getUniqueId()); - } - - public static Dialog getDialog(UUID uuid) { - return dialogs.get(uuid); - } - - public static void registerDialog(Player p, Dialog dialog) { - Dialog current = dialogs.get(p.getUniqueId()); - if (current != null) { - current.end(); - } - dialogs.put(p.getUniqueId(), dialog); - } - - public static void forceEndDialog(Player p) { - forceEndDialog(p.getUniqueId()); - } - - public static void forceEndDialog(UUID uuid) { - Dialog dia = dialogs.remove(uuid); - if (dia != null) { - dia.end(); - } - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/LDialog.java b/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/LDialog.java deleted file mode 100644 index 8dd875dd..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/LDialog.java +++ /dev/null @@ -1,36 +0,0 @@ -package vg.civcraft.mc.civmodcore.chatDialog; - -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; -import org.bukkit.entity.Player; -import vg.civcraft.mc.civmodcore.CivModCorePlugin; - -/** - * @deprecated Create an anonymous instance of {@link vg.civcraft.mc.civmodcore.chat.dialog.Dialog} instead. - */ -@Deprecated -public class LDialog extends Dialog { - - private Consumer replyFunction; - - public LDialog(Player player, Consumer replyFunction) { - this(player, replyFunction, null); - } - - public LDialog(Player player, Consumer replyFunction, String msgToShow) { - super(player, CivModCorePlugin.getInstance(), msgToShow); - this.replyFunction = replyFunction; - } - - @Override - public void onReply(String[] message) { - replyFunction.accept(String.join(" ", message)); - } - - @Override - public List onTabComplete(String wordCompleted, String[] fullMessage) { - return Collections.emptyList(); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/package-info.java b/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/package-info.java deleted file mode 100644 index 2ee0705f..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * The goal with this package is to relocate it to "chat.dialog" - */ -package vg.civcraft.mc.civmodcore.chatDialog; diff --git a/src/main/java/vg/civcraft/mc/civmodcore/command/MailBoxAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/command/MailBoxAPI.java deleted file mode 100644 index 41c86cb9..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/command/MailBoxAPI.java +++ /dev/null @@ -1,56 +0,0 @@ -package vg.civcraft.mc.civmodcore.command; - -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import vg.civcraft.mc.civmodcore.playersettings.PlayerSettingAPI; -import vg.civcraft.mc.civmodcore.playersettings.impl.collection.ListSetting; - -public class MailBoxAPI { - - private static ListSetting mail; - - /** - * Internal setup, should only be called when CivModCore is enabling - */ - public static void setup() { - if (mail != null) { - throw new IllegalStateException("Was already registed"); - } - /*mail = new ListSetting<>(CivModCorePlugin.getInstance(), "Mail box", "cmcMailBox", - new ItemStack(Material.STICK), null, String.class, false); */ - PlayerSettingAPI.registerSetting(mail, null); - } - - /** - * Adds a new messages to the players mail box - * @param player UUID of the player to send message to - * @param msg Message to add - */ - public static void addMail(UUID player, String msg) { - Preconditions.checkNotNull(player, "Player may not be null"); - Preconditions.checkNotNull(msg, "Message to add may not be null"); - mail.addElement(player, msg); - } - - /** - * Gets all pending messages in a players mail box - * @param player Player to mail box of - * @return Messages in the players mail box - */ - public static List getMail(UUID player) { - Preconditions.checkNotNull(player, "Player may not be null"); - return mail.getValue(player); - } - - /** - * Clears all mail a player has - * @param player - */ - public static void clearMail(UUID player) { - Preconditions.checkNotNull(player, "Player may not be null"); - mail.setValue(player, new ArrayList<>()); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCache.java b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCache.java deleted file mode 100644 index 1949b3fd..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCache.java +++ /dev/null @@ -1,20 +0,0 @@ -package vg.civcraft.mc.civmodcore.serialization; - -/** - * Class designed to encode and decode directly on NBT rather than use cache fields. - */ -public abstract class NBTCache implements NBTSerializable { - - protected final NBTCompound nbt = new NBTCompound(); - - @Override - public void serialize(NBTCompound other) { - other.adopt(this.nbt); - } - - @Override - public void deserialize(NBTCompound other) { - this.nbt.adopt(other); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java index 2e88a2ea..78d68d63 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java @@ -38,11 +38,8 @@ public class NBTCompound implements Cloneable, Validation { public static final String NULL_STRING = "\u0000"; private static final String INTERNAL_MAP_KEY = "map"; - private static final String UUID_MOST_SUFFIX = "Most"; - private static final String UUID_LEAST_SUFFIX = "Least"; - private static final String UUID_KEY = "uuid"; private NBTTagCompound tag; @@ -842,36 +839,6 @@ public void setCompoundArray(String key, NBTCompound[] values) { } } - /** - * Gets a list value from a key. - * - * @param key The key to get the value of. - * @return The value of the key, default: empty list - */ - public NBTCompoundList getSerializableList(String key) { - Preconditions.checkArgument(!Strings.isNullOrEmpty(key)); - if (!this.tag.hasKeyOfType(key, 9)) { - return new NBTCompoundList<>(); - } - return NBTCompoundList.deserialize(this.tag.getList(key, 10)); - } - - /** - * Sets a list value to a key. - * - * @param key The key to set to value to. - * @param value The value to set to the key. - */ - public void setSerializableList(String key, NBTCompoundList value) { - Preconditions.checkArgument(!Strings.isNullOrEmpty(key)); - if (value == null) { - this.tag.remove(key); - } - else { - this.tag.set(key, value.serialize()); - } - } - // ------------------------------------------------------------ // NBT Base Functions // ------------------------------------------------------------ diff --git a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompoundList.java b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompoundList.java deleted file mode 100644 index 83fcdee8..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompoundList.java +++ /dev/null @@ -1,79 +0,0 @@ -package vg.civcraft.mc.civmodcore.serialization; - -import static vg.civcraft.mc.civmodcore.util.NullCoalescing.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import net.minecraft.server.v1_16_R3.NBTBase; -import net.minecraft.server.v1_16_R3.NBTTagCompound; -import net.minecraft.server.v1_16_R3.NBTTagList; -import org.apache.commons.lang3.reflect.FieldUtils; -import vg.civcraft.mc.civmodcore.util.Validation; - -/** - *

Represents a list of nbt class serializable elements of the same type.

- * - *

Read More:

- *
    - *
  • {@link NBTSerialization}
  • - *
  • {@link NBTSerialization#serialize(NBTSerializable)}
  • - *
  • {@link NBTSerialization#deserialize(NBTCompound)}
  • - *
- */ -@Deprecated -public class NBTCompoundList extends ArrayList { - - /** - * Serializes each element into an {@link NBTTagList}. - * - * @return Returns a populated {@link NBTTagList}. - */ - public NBTTagList serialize() { - NBTTagList list = new NBTTagList(); - List inner = getInnerList(list); - stream().filter(Objects::nonNull) - .map(NBTSerialization::serialize) - .filter(Validation::checkValidity) - .map(NBTCompound::getRAW) - .forEachOrdered(inner::add); - return list; - } - - /** - * Converts a {@link NBTTagList} into an NBTCompoundList, deserializing each element to - * the given generic type. - * - * @param The generic type each element should be cast to. - * @param list The {@link NBTTagList} to convert into NBTCompoundList. - * @return Returns a new NBTCompoundList. - */ - @SuppressWarnings("unchecked") - public static NBTCompoundList deserialize(NBTTagList list) { - NBTCompoundList wrapper = new NBTCompoundList<>(); - if (list == null) { - return wrapper; - } - if (list.d_() != 10) { - return wrapper; - } - getInnerList(list).stream() - .map(nbt -> chain(() -> new NBTCompound((NBTTagCompound) nbt))) - .map(nbt -> chain(() -> (T) NBTSerialization.deserialize(nbt))) - .filter(Objects::nonNull) - .forEachOrdered(wrapper::add); - return wrapper; - } - - @SuppressWarnings("unchecked") - private static List getInnerList(NBTTagList list) { - try { - return (List) FieldUtils.readField(list, "list", true); - } - catch (Exception exception) { - throw new NBTSerializationException( - "Could not encode NBTCompound list to NBTTagList: could not access inner list of NBTTagList.", - exception); - } - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/EnumUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/util/EnumUtils.java deleted file mode 100644 index 14ba1f6e..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/util/EnumUtils.java +++ /dev/null @@ -1,72 +0,0 @@ -package vg.civcraft.mc.civmodcore.util; - -import com.google.common.base.Strings; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.reflect.MethodUtils; - -/** - * Class of enum utilities. - * - * @deprecated Use {@link org.apache.commons.lang3.EnumUtils} instead. - */ -@Deprecated -public class EnumUtils { - - /** - * Retrieves a enum element from an enum class if the given slug matches. - * - * @param The enum type. - * @param clazz The enum class. - * @param slug The slug of the intended enum element. - * @param caseInsensitive Set to true if you want to check to not care about case sensitivity. - * @return Returns the matched enum element, or null. - * - * @deprecated Use {@link org.apache.commons.lang3.EnumUtils#getEnum(Class, String)} or - * {@link org.apache.commons.lang3.EnumUtils#getEnumIgnoreCase(Class, String)} instead. - */ - @Deprecated - @SuppressWarnings("unchecked") - public static > T fromSlug(Class clazz, String slug, boolean caseInsensitive) { - if (clazz == null || Strings.isNullOrEmpty(slug)) { - return null; - } - T[] values = null; - try { - values = (T[]) MethodUtils.invokeExactStaticMethod(clazz, "values", null); - } - catch (Exception ignored) { } - if (ArrayUtils.isEmpty(values)) { - return null; - } - for (T value : values) { - if (caseInsensitive) { - if (TextUtil.stringEqualsIgnoreCase(value.name(), slug)) { - return value; - } - } - else { - if (TextUtil.stringEquals(value.name(), slug)) { - return value; - } - } - } - return null; - } - - /** - * Null safe way of getting an enum elements' name. - * - * @param element The enum element to get the name of. - * @return Return an element's name or null. - * - * @deprecated Use {@link Chainer} instead. - */ - @Deprecated - public static String getSlug(Enum element) { - if (element == null) { - return null; - } - return element.name(); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/Guard.java b/src/main/java/vg/civcraft/mc/civmodcore/util/Guard.java deleted file mode 100644 index da9b0cd0..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/util/Guard.java +++ /dev/null @@ -1,43 +0,0 @@ -package vg.civcraft.mc.civmodcore.util; - -import org.apache.commons.lang.NullArgumentException; - -/** - * Class for checking arguments and throwing null argument exceptions. - * - * @deprecated Just use {@link com.google.common.base.Preconditions Preconditions}. - */ -@Deprecated -public final class Guard { - - @Deprecated - public static void ArgumentNotNull(Object argument, String parameterName) { - if (parameterName == null) { - throw new NullArgumentException("parameterName"); - } - if (argument == null) { - throw new NullArgumentException(parameterName); - } - } - - @Deprecated - public static void ArgumentNotNullOrEmpty(String argument, String parameterName) { - if (parameterName == null) { - throw new NullArgumentException("parameterName"); - } - if (argument == null) { - throw new NullArgumentException(parameterName); - } - if (argument.equals("")) { - throw new RuntimeException(parameterName + " can't be empty."); - } - } - - @Deprecated - public static void ArgumentNotEquals(Object argument, String parameterName, Object other, String otherName) { - if (argument.equals(other)) { - throw new RuntimeException(parameterName + " can't be equal to " + otherName); - } - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/Iteration.java b/src/main/java/vg/civcraft/mc/civmodcore/util/Iteration.java deleted file mode 100644 index fa1c5ee2..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/util/Iteration.java +++ /dev/null @@ -1,350 +0,0 @@ -package vg.civcraft.mc.civmodcore.util; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ThreadLocalRandom; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.function.Supplier; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.ArrayUtils; - -/** - * @deprecated Use {@link MoreArrayUtils}, {@link MoreCollectionUtils}, and {@link MoreMapUtils} instead. - */ -@Deprecated -public final class Iteration { - - @FunctionalInterface - public interface ElementAndBoolConsumer { - void accept(T former, boolean latter); - } - - /** - *

DO NOT USE THIS!

- * - *

This method was originally created for developer ease of use, but instead has become a hot bed for - * hidden bugs. The reason for that being the varargs. If you pass in an object that you expect to be - * handled by {@link #isNullOrEmpty(Collection)} but don't realise the object doesn't actually inherit - * from {@link Collection}, like a {@link Map}, then it falls back to this version of the method, giving - * the illusion that it's doing what you intended. But instead of checking whether the object you gave - * is null or empty, it's instead only checking if the method itself has any parameters.

- * - * @deprecated Use {@link ArrayUtils#isEmpty(Object[])} instead. - */ - @Deprecated - @SafeVarargs - public static boolean isNullOrEmpty(T... array) { - return ArrayUtils.isEmpty(array); - } - - /** - *

Determines whether a collection is null or empty.

- * - *

Note: This will not check the elements within the collection. It only checks if the collection itself exists - * and has elements. If for example the collection has 100 null elements, this function would still return true.

- * - * @param The type of collection. - * @param collection The collection to check. - * @return Returns true if the collection exists and at least one item. - * - * @deprecated Use {@link CollectionUtils#isEmpty(Collection)} instead. - */ - @Deprecated - public static boolean isNullOrEmpty(Collection collection) { - return collection == null || collection.isEmpty(); - } - - /** - * Returns the first matching item in the parameters, which is particularly useful when you need to match Materials - * without necessarily needing to create a new {@link vg.civcraft.mc.civmodcore.api.MaterialAPI MaterialAPI}. - * - * @param The type of the object to match. - * @param base The object to match. - * @param values An array of items to match against. - * @return Returns true if the base is found within the values. - * - * @deprecated Use {@link org.apache.commons.lang3.ArrayUtils#contains(Object[], Object)} instead. - */ - @Deprecated - @SafeVarargs - public static boolean contains(T base, T... values) { - if (ArrayUtils.isEmpty(values)) { - return false; - } - for (T value : values) { - if (Objects.equals(base, value)) { - return true; - } - } - return false; - } - - /** - * Iterates through a collection before clearing it completely. Useful for wiping out data on plugin disable. - * - * @param The generic type of the collection. - * @param collection The collection to iterate and clear. - * @param processor The iteration processor which will be called for each item in the collection. - * - * @deprecated Use {@link Collection#forEach(Consumer)} and {@link Collection#clear()} instead. - */ - @Deprecated - public static void iterateThenClear(Collection collection, Consumer processor) { - if (isNullOrEmpty(collection) || processor == null) { - return; - } - for (T element : collection) { - processor.accept(element); - } - collection.clear(); - } - - /** - * Iterates through a collection, whereby each element has knowledge of whether it's the last element. - * - * @param The generic type of the collection. - * @param collection The collection to iterate. - * @param processor The iteration processor which will be called for each item in the collection. - * - * @deprecated Use {@link Collection#iterator()} instead. - */ - @Deprecated - public static void iterateHasNext(Collection collection, ElementAndBoolConsumer processor) { - if (isNullOrEmpty(collection) || processor == null) { - return; - } - Iterator iterator = collection.iterator(); - while (iterator.hasNext()) { - processor.accept(iterator.next(), iterator.hasNext()); - } - } - - /** - * Fills an array with a particular value. - * - * @param The type of the array. - * @param array The array to fill. - * @param value The value to fill the array with. - * @return Returns the given array with the filled values. - * - * @deprecated Use {@link MoreArrayUtils#fill(Object[], Object)} instead. - */ - @Deprecated - public static T[] fill(T[] array, T value) { - if (ArrayUtils.isEmpty(array)) { - return array; - } - Arrays.fill(array, value); - return array; - } - - /** @deprecated Use {@link MoreArrayUtils#anyMatch(Object[], Predicate)} instead. */ - @Deprecated - public static boolean some(T[] array, Predicate predicate) { - return anyMatch(array, predicate); - } - - /** - *

Tests whether there is at least one element in the given array that passes the criteria of the given - * predicate.

- * - *

Emulates: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

- * - * @param The type of the array elements. - * @param array The array to iterate. - * @param predicate The element tester. - * @return Returns true if at least one element passes the predicate test. Or false if the array fails the - * {@link ArrayUtils#isEmpty(Object[]) isNullOrEmpty()} test, or true if the give predicate is null. - * - * @deprecated Use {@link MoreArrayUtils#anyMatch(Object[], Predicate)} instead. - */ - @Deprecated - public static boolean anyMatch(T[] array, Predicate predicate) { - if (ArrayUtils.isEmpty(array)) { - return false; - } - if (predicate == null) { - return true; - } - for (T element : array) { - if (predicate.test(element)) { - return true; - } - } - return false; - } - - /** @deprecated Use {@link MoreArrayUtils#allMatch(Object[], Predicate)} instead. */ - @Deprecated - public static boolean every(T[] array, Predicate predicate) { - return allMatch(array, predicate); - } - - /** - *

Tests whether every element in an array passes the criteria of the given predicate.

- * - *

Emulates: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

- * - * @param The type of the array elements. - * @param array The array to iterate. - * @param predicate The element tester. - * @return Returns true if no element fails the predicate test, or if the array fails the - * {@link ArrayUtils#isEmpty(Object[]) isNullOrEmpty()} test, or if the give predicate is null. - * - * @deprecated Use {@link MoreArrayUtils#allMatch(Object[], Predicate)} instead. - */ - @Deprecated - public static boolean allMatch(T[] array, Predicate predicate) { - if (ArrayUtils.isEmpty(array)) { - return true; - } - if (predicate == null) { - return true; - } - for (T element : array) { - if (!predicate.test(element)) { - return false; - } - } - return true; - } - - /** - * Determines whether a Map Entry is valid in that it exists and so does the key and value. - * - * @param entry The map entry itself. - * @return Returns true if the entry is considered valid. - * - * @deprecated Use {@link MoreMapUtils#validEntry(Map.Entry)} instead. - */ - @Deprecated - public static boolean validEntry(Map.Entry entry) { - if (entry == null) { - return false; - } - if (entry.getKey() == null) { - return false; - } - if (entry.getValue() == null) { - return false; - } - return true; - } - - /** - * Creates a new collection with a given set of predefined elements, if any are given. - * - * @param The type of the elements to store in the collection. - * @param constructor The constructor for the collection. - * @param elements The elements to add to the collection. - * @return Returns a new collection, or null if no constructor was given, or the constructor didn't produce a new - * collection. - * - * @deprecated Use {@link CollectionUtils#addAll(Collection, Object[])} instead. - */ - @Deprecated - @SafeVarargs - public static > K collect(Supplier constructor, T... elements) { - if (constructor == null) { - return null; - } - K collection = constructor.get(); - if (collection == null) { - return null; - } - if (ArrayUtils.isEmpty(elements)) { - return collection; - } - addAll(collection, elements); - return collection; - } - - /** - * Use this to add arbitrary amounts of things to a collection that doesn't already exist as a collection, - * which means you can avoid the dreaded {@code Arrays.asList(thing, thing2);}, thereby creating a new list - * just to immediately discard it in the next operation execution. - * - * @param The type of the elements of the collection and to add. - * @param collection The collection to add the values to. - * @param values The values to add to the collection. - * - * @deprecated Use {@link CollectionUtils#addAll(Collection, Object[])} instead. - */ - @Deprecated - @SafeVarargs - public static void addAll(Collection collection, T... values) { - if (collection == null || ArrayUtils.isEmpty(values)) { - return; - } - for (T value : values) { - // Do not let this be simplified. There's no reason to create a new ArrayList - // as it would be immediately discarded and that's... bad - collection.add(value); - } - } - - /** - * Removes the element at the end of the given list. - * - * @param The type of the list's elements. - * @param list The list to remove the last element from. - * @return Returns the element removed. - * - * @deprecated Use {@link MoreCollectionUtils#removeLastElement(List)} instead. - */ - @Deprecated - public static T removeLastElement(List list) { - if (isNullOrEmpty(list)) { - return null; - } - return list.remove(list.size() - 1); - } - - /** - * Retrieves a random element from an array of elements. - * - * @param The type of element. - * @param array The array to retrieve a value from. - * @return Returns a random element, or null. - * - * @deprecated Use {@link MoreArrayUtils#randomElement(Object[])} instead. - */ - @Deprecated - @SafeVarargs - public static T randomElement(final T... array) { - if (ArrayUtils.isEmpty(array)) { - return null; - } - if (array.length == 1) { - return array[0]; - } - return array[ThreadLocalRandom.current().nextInt(array.length)]; - } - - /** - * Retrieves a random element from an list of elements. - * - * @param The type of element. - * @param list The list to retrieve a value from. - * @return Returns a random element, or null. - * - * @deprecated Use {@link MoreCollectionUtils#randomElement(List)} instead. - */ - @Deprecated - public static T randomElement(final List list) { - if (isNullOrEmpty(list)) { - return null; - } - final int size = list.size(); - if (size == 1) { - return list.get(0); - } - return list.get(ThreadLocalRandom.current().nextInt(size)); - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/MapUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/util/MapUtils.java deleted file mode 100644 index 1f3fc284..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/util/MapUtils.java +++ /dev/null @@ -1,164 +0,0 @@ -package vg.civcraft.mc.civmodcore.util; - -import com.google.common.collect.BiMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import org.apache.commons.lang3.ArrayUtils; -import org.bukkit.Material; -import vg.civcraft.mc.civmodcore.inventory.items.MaterialUtils; - -/** - * Class of Map utilities. - * - * @deprecated Use {@link MoreMapUtils} instead. - */ -@Deprecated -public final class MapUtils { - - /** - *

Determines whether a map is null or empty.

- * - *

Note: This will not check the elements within the map. It only checks if the map itself exists and has - * key-value pairs. If for example the map has 100 null keyed values, this function would still return true.

- * - * @param The type of keys. - * @param The type of values. - * @param map The map to check. - * @return Returns true if the map exists and at least one key-value pair. - * - * @deprecated Use {@link org.apache.commons.collections4.MapUtils#isEmpty(Map)} instead. - */ - @Deprecated - public static boolean isNullOrEmpty(Map map) { - return map == null || map.isEmpty(); - } - - /** - * Retrieves a key from a map based on a given value. If two or more keys share a value, - * the key that's returned is the first that matches during standard iteration. - * - * @param The key type. - * @param The value type. - * @param map The map to retrieve the key from. - * @param value The value to based the search on. - * @return Returns the key, or null. - * - * @deprecated Use {@link MoreMapUtils#getKeyFromValue(Map, Object)} instead. - */ - @Deprecated - public static K getKeyFromValue(final Map map, final V value) { - if (isNullOrEmpty(map)) { - return null; - } - if (map instanceof BiMap) { - return ((BiMap) map).inverse().get(value); - } - for (final Map.Entry entry : map.entrySet()) { - if (NullCoalescing.equals(value, entry.getValue())) { - return entry.getKey(); - } - } - return null; - } - - /** - * Attempts to retrieve a value from a given map from a range of keys. - * - * @param The key type of the map. - * @param The value type of the map. - * @param The desired return type. - * @param map The map to retrieve the value from. - * @param fallback The value that should be returned if none of the keys return a [valid] value. - * @param keys The keys to check. - * @return Returns a value, either from the keys or the fallback, both of which may be null. - * - * @deprecated Use {@link MoreMapUtils#attemptGet(Map, Object, Object[])} instead. - */ - @Deprecated - @SafeVarargs - public static R attemptGet(Map map, R fallback, K... keys) { - return attemptGet(map, null, fallback, keys); - } - - /** - * Attempts to retrieve a value from a given map from a range of keys. - * - * @param The key type of the map. - * @param The value type of the map. - * @param The desired return type. - * @param map The map to retrieve the value from. - * @param parser The function to process the value from the map. Null will use a default parser. - * @param fallback The value that should be returned if none of the keys return a [valid] value. - * @param keys The keys to check. - * @return Returns a value, either from the keys or the fallback, both of which may be null. - * - * @deprecated Use {@link MoreMapUtils#attemptGet(Map, Function, Object, Object[])} instead. - */ - @Deprecated - @SafeVarargs - @SuppressWarnings("unchecked") - public static R attemptGet(Map map, Function parser, R fallback, K... keys) { - if (isNullOrEmpty(map) || ArrayUtils.isEmpty(keys)) { - return fallback; - } - if (parser == null) { - // Default parser (basic cast) - parser = (V v) -> (R) v; - } - for (K key : keys) { - if (!map.containsKey(key)) { - continue; - } - try { - return parser.apply(map.get(key)); - } - // Yeeeaaaah, I know this is a catch all exception and that's bad, but this really could be anything since - // the parser function could be anything.. it could be a class cast, a null reference, number format... - // But since this is a value parser and not an arbitrary code executor, nothing complication will be run, - // so any exception cab be interpreted as a bad or unexpected value. - catch (Exception ignored) { - return fallback; - } - } - return fallback; - } - - // ------------------------------------------------------------ - // Parsers - // ------------------------------------------------------------ - - /** - *

Parses a list from a map.

- * - *

Use with {@link #attemptGet(Map, Function, Object, Object[])} as the parser.

- * - * @param value The value retrieved from the map. - * @return Returns the value cast to a list, or null. - */ - public static List parseList(Object value) { - if (value instanceof List) { - return (List) value; - } - return null; - } - - /** - *

Parses a material from a map.

- * - *

Use with {@link #attemptGet(Map, Function, Object, Object[])} as the parser.

- * - * @param value The value retrieved from the map. - * @return Returns the value as a material, or null. - */ - public static Material parseMaterial(Object value) { - if (value instanceof Material) { - return (Material) value; - } - if (value instanceof String) { - return MaterialUtils.getMaterial((String) value); - } - return null; - } - -} diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/NullCoalescing.java b/src/main/java/vg/civcraft/mc/civmodcore/util/NullCoalescing.java deleted file mode 100644 index e6093d9f..00000000 --- a/src/main/java/vg/civcraft/mc/civmodcore/util/NullCoalescing.java +++ /dev/null @@ -1,185 +0,0 @@ -package vg.civcraft.mc.civmodcore.util; - -import com.google.common.base.Objects; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * @deprecated Use {@link NullUtils} instead. - */ -@Deprecated -public final class NullCoalescing { - - @FunctionalInterface - public interface NullChecker { - T get() throws Exception; - } - - /** - *

Returns the first non-null given parameter, if any are given.

- * - *

Emulates: - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

- * - * @param Any non-primitive type. - * @param items The list of parameters to find a non-null value from. - * @return Returns the first non-null value found, or null. - * - * @deprecated Use {@link NullUtils#firstNonNull(Object[])} instead. - */ - @Deprecated - @SafeVarargs - public static T coalesce(T... items) { - for (T item : items) { - if (item != null) { - return item; - } - } - return null; - } - - /** - *

Allows developers to chain statements that might otherwise require a ton of null checking.

- * - *

Emulates: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

- * - * @param Any non-primitive type. - * @param statement Function that throws an exception to call the chained statement within. - * @return Returns the result of the chained statement, or null if the chain failed. - * - * @deprecated Use {@link Chainer} instead. - */ - @Deprecated - public static T chain(NullChecker statement) { - return chain(statement, null); - } - - /** - *

Allows developers to chain statements that might otherwise require a ton of null checking.

- * - *

Emulates: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining and - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

- * - * @param Any non-primitive type. - * @param statement Function that throws an exception to call the chained statement within. - * @param fallback The value that will be fallen back upon if something goes wrong. - * @return Returns the result of the chained statement, or the fallback if the chain failed. - * - * @deprecated Use {@link Chainer} instead. - */ - @Deprecated - public static T chain(NullChecker statement, T fallback) { - if (statement == null) { - return fallback; - } - try { - return statement.get(); - } - catch (Exception ignored) { - return fallback; - } - } - - /** - * Runs a handler only if the given value is not null. - * - * @param The type of the given parameter. - * @param value The given parameter. - * @param handler The handler to run if the given parameter exists. - * - * @deprecated Just use an if statement. - */ - @Deprecated - public static void exists(T value, Consumer handler) { - if (value != null && handler != null) { - handler.accept(value); - } - } - - /** - * Executes a function to supply a value should that value not already exist. - * - * @param The type of the value. - * @param value The given value. - * @param handler The supplier that will be run should the given value be null. - * @return Returns the given value or the result of the handler. - * - * @deprecated Just use an if statement. - */ - @Deprecated - public static T notExists(T value, Supplier handler) { - if (value == null && handler != null) { - value = handler.get(); - } - return value; - } - - /** - * Checks whether a value can be cast to a particular type. - * - * @param The type to cast to. - * @param clazz The class of the type. - * @param value The value to attempt to cast. - * @return Returns the value cast to the given type, nor null. - * - * @deprecated Use {@link MoreClassUtils#castOrNull(Class, Object)} instead. - */ - @Deprecated - @SuppressWarnings("unchecked") - public static T castOrNull(Class clazz, Object value) { - if (clazz == null || value == null) { - return null; - } - if (clazz.isAssignableFrom(value.getClass())) { - return (T) value; - } - return null; - } - - /** - * Determines if two objects objects are equal. - * - * @param former The former object. - * @param latter The latter object. - * @return Returns true if the values equal each other. - * - * @deprecated Use {@link Objects#equal(Object, Object)} instead. - */ - @Deprecated - public static boolean equals(Object former, Object latter) { - if (former == latter) { - return true; - } - if (former != null && former.equals(latter)) { - return true; - } - if (latter != null && latter.equals(former)) { - return true; - } - return false; - } - - /** - * Determines if two objects objects are equal, except that null values are disallowed. - * - * @param former The former object. - * @param latter The latter object. - * @return Returns true only if both objects are not null and pass an equals test. - * - * @deprecated Use {@link NullUtils#equalsNotNull(Object, Object)} instead. - */ - @Deprecated - public static boolean equalsNotNull(Object former, Object latter) { - if (former == null || latter == null) { - return false; - } - if (former.equals(latter)) { - return true; - } - if (latter.equals(former)) { - return true; - } - return false; - } - -} diff --git a/src/test/java/vg/civcraft/mc/civmodcore/serialization/ExampleSerializable.java b/src/test/java/vg/civcraft/mc/civmodcore/serialization/ExampleSerializable.java index 2b9621ea..52a6d9cb 100644 --- a/src/test/java/vg/civcraft/mc/civmodcore/serialization/ExampleSerializable.java +++ b/src/test/java/vg/civcraft/mc/civmodcore/serialization/ExampleSerializable.java @@ -3,10 +3,12 @@ /** * Class to be used during testing as an example serializable. */ -public final class ExampleSerializable extends NBTCache { +public final class ExampleSerializable implements NBTSerializable { private static final String MESSAGE_KEY = "message"; + private final NBTCompound nbt = new NBTCompound(); + /** * Gets the message stored within the NBT directly. * @@ -25,4 +27,14 @@ public void setMessage(String message) { this.nbt.setString(MESSAGE_KEY, message); } + @Override + public void serialize(final NBTCompound nbt) { + nbt.adopt(this.nbt); + } + + @Override + public void deserialize(final NBTCompound nbt) { + this.nbt.adopt(nbt); + } + } diff --git a/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTester.java b/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTester.java index 1c945ea1..39240d2e 100644 --- a/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTester.java +++ b/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTester.java @@ -1,6 +1,5 @@ package vg.civcraft.mc.civmodcore.serialization; -import java.util.Objects; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; @@ -125,32 +124,4 @@ public void testNBTClearing() { Assert.assertNull(nbt.getString(STRING_KEY)); } - @Test - public void testListValues() { - // Setup - String LIST_KEY = "tester"; - ExampleSerializable expected = new ExampleSerializable(); - String expectedString = "Porttitor massa id neque aliquam. Libero enim sed faucibus turpis in eu mi. " + - "Dignissim sodales ut eu sem integer vitae justo. Adipiscing elit duis tristique sollicitudin " + - "nibh. Elit ullamcorper dignissim cras tincidunt lobortis feugiat. Viverra adipiscing at in " + - "tellus integer feugiat scelerisque varius morbi. Auctor augue mauris augue neque gravida. Sed " + - "viverra tellus in hac habitasse platea dictumst. Fermentum posuere urna nec tincidunt praesent " + - "semper. Tristique magna sit amet purus gravida. Orci eu lobortis elementum nibh tellus molestie " + - "nunc non. Tincidunt eget nullam non nisi est sit amet facilisis magna. Sit amet nisl suscipit " + - "adipiscing bibendum. Justo donec enim diam vulputate ut. Magna ac placerat vestibulum lectus " + - "mauris ultrices eros."; - expected.setMessage(expectedString); - NBTCompoundList list = new NBTCompoundList<>(); - list.add(expected); - // Process - NBTCompound beforeNBT = new NBTCompound(); - beforeNBT.setSerializableList(LIST_KEY, list); - byte[] data = NBTCompound.toBytes(beforeNBT); - NBTCompound afterNBT = NBTCompound.fromBytes(data); - // Check - Assert.assertNotNull(afterNBT); - Assert.assertEquals(expectedString, Objects.requireNonNull( - afterNBT.getSerializableList(LIST_KEY).get(0)).getMessage()); - } - } From 8d1374e9c912c14f92d02d61023d7ba64ae35c4a Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 8 Apr 2021 18:06:44 +0100 Subject: [PATCH 014/143] Give Maven compiler a version --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 7c9fb3d5..9239e8f6 100644 --- a/pom.xml +++ b/pom.xml @@ -20,6 +20,7 @@ org.apache.maven.plugins maven-compiler-plugin + 3.8.1 -proc:none From 22914d4459d20be5323c11104e594fc90d6ec1a1 Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 8 Apr 2021 18:07:23 +0100 Subject: [PATCH 015/143] Add CivLogger --- .../mc/civmodcore/util/CivLogger.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java b/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java new file mode 100644 index 00000000..f36f4822 --- /dev/null +++ b/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java @@ -0,0 +1,45 @@ +package vg.civcraft.mc.civmodcore.util; + +import com.google.common.base.Strings; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import org.bukkit.plugin.java.PluginClassLoader; + +public final class CivLogger extends Logger { + + private final String prefix; + + private CivLogger(final Logger logger, final String prefix) { + super(logger.getName(), logger.getResourceBundleName()); + setParent(logger); + this.prefix = prefix; + } + + @Override + public void log(final LogRecord record) { + if (!Strings.isNullOrEmpty(this.prefix)) { + record.setMessage("[" + this.prefix + "] " + record.getMessage()); + } + super.log(record); + } + + /** + * Creates a logger based on a given class. If the given class was loaded by a plugin, it will piggy back off that + * plugin's logger. + * + * @param clazz The class to base the logger on. + * @return Returns a new civ logger. + */ + public static CivLogger getLogger(final Class clazz) { + if (clazz == null) { + return new CivLogger(Logger.getLogger(CivLogger.class.getSimpleName()), null); + } + final ClassLoader classLoader = clazz.getClassLoader(); + if (!(classLoader instanceof PluginClassLoader)) { + return new CivLogger(Logger.getLogger(CivLogger.class.getSimpleName()), clazz.getSimpleName()); + } + final var plugin = ((PluginClassLoader) classLoader).getPlugin(); + return new CivLogger(plugin.getLogger(), clazz.getSimpleName()); + } + +} From 2a361e9dc370f9a49d3ba0a259f0ae120214ef55 Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 8 Apr 2021 23:21:29 +0100 Subject: [PATCH 016/143] Update ACivMod.getInstance() --- .../vg/civcraft/mc/civmodcore/ACivMod.java | 39 +++++++++++-------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/src/main/java/vg/civcraft/mc/civmodcore/ACivMod.java b/src/main/java/vg/civcraft/mc/civmodcore/ACivMod.java index d1410f56..d6cd8ac3 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/ACivMod.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/ACivMod.java @@ -8,6 +8,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Consumer; @@ -35,9 +36,7 @@ public abstract class ACivMod extends JavaPlugin { @Deprecated protected CommandHandler handle = null; - protected StandaloneCommandHandler newCommandHandler; - protected boolean useNewCommandHandler = true; @Override @@ -338,28 +337,36 @@ public static T getInstance(final Class clazz) { if (clazz == null) { return null; } + try { + return JavaPlugin.getPlugin(clazz); + } + catch (final IllegalArgumentException | IllegalStateException ignored) { } for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - if (clazz.isAssignableFrom(plugin.getClass())) { + if (clazz.equals(plugin.getClass())) { return (T) plugin; } } - try { - final Method method = clazz.getDeclaredMethod("getInstance"); - if (Modifier.isPublic(method.getModifiers()) - && Modifier.isStatic(method.getModifiers()) - && clazz.isAssignableFrom(method.getReturnType())) { - return (T) method.invoke(null); + for (final String methodName : Arrays.asList("getInstance", "getPlugin")) { + try { + final Method method = clazz.getDeclaredMethod(methodName); + if (Modifier.isPublic(method.getModifiers()) + && Modifier.isStatic(method.getModifiers()) + && clazz.isAssignableFrom(method.getReturnType())) { + return (T) method.invoke(null); + } } + catch (final Exception ignored) { } } - catch (final Exception ignored) { } - try { - final Field field = clazz.getField("instance"); - if (Modifier.isStatic(field.getModifiers()) - && clazz.isAssignableFrom(field.getType())) { - return (T) field.get(null); + for (final String fieldName : Arrays.asList("instance", "plugin")) { + try { + final Field field = clazz.getField(fieldName); + if (Modifier.isStatic(field.getModifiers()) + && clazz.isAssignableFrom(field.getType())) { + return (T) field.get(null); + } } + catch (final Exception ignored) { } } - catch (final Exception ignored) { } // Otherwise there's no instance of the plugin, or it's stored in an unusual way return null; } From 335513033a047bf70b457ba72f1efe37785d02d6 Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 8 Apr 2021 23:22:05 +0100 Subject: [PATCH 017/143] Tidy up CivModCorePlugin a lil' --- .../mc/civmodcore/CivModCorePlugin.java | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java index 8321dc59..b7935108 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java @@ -40,12 +40,9 @@ public final class CivModCorePlugin extends ACivMod { private static CivModCorePlugin instance; private GlobalChunkMetaManager chunkMetaManager; - private ManagedDatasource database; - private WorldIDManager worldIdManager; - - private AikarCommandManager manager; + private AikarCommandManager commands; @Override public void onEnable() { @@ -89,13 +86,10 @@ public void onEnable() { registerListener(new WorldTracker()); registerListener(ChunkOperationManager.INSTANCE); // Register commands - this.manager = new AikarCommandManager(this) { - @Override - public void registerCommands() { - registerCommand(new ConfigCommand()); - registerCommand(ChunkOperationManager.INSTANCE); - } - }; + this.commands = new AikarCommandManager(this, false); + this.commands.registerCommand(new ConfigCommand()); + this.commands.registerCommand(ChunkOperationManager.INSTANCE); + this.commands.init(); // Load APIs EnchantUtils.loadEnchantAbbreviations(this); ItemUtils.loadItemNames(this); @@ -131,9 +125,9 @@ public void onDisable() { PlayerSettingAPI.saveAll(); ConfigurationSerialization.unregisterClass(ManagedDatasource.class); NBTSerialization.clearAllRegistrations(); - if (this.manager != null) { - this.manager.reset(); - this.manager = null; + if (this.commands != null) { + this.commands.reset(); + this.commands = null; } super.onDisable(); } From 57a667121a6e6c0204c207bccd74402b14214fc0 Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 8 Apr 2021 23:22:24 +0100 Subject: [PATCH 018/143] Start using CivLogger --- .../mc/civmodcore/inventory/items/EnchantUtils.java | 12 +++++++----- .../mc/civmodcore/inventory/items/ItemUtils.java | 12 +++++++----- .../mc/civmodcore/inventory/items/MoreTags.java | 4 +++- .../mc/civmodcore/inventory/items/PotionUtils.java | 7 ++++--- .../mc/civmodcore/inventory/items/SpawnEggUtils.java | 5 +++-- .../mc/civmodcore/inventory/items/TreeTypeUtils.java | 7 ++++--- 6 files changed, 28 insertions(+), 19 deletions(-) diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/EnchantUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/EnchantUtils.java index 1f82abab..6162c4d9 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/EnchantUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/EnchantUtils.java @@ -19,6 +19,7 @@ import org.bukkit.inventory.meta.ItemMeta; import vg.civcraft.mc.civmodcore.CivModCorePlugin; import vg.civcraft.mc.civmodcore.util.Chainer; +import vg.civcraft.mc.civmodcore.util.CivLogger; import vg.civcraft.mc.civmodcore.util.KeyedUtils; /** @@ -96,34 +97,35 @@ public final class EnchantUtils { * Loads enchantment names and initials from the config. */ public static void loadEnchantAbbreviations(final CivModCorePlugin plugin) { + final var logger = CivLogger.getLogger(EnchantUtils.class); ENCHANT_ABBR.clear(); final File enchantsFile = plugin.getResourceFile("enchants.yml"); final YamlConfiguration enchantsConfig = YamlConfiguration.loadConfiguration(enchantsFile); for (final String key : enchantsConfig.getKeys(false)) { if (Strings.isNullOrEmpty(key)) { - plugin.warning("[EnchantUtils] Enchantment key was empty."); + logger.warning("Enchantment key was empty."); continue; } final Enchantment enchant = EnchantUtils.getEnchantment(key); if (enchant == null) { - plugin.warning("[EnchantUtils] Could not find enchantment: " + key); + logger.warning("Could not find enchantment: " + key); return; } final String abbreviation = enchantsConfig.getString(key); if (Strings.isNullOrEmpty(abbreviation)) { - plugin.warning("[EnchantUtils] Abbreviation for [" + key + "] was empty."); + logger.warning("Abbreviation for [" + key + "] was empty."); continue; } ENCHANT_ABBR.put(enchant, abbreviation); } - plugin.info("[EnchantUtils] Loaded a total of " + ENCHANT_ABBR.size() + " abbreviations from enchants.yml"); + logger.info("Loaded a total of " + ENCHANT_ABBR.size() + " abbreviations from enchants.yml"); // Determine if there's any enchants missing abbreviations final Set missing = new HashSet<>(); CollectionUtils.addAll(missing, Enchantment.values()); missing.removeIf(ENCHANT_ABBR::containsKey); if (!missing.isEmpty()) { //noinspection deprecation - plugin.warning("[EnchantUtils] The following enchants are missing from enchants.yml: " + + logger.warning("The following enchants are missing from enchants.yml: " + missing.stream().map(Enchantment::getName).collect(Collectors.joining(",")) + "."); } } diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java index 5f75a264..570c3730 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/ItemUtils.java @@ -19,6 +19,7 @@ import org.bukkit.inventory.meta.ItemMeta; import vg.civcraft.mc.civmodcore.CivModCorePlugin; import vg.civcraft.mc.civmodcore.chat.ChatUtils; +import vg.civcraft.mc.civmodcore.util.CivLogger; /** * Class of static APIs for Items. Replaces ISUtils. @@ -33,33 +34,34 @@ public final class ItemUtils { * @param plugin The CivModCore instance plugin. */ public static void loadItemNames(final CivModCorePlugin plugin) { + final var logger = CivLogger.getLogger(ItemUtils.class); MATERIAL_NAMES.clear(); final File materialsFile = plugin.getResourceFile("materials.yml"); final YamlConfiguration materialsConfig = YamlConfiguration.loadConfiguration(materialsFile); for (final String key : materialsConfig.getKeys(false)) { if (Strings.isNullOrEmpty(key)) { - plugin.warning("[ItemUtils] Material key was empty."); + logger.warning("Material key was empty."); continue; } final Material material = Material.getMaterial(key); if (material == null) { - plugin.warning("[ItemUtils] Could not find material: " + key); + logger.warning("Could not find material: " + key); return; } final String name = materialsConfig.getString(key); if (Strings.isNullOrEmpty(name)) { - plugin.warning("[ItemUtils] Name for [" + key + "] was empty."); + logger.warning("Name for [" + key + "] was empty."); continue; } MATERIAL_NAMES.put(material, ChatUtils.parseColor(name)); } - plugin.info("[ItemUtils] Loaded a total of " + MATERIAL_NAMES.size() + " item names from materials.yml"); + logger.info("Loaded a total of " + MATERIAL_NAMES.size() + " item names from materials.yml"); // Determine if there's any materials missing final Set missing = new HashSet<>(); CollectionUtils.addAll(missing, Material.values()); missing.removeIf(MATERIAL_NAMES::containsKey); if (!missing.isEmpty()) { - plugin.warning("[ItemUtils] The following materials are missing from materials.yml: " + + logger.warning("The following materials are missing from materials.yml: " + missing.stream().map(Enum::name).collect(Collectors.joining(",")) + "."); } } diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MoreTags.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MoreTags.java index 745041fe..5fd29988 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MoreTags.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/MoreTags.java @@ -14,6 +14,7 @@ import org.bukkit.NamespacedKey; import org.bukkit.Tag; import org.bukkit.block.data.Ageable; +import vg.civcraft.mc.civmodcore.util.CivLogger; import vg.civcraft.mc.civmodcore.util.KeyedUtils; /** @@ -216,6 +217,7 @@ public NamespacedKey getKey() { // ------------------------------------------------------------ public static void init() { + final var logger = CivLogger.getLogger(MoreTags.class); // Determine if there's any crops missing { final Set missing = new HashSet<>(); @@ -226,7 +228,7 @@ public static void init() { missing.removeIf(Tag.FIRE::isTagged); missing.removeIf(CROPS::isTagged); if (!missing.isEmpty()) { - Bukkit.getLogger().warning("[MoreTags] The following crops are missing: " + + logger.warning("The following crops are missing: " + missing.stream().map(Material::name).collect(Collectors.joining(",")) + "."); } } diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/PotionUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/PotionUtils.java index 3791f3bc..73173449 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/PotionUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/PotionUtils.java @@ -7,9 +7,9 @@ import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; -import org.bukkit.Bukkit; import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionType; +import vg.civcraft.mc.civmodcore.util.CivLogger; public final class PotionUtils { @@ -83,13 +83,14 @@ public final class PotionUtils { }}; public static void init() { + final var logger = CivLogger.getLogger(PotionUtils.class); // Determine if there's any missing potion types { final Set missing = new HashSet<>(); CollectionUtils.addAll(missing, PotionType.values()); missing.removeIf(POTIONS::containsKey); if (!missing.isEmpty()) { - Bukkit.getLogger().warning("[PotionUtils] The following potion types are missing: " + + logger.warning("The following potion types are missing: " + missing.stream().map(Enum::name).collect(Collectors.joining(",")) + "."); } } @@ -99,7 +100,7 @@ public static void init() { CollectionUtils.addAll(missing, PotionEffectType.values()); missing.removeIf(EFFECTS::containsKey); if (!missing.isEmpty()) { - Bukkit.getLogger().warning("[PotionUtils] The following potion effects are missing: " + + logger.warning("The following potion effects are missing: " + missing.stream().map(PotionEffectType::getName).collect(Collectors.joining(",")) + "."); } } diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/SpawnEggUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/SpawnEggUtils.java index 9689dd93..2d36ac45 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/SpawnEggUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/SpawnEggUtils.java @@ -7,9 +7,9 @@ import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.commons.collections4.CollectionUtils; -import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.EntityType; +import vg.civcraft.mc.civmodcore.util.CivLogger; /** * Class of static APIs for Spawn Eggs. @@ -84,12 +84,13 @@ public final class SpawnEggUtils { .build(); public static void init() { + final var logger = CivLogger.getLogger(SpawnEggUtils.class); // Determine if there's any enchants missing names final Set missing = new HashSet<>(); CollectionUtils.addAll(missing, Material.values()); missing.removeIf(material -> !material.name().endsWith("_SPAWN_EGG") || SPAWN_EGGS.containsKey(material)); if (!missing.isEmpty()) { - Bukkit.getLogger().warning("[SpawnEggUtils] The following spawn eggs are missing: " + + logger.warning("The following spawn eggs are missing: " + missing.stream().map(Enum::name).collect(Collectors.joining(",")) + "."); } } diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/TreeTypeUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/TreeTypeUtils.java index 2b6d1bab..ee93c0e3 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/TreeTypeUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/TreeTypeUtils.java @@ -6,9 +6,9 @@ import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; -import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.TreeType; +import vg.civcraft.mc.civmodcore.util.CivLogger; public final class TreeTypeUtils { @@ -109,6 +109,7 @@ public final class TreeTypeUtils { .build(); public static void init() { + final var logger = CivLogger.getLogger(TreeTypeUtils.class); // Determine if there's any tree types missing { final Set missing = new HashSet<>(); @@ -118,7 +119,7 @@ public static void init() { CollectionUtils.addAll(missing, TreeType.values()); missing.removeIf(type -> exclude.contains(type) || TREE_MATERIALS.containsValue(type)); if (!missing.isEmpty()) { - Bukkit.getLogger().warning("[TreeTypeUtils] The following tree types are missing: " + + logger.warning("The following tree types are missing: " + missing.stream().map(Enum::name).collect(Collectors.joining(",")) + "."); } } @@ -128,7 +129,7 @@ public static void init() { CollectionUtils.addAll(missing, TreeType.values()); missing.removeIf(SAPLING_MATERIALS::containsKey); if (!missing.isEmpty()) { - Bukkit.getLogger().warning("[TreeTypeUtils] The following sapling types are missing: " + + logger.warning("The following sapling types are missing: " + missing.stream().map(Enum::name).collect(Collectors.joining(",")) + "."); } } From 09e4194029c6e96674a421a22e9408a6355e00fc Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 9 Apr 2021 00:57:40 +0100 Subject: [PATCH 019/143] Move away from Chainer --- .../inventory/items/EnchantUtils.java | 8 +- .../civmodcore/util/MoreCollectionUtils.java | 5 +- .../civcraft/mc/civmodcore/util/TextUtil.java | 170 ++---------------- 3 files changed, 19 insertions(+), 164 deletions(-) diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/EnchantUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/EnchantUtils.java index 1f82abab..f8ad8d16 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/EnchantUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/items/EnchantUtils.java @@ -5,8 +5,8 @@ import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableBiMap; +import com.google.common.collect.ImmutableMap; import java.io.File; -import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -18,7 +18,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import vg.civcraft.mc.civmodcore.CivModCorePlugin; -import vg.civcraft.mc.civmodcore.util.Chainer; import vg.civcraft.mc.civmodcore.util.KeyedUtils; /** @@ -187,7 +186,10 @@ public static boolean isSafeEnchantment(final Enchantment enchantment, final int * @return Returns the item's enchantments, which are never null. */ public static Map getEnchantments(final ItemStack item) { - return Chainer.from(item).then(ItemStack::getEnchantments).getOrGenerate(HashMap::new); + if (item == null) { + return ImmutableMap.of(); + } + return item.getEnchantments(); } /** diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/MoreCollectionUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/util/MoreCollectionUtils.java index 093065f5..683f87e3 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/util/MoreCollectionUtils.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/util/MoreCollectionUtils.java @@ -26,7 +26,10 @@ public final class MoreCollectionUtils { */ @SafeVarargs public static > K collect(final Supplier constructor, final T... elements) { - final K collection = Chainer.from(constructor).then(Supplier::get).get(); + if (constructor == null) { + return null; + } + final K collection = constructor.get(); if (collection == null) { return null; } diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/TextUtil.java b/src/main/java/vg/civcraft/mc/civmodcore/util/TextUtil.java index 714ab4d8..e4af566a 100644 --- a/src/main/java/vg/civcraft/mc/civmodcore/util/TextUtil.java +++ b/src/main/java/vg/civcraft/mc/civmodcore/util/TextUtil.java @@ -1,13 +1,11 @@ package vg.civcraft.mc.civmodcore.util; import com.google.common.base.Preconditions; -import com.google.common.base.Strings; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.TextComponent; -import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.bukkit.ChatColor; import org.bukkit.entity.Player; @@ -62,10 +60,7 @@ public static String parse(String str) { */ @Deprecated public static String parseColor(String string) { - string = parseColorAmp(string); - string = parseColorAcc(string); - string = parseColorTags(string); - return string; + return ChatUtils.parseColor(string); } /** @@ -73,9 +68,7 @@ public static String parseColor(String string) { */ @Deprecated public static String parseColorAmp(String string) { - string = string.replace("&&", "&"); - string = string.replaceAll("&([a-zA-Z0-9])", "§$1"); - return string; + return ChatUtils.parseColorAmp(string); } /** @@ -83,39 +76,7 @@ public static String parseColorAmp(String string) { */ @Deprecated public static String parseColorAcc(String string) { - return string. - replace("`0", ChatColor.BLACK.toString()). - replace("`1", ChatColor.DARK_BLUE.toString()). - replace("`2", ChatColor.DARK_GREEN.toString()). - replace("`3", ChatColor.DARK_AQUA.toString()). - replace("`4", ChatColor.DARK_RED.toString()). - replace("`5", ChatColor.DARK_PURPLE.toString()). - replace("`6", ChatColor.GOLD.toString()). - replace("`7", ChatColor.GRAY.toString()). - replace("`8", ChatColor.DARK_GRAY.toString()). - replace("`9", ChatColor.BLUE.toString()). - replace("`A", ChatColor.GREEN.toString()). - replace("`a", ChatColor.GREEN.toString()). - replace("`B", ChatColor.AQUA.toString()). - replace("`b", ChatColor.AQUA.toString()). - replace("`C", ChatColor.RED.toString()). - replace("`c", ChatColor.RED.toString()). - replace("`D", ChatColor.LIGHT_PURPLE.toString()). - replace("`d", ChatColor.LIGHT_PURPLE.toString()). - replace("`E", ChatColor.YELLOW.toString()). - replace("`e", ChatColor.YELLOW.toString()). - replace("`F", ChatColor.WHITE.toString()). - replace("`f", ChatColor.WHITE.toString()). - replace("`L", ChatColor.BOLD.toString()). - replace("`l", ChatColor.BOLD.toString()). - replace("`M", ChatColor.STRIKETHROUGH.toString()). - replace("`m", ChatColor.STRIKETHROUGH.toString()). - replace("`N", ChatColor.UNDERLINE.toString()). - replace("`n", ChatColor.UNDERLINE.toString()). - replace("`O", ChatColor.ITALIC.toString()). - replace("`o", ChatColor.ITALIC.toString()). - replace("`R", ChatColor.RESET.toString()). - replace("`r", ChatColor.RESET.toString()); + return ChatUtils.parseColorAcc(string); } /** @@ -123,52 +84,7 @@ public static String parseColorAcc(String string) { */ @Deprecated public static String parseColorTags(String string) { - return string. - replace("", ChatColor.BLACK.toString()). - replace("", ChatColor.DARK_BLUE.toString()). - replace("", ChatColor.DARK_GREEN.toString()). - replace("", ChatColor.DARK_AQUA.toString()). - replace("", ChatColor.DARK_RED.toString()). - replace("", ChatColor.DARK_PURPLE.toString()). - replace("", ChatColor.GOLD.toString()). - replace("", ChatColor.GRAY.toString()). // This has to be lgray because gray is already claimed. - replace("", ChatColor.DARK_GRAY.toString()). - replace("", ChatColor.BLUE.toString()). - replace("", ChatColor.GREEN.toString()). - replace("", ChatColor.AQUA.toString()). - replace("", ChatColor.RED.toString()). - replace("", ChatColor.LIGHT_PURPLE.toString()). - replace("", ChatColor.YELLOW.toString()). - replace("", ChatColor.WHITE.toString()). - replace("", ChatColor.STRIKETHROUGH.toString()). - replace("", ChatColor.UNDERLINE.toString()). - replace("