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 extends Player> 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.paperpaper
- 1.16.4-R0.1-SNAPSHOT
+ 1.16.5-R0.1-SNAPSHOTprovided
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 extends Audience> 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;
-
-/**
- *
- *
- * @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.
- */
-@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.
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.
- *
- * @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.
- *
- * @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.
- *
- * @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.pluginsmaven-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("
+
+ net.kyori
+ adventure-text-minimessage
+ 4.1.0-SNAPSHOT
+ org.apache.commonscommons-lang3
@@ -79,7 +84,7 @@
junitjunit
- 4.13
+ 4.13.2test
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 34970602..63a820b9 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java
@@ -2,12 +2,15 @@
import com.google.common.base.Strings;
import java.awt.Color;
-import java.util.Arrays;
import java.util.List;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.minimessage.MiniMessage;
+import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.md_5.bungee.api.ChatColor;
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;
public final class ChatUtils {
@@ -152,28 +155,31 @@ public static String parseColorTags(String string) {
*
* @param component The component to test if null or empty.
* @return Returns true if the component is null or has no visible content.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
*/
+ @Deprecated
public static boolean isNullOrEmpty(final BaseComponent component) {
if (component == null) {
return true;
}
- final TextComponent text = fromLegacyText(component.toPlainText());
- return Strings.isNullOrEmpty(text.toPlainText());
+ return Strings.isNullOrEmpty(component.toPlainText());
}
/**
- *
Converts a string containing Minecraft's legacy colour codes into a text component.
+ *
Determines whether a given base component is null or empty.
*
- *
Note: This does not work on Civ's colour code equivalents, make sure to parse those before using this.
+ *
This is determined by converting the component into plain text, so a non-null component filled with
+ * nothing but colour codes and hover text will likely return true.
*
- * @param text The legacy text to parse.
- * @return Returns a text component of the legacy text.
+ * @param component The component to test if null or empty.
+ * @return Returns true if the component is null or has no visible content.
*/
- public static TextComponent fromLegacyText(final String text) {
- if (Strings.isNullOrEmpty(text)) {
- return new TextComponent(text);
+ public static boolean isNullOrEmpty(final Component component) {
+ if (component == null) {
+ return true;
}
- return new TextComponent(TextComponent.fromLegacyText(text, ChatColor.RESET));
+ return Strings.isNullOrEmpty(LegacyComponentSerializer.legacyAmpersand().serialize(component));
}
/**
@@ -182,7 +188,10 @@ public static TextComponent fromLegacyText(final String text) {
* @param value The value of the text. (Objects will be stringified)
* @param formats The colour formats.
* @return Returns the created component, so you can do more stuff to it.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure. Use {@link Component#text()} instead.
*/
+ @Deprecated
public static TextComponent textComponent(final Object value, final ChatColor... formats) {
final TextComponent component = new TextComponent(value == null ? "" : value.toString());
if (!ArrayUtils.isEmpty(formats)) {
@@ -221,50 +230,18 @@ 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;
+ public static boolean areComponentsEqual(final Component former, final Component latter) {
+ if (StringUtils.equals(
+ MiniMessage.get().serialize(former),
+ MiniMessage.get().serialize(latter))) {
+ return true;
}
- 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;
+ if (StringUtils.equals(
+ LegacyComponentSerializer.legacyAmpersand().serialize(former),
+ LegacyComponentSerializer.legacyAmpersand().serialize(latter))) {
+ return true;
}
- return new TextComponent(components);
- }
-
- public static boolean areComponentsEqual(final TextComponent former, final TextComponent latter) {
- return Arrays.equals(
- toBaseComponents(former),
- toBaseComponents(latter));
+ return false;
}
}
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 570c3730..e4628c11 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
@@ -10,7 +10,7 @@
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
-import net.md_5.bungee.api.chat.TextComponent;
+import net.kyori.adventure.text.Component;
import org.apache.commons.collections4.CollectionUtils;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
@@ -230,48 +230,12 @@ public static boolean hasDisplayName(final ItemStack item) {
* @param item The item to retrieve the display name from.
* @return Returns the display name of an item.
*/
- public static String getDisplayName(final ItemStack item) {
- 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) {
+ public static Component getComponentDisplayName(final ItemStack item) {
final var meta = getItemMeta(item);
if (meta == null) {
return null;
}
- return MetaUtils.getComponentDisplayName(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 setDisplayName(final ItemStack item, final String name) {
- final var meta = getItemMeta(item);
- if (meta == null) {
- throw new IllegalArgumentException("Cannot set that display name: item has no meta.");
- }
- if (Strings.isNullOrEmpty(name)) {
- meta.setDisplayName(null);
- }
- else {
- meta.setDisplayName(name);
- }
- item.setItemMeta(meta);
+ return meta.displayName();
}
/**
@@ -282,29 +246,15 @@ public static void setDisplayName(final ItemStack item, final String name) {
*
* @throws IllegalArgumentException Throws when the given item has no meta.
*/
- public static void setComponentDisplayName(final ItemStack item, final TextComponent name) {
+ public static void setComponentDisplayName(final ItemStack item, final Component 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);
+ meta.displayName(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.
- */
- public static List getLore(final ItemStack item) {
- final var meta = getItemMeta(item);
- if (meta == null) {
- return new ArrayList<>();
- }
- return MetaUtils.getLore(meta);
- }
-
/**
* Retrieves the lore from an item.
*
@@ -312,10 +262,10 @@ public static List getLore(final ItemStack item) {
* @return Returns the lore, which is never null.
*/
@Nonnull
- public static List getComponentLore(final ItemStack item) {
+ public static List getComponentLore(final ItemStack item) {
final var meta = getItemMeta(item);
if (meta == null) {
- return new ArrayList<>();
+ return new ArrayList<>(0);
}
return MetaUtils.getComponentLore(meta);
}
@@ -330,42 +280,7 @@ public static List getComponentLore(final ItemStack item) {
*
* @throws IllegalArgumentException Throws when the given item has no meta.
*/
- public static void setLore(final ItemStack item, final String... lines) {
- final List lore = new ArrayList<>();
- CollectionUtils.addAll(lore, lines);
- setLore(item, 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 ItemUtils#clearLore(ItemStack)
- *
- * @throws IllegalArgumentException Throws when the given item has no meta.
- */
- public static void setLore(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.");
- }
- meta.setLore(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) {
+ public static void setComponentLore(final ItemStack item, final Component... lines) {
final var meta = getItemMeta(item);
if (meta == null) {
throw new IllegalArgumentException("Cannot set that lore: item has no meta.");
@@ -384,7 +299,7 @@ public static void setComponentLore(final ItemStack item, final TextComponent...
*
* @throws IllegalArgumentException Throws when the given item has no meta.
*/
- public static void setComponentLore(final ItemStack item, final List lines) {
+ 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.");
@@ -393,66 +308,6 @@ public static void setComponentLore(final ItemStack item, final 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.
- *
- * @throws IllegalArgumentException Throws when the given item has no meta.
- */
- public static void addLore(final ItemStack item, final boolean prepend, final String... lines) {
- 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);
- }
-
- /**
- * 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 addLore(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.addLore(meta, prepend, lines);
- item.setItemMeta(meta);
- }
-
/**
* Clears the lore from an item.
*
@@ -472,7 +327,7 @@ public static void clearLore(final ItemStack item) {
*
* @throws IllegalArgumentException Throws when the given item has no meta.
*/
- public static void addComponentLore(final ItemStack item, final TextComponent... lines) {
+ public static void addComponentLore(final ItemStack item, final Component... lines) {
addComponentLore(item, false, lines);
}
@@ -484,7 +339,7 @@ public static void addComponentLore(final ItemStack item, final TextComponent...
*
* @throws IllegalArgumentException Throws when the given item has no meta.
*/
- public static void addComponentLore(final ItemStack item, final List lines) {
+ public static void addComponentLore(final ItemStack item, final List lines) {
addComponentLore(item, false, lines);
}
@@ -499,7 +354,7 @@ public static void addComponentLore(final ItemStack item, final List lines) {
+ final List lines) {
final var meta = getItemMeta(item);
if (meta == null) {
throw new IllegalArgumentException("Cannot add that lore: item has no meta.");
@@ -596,4 +451,184 @@ public static boolean handleItemMeta(final ItemStack item, final Predicate getLore(final ItemStack item) {
+ final var meta = getItemMeta(item);
+ if (meta == null) {
+ return new ArrayList<>(0);
+ }
+ return MetaUtils.getLore(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.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
+ * Use {@link #setComponentLore(ItemStack, Component...)} instead.
+ */
+ @Deprecated
+ public static void setLore(final ItemStack item, final String... lines) {
+ final List lore = new ArrayList<>();
+ CollectionUtils.addAll(lore, lines);
+ setLore(item, 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 ItemUtils#clearLore(ItemStack)
+ *
+ * @throws IllegalArgumentException Throws when the given item has no meta.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
+ * Use {@link #setComponentLore(ItemStack, List)} instead.
+ */
+ @Deprecated
+ public static void setLore(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.");
+ }
+ 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.
+ *
+ * @throws IllegalArgumentException Throws when the given item has no meta.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
+ * Use {@link #addComponentLore(ItemStack, Component...)} instead.
+ */
+ @Deprecated
+ public static void addLore(final ItemStack item, final String... lines) {
+ addLore(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.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
+ * Use {@link #addComponentLore(ItemStack, List)} instead.
+ */
+ @Deprecated
+ public static void addLore(final ItemStack item, final 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.
+ *
+ * @throws IllegalArgumentException Throws when the given item has no meta.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
+ * Use {@link #addComponentLore(ItemStack, boolean, Component...)} instead.
+ */
+ @Deprecated
+ public static void addLore(final ItemStack item, final boolean prepend, final String... lines) {
+ 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);
+ }
+
+ /**
+ * 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.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
+ * Use {@link #addComponentLore(ItemStack, boolean, List)} instead.
+ */
+ @Deprecated
+ public static void addLore(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.addLore(meta, prepend, lines);
+ item.setItemMeta(meta);
+ }
+
}
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 228392d4..c1a64f84 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,15 +1,13 @@
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.Objects;
import java.util.function.Predicate;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
import javax.annotation.Nonnull;
-import net.md_5.bungee.api.chat.BaseComponent;
-import net.md_5.bungee.api.chat.TextComponent;
+import net.kyori.adventure.text.Component;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.bukkit.Bukkit;
@@ -43,10 +41,10 @@ public static boolean areMetasEqual(final ItemMeta former, final ItemMeta latter
// 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);
+ fakeFormer.displayName(null);
+ fakeFormer.lore(null);
+ fakeLatter.displayName(null);
+ fakeLatter.lore(null);
if (!Bukkit.getItemFactory().equals(fakeFormer, fakeLatter)) {
return false;
}
@@ -56,8 +54,8 @@ public static boolean areMetasEqual(final ItemMeta former, final ItemMeta latter
}
if (former.hasDisplayName()) {
if (!ChatUtils.areComponentsEqual(
- getComponentDisplayName(former),
- getComponentDisplayName(latter))) {
+ former.displayName(),
+ latter.displayName())) {
return false;
}
}
@@ -74,45 +72,6 @@ public static boolean areMetasEqual(final ItemMeta former, final ItemMeta latter
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.
- *
- * @param meta The item meta to retrieve the lore from.
- * @return Returns the lore, which is never null.
- */
- @Nonnull
- public static List getLore(@Nonnull final ItemMeta meta) {
- final List lore = meta.getLore();
- if (lore == null) {
- return new ArrayList<>();
- }
- return lore;
- }
-
-
/**
* Retrieves the lore from a given item meta.
*
@@ -120,14 +79,12 @@ public static List getLore(@Nonnull final ItemMeta meta) {
* @return Returns the lore, which is never null.
*/
@Nonnull
- public static List getComponentLore(@Nonnull final ItemMeta meta) {
- final List lore = meta.getLoreComponents();
+ public static List getComponentLore(@Nonnull final ItemMeta meta) {
+ final List lore = meta.lore();
if (CollectionUtils.isEmpty(lore)) {
- return new ArrayList<>();
+ return new ArrayList<>(0);
}
- return lore.stream()
- .map(ChatUtils::fromBaseComponents)
- .collect(Collectors.toCollection(ArrayList::new));
+ return lore;
}
/**
@@ -136,14 +93,12 @@ public static List getComponentLore(@Nonnull final ItemMeta 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 TextComponent... lines) {
+ public static void setComponentLore(@Nonnull final ItemMeta meta, final Component... lines) {
if (ArrayUtils.isEmpty(lines)) {
- meta.setLore(null);
+ meta.lore(null);
return;
}
- meta.setLoreComponents(Stream.of(lines)
- .map(ChatUtils::toBaseComponents)
- .collect(Collectors.toList()));
+ meta.lore(Arrays.asList(lines));
}
/**
@@ -152,14 +107,21 @@ public static void setComponentLore(@Nonnull final ItemMeta meta, final TextComp
* @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) {
+ public static void setComponentLore(@Nonnull final ItemMeta meta, final List lines) {
if (CollectionUtils.isEmpty(lines)) {
- meta.setLore(null);
+ meta.lore(null);
return;
}
- meta.setLoreComponents(lines.stream()
- .map(ChatUtils::toBaseComponents)
- .collect(Collectors.toList()));
+ meta.lore(lines);
+ }
+
+ /**
+ * Clears the lore from an item meta.
+ *
+ * @param meta The item meta to clear the lore of.
+ */
+ public static void clearLore(@Nonnull final ItemMeta meta) {
+ meta.lore(null);
}
/**
@@ -168,8 +130,8 @@ public static void setComponentLore(@Nonnull final ItemMeta meta, final List lines) {
- addLore(meta, false, lines);
+ public static void addComponentLore(@Nonnull final ItemMeta meta, final List lines) {
+ addComponentLore(meta, false, lines);
}
/**
@@ -189,21 +151,23 @@ public static void addLore(@Nonnull final ItemMeta meta, final List line
* @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 addLore(@Nonnull final ItemMeta meta, final boolean prepend, final String... lines) {
+ public static void addComponentLore(@Nonnull final ItemMeta meta,
+ final boolean prepend,
+ final Component... lines) {
if (ArrayUtils.isEmpty(lines)) {
return;
}
- final List lore = getLore(meta);
+ final List lore = getComponentLore(meta);
if (prepend) {
ArrayUtils.reverse(lines);
- for (final String line : lines) {
+ for (final Component line : lines) {
lore.add(0, line);
}
}
else {
CollectionUtils.addAll(lore, lines);
}
- meta.setLore(lore);
+ setComponentLore(meta, lore);
}
/**
@@ -213,30 +177,58 @@ public static void addLore(@Nonnull final ItemMeta meta, final boolean prepend,
* @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 addLore(@Nonnull final ItemMeta meta, final boolean prepend, final List lines) {
+ public static void addComponentLore(@Nonnull final ItemMeta meta,
+ final boolean prepend,
+ final List lines) {
if (CollectionUtils.isEmpty(lines)) {
return;
}
- final List lore = getLore(meta);
+ final List lore = getComponentLore(meta);
if (prepend) {
Collections.reverse(lines);
- for (final String line : lines) {
+ for (final Component line : lines) {
lore.add(0, line);
}
}
else {
lore.addAll(lines);
}
- meta.setLore(lore);
+ setComponentLore(meta, lore);
}
/**
- * Clears the lore from an item meta.
+ * 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 meta The item meta to clear the lore of.
+ * @param meta Item meta to apply glow to.
*/
- public static void clearLore(@Nonnull final ItemMeta meta) {
- meta.setLore(null);
+ public static void addGlow(@Nonnull final ItemMeta meta) {
+ meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
+ meta.addEnchant(Enchantment.DURABILITY, 1, true); // true = ignoreLevelRestriction
+ }
+
+ // ------------------------------------------------------------
+ // Deprecated Functions
+ // ------------------------------------------------------------
+
+ /**
+ * 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.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
+ * Use {@link #getComponentLore(ItemMeta)} instead.
+ */
+ @Deprecated
+ @Nonnull
+ public static List getLore(@Nonnull final ItemMeta meta) {
+ final List lore = meta.getLore();
+ if (lore == null) {
+ return new ArrayList<>(0);
+ }
+ return lore;
}
/**
@@ -244,9 +236,13 @@ public static void clearLore(@Nonnull final ItemMeta meta) {
*
* @param meta The item meta to append the lore to.
* @param lines The lore to append to the item meta.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
+ * Use {@link #addComponentLore(ItemMeta, Component...)} instead.
*/
- public static void addComponentLore(@Nonnull final ItemMeta meta, final TextComponent... lines) {
- addComponentLore(meta, false, lines);
+ @Deprecated
+ public static void addLore(@Nonnull final ItemMeta meta, final String... lines) {
+ addLore(meta, false, lines);
}
/**
@@ -254,9 +250,13 @@ public static void addComponentLore(@Nonnull final ItemMeta meta, final TextComp
*
* @param meta The item meta to append the lore to.
* @param lines The lore to append to the item meta.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
+ * Use {@link #addComponentLore(ItemMeta, List)} instead.
*/
- public static void addComponentLore(@Nonnull final ItemMeta meta, final List lines) {
- addComponentLore(meta, false, lines);
+ @Deprecated
+ public static void addLore(@Nonnull final ItemMeta meta, final List lines) {
+ addLore(meta, false, lines);
}
/**
@@ -265,24 +265,26 @@ public static void addComponentLore(@Nonnull final ItemMeta meta, final List lore = getComponentLore(meta);
+ final List lore = getLore(meta);
if (prepend) {
ArrayUtils.reverse(lines);
- for (final TextComponent line : lines) {
+ for (final String line : lines) {
lore.add(0, line);
}
}
else {
CollectionUtils.addAll(lore, lines);
}
- setComponentLore(meta, lore);
+ meta.setLore(lore);
}
/**
@@ -291,36 +293,26 @@ public static void addComponentLore(@Nonnull final ItemMeta meta,
* @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.
+ *
+ * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
+ * Use {@link #addComponentLore(ItemMeta, boolean, List)} instead.
*/
- public static void addComponentLore(@Nonnull final ItemMeta meta,
- final boolean prepend,
- final List lines) {
+ @Deprecated
+ public static void addLore(@Nonnull final ItemMeta meta, final boolean prepend, final List lines) {
if (CollectionUtils.isEmpty(lines)) {
return;
}
- final List lore = getComponentLore(meta);
+ final List lore = getLore(meta);
if (prepend) {
Collections.reverse(lines);
- for (final TextComponent line : lines) {
+ for (final String 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
- * does actually apply an enchantment to an item.
- *
- * @param meta Item meta to apply glow to.
- */
- public static void addGlow(@Nonnull final ItemMeta meta) {
- meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
- meta.addEnchant(Enchantment.DURABILITY, 1, true); // true = ignoreLevelRestriction
+ meta.setLore(lore);
}
}
diff --git a/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java b/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTests.java
similarity index 57%
rename from src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java
rename to src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTests.java
index da2e60a0..10bf6cac 100644
--- a/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTester.java
+++ b/src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTests.java
@@ -1,10 +1,9 @@
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 net.kyori.adventure.text.Component;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
+import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.pseudo.PseudoServer;
import org.junit.Assert;
import org.junit.BeforeClass;
@@ -14,7 +13,7 @@
import vg.civcraft.mc.civmodcore.serialization.NBTCompound;
import vg.civcraft.mc.civmodcore.util.NullUtils;
-public class ItemMetaTester {
+public class ItemMetaTests {
private static final ItemStack TEMPLATE_ITEM = new ItemStack(Material.STICK);
@@ -23,21 +22,6 @@ public static void setupBukkit() {
PseudoServer.setup();
}
- /**
- * Tests whether two components of different order can match.
- */
- @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);
- }
-
/**
* Tests whether a primitive display name can match with a component.
*/
@@ -50,7 +34,7 @@ public void testBasicDisplayNameEquality() {
nbt.setCompound("display", display);
}));
final var latterItem = TEMPLATE_ITEM.clone();
- ItemUtils.setDisplayName(latterItem, "Hello!");
+ ItemUtils.setComponentDisplayName(latterItem, Component.text("Hello!"));
// Check
Assert.assertTrue(ChatUtils.areComponentsEqual(
ItemUtils.getComponentDisplayName(formerItem),
@@ -61,29 +45,20 @@ public void testBasicDisplayNameEquality() {
* How do different API methods of setting the display name fare?
*/
@Test
+ @SuppressWarnings("deprecation")
public void testAdvancedDisplayNameEquality() {
// Setup
final var formerItem = TEMPLATE_ITEM.clone();
- ItemUtils.setDisplayName(formerItem, "Hello!");
+ ItemUtils.handleItemMeta(formerItem, (ItemMeta meta) -> {
+ meta.setDisplayName("Hello!");
+ return true;
+ });
final var latterItem = TEMPLATE_ITEM.clone();
- ItemUtils.setComponentDisplayName(latterItem, new TextComponent("Hello!"));
+ ItemUtils.setComponentDisplayName(latterItem, Component.text("Hello!"));
// Check
Assert.assertTrue(ChatUtils.areComponentsEqual(
ItemUtils.getComponentDisplayName(formerItem),
ItemUtils.getComponentDisplayName(latterItem)));
- }
-
- /**
- * Tries a full item similarity check.
- */
- @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/SerializationTester.java b/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTests.java
similarity index 99%
rename from src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTester.java
rename to src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTests.java
index 1c945ea1..1f888cbf 100644
--- a/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTester.java
+++ b/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTests.java
@@ -7,7 +7,7 @@
import org.junit.Test;
import vg.civcraft.mc.civmodcore.util.Validation;
-public class SerializationTester {
+public class SerializationTests {
@BeforeClass
public static void beforeAll() {
diff --git a/src/test/java/vg/civcraft/mc/civmodcore/text/TextTests.java b/src/test/java/vg/civcraft/mc/civmodcore/text/TextTests.java
new file mode 100644
index 00000000..3aa40ad6
--- /dev/null
+++ b/src/test/java/vg/civcraft/mc/civmodcore/text/TextTests.java
@@ -0,0 +1,40 @@
+package vg.civcraft.mc.civmodcore.text;
+
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.format.NamedTextColor;
+import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
+import org.junit.Assert;
+import org.junit.Test;
+import vg.civcraft.mc.civmodcore.chat.ChatUtils;
+
+public class TextTests {
+
+ /**
+ * Tests whether two components of different order can match.
+ */
+ @Test
+ public void testComponentOrderEquality() {
+ // Setup
+ final String formerMessage = "{\"text\":\"\",\"extra\":[{\"text\":\"Test!\"}]}";
+ final String latterMessage = "{\"extra\":[{\"text\":\"Test!\"}],\"text\":\"\"}";
+ // Process
+ final Component formerParsed = GsonComponentSerializer.gson().deserialize(formerMessage);
+ final Component latterParsed = GsonComponentSerializer.gson().deserialize(latterMessage);
+ // Check
+ Assert.assertEquals(formerParsed, latterParsed);
+ }
+
+ /**
+ * Tests whether two components of different arrangement but equal content can match.
+ */
+ @Test
+ public void testComponentArrangementEquality() {
+ // Setup
+ final Component formerComponent = Component.text("Test").color(NamedTextColor.RED);
+ final Component latterComponent = Component.text().color(NamedTextColor.RED)
+ .append(Component.text("Test")).build();
+ // Check
+ Assert.assertTrue(ChatUtils.areComponentsEqual(formerComponent, latterComponent));
+ }
+
+}
From dd98b5118cc72a661e19feaebcfb82ec72935793 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Fri, 9 Apr 2021 14:18:17 +0100
Subject: [PATCH 022/143] Rename UuidTester to actually work
Apparently test classes have to be suffixed with "Tests"
---
.../mc/civmodcore/uuid/{UuidTester.java => UuidTests.java} | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
rename src/test/java/vg/civcraft/mc/civmodcore/uuid/{UuidTester.java => UuidTests.java} (94%)
diff --git a/src/test/java/vg/civcraft/mc/civmodcore/uuid/UuidTester.java b/src/test/java/vg/civcraft/mc/civmodcore/uuid/UuidTests.java
similarity index 94%
rename from src/test/java/vg/civcraft/mc/civmodcore/uuid/UuidTester.java
rename to src/test/java/vg/civcraft/mc/civmodcore/uuid/UuidTests.java
index 33e647e0..8f3cb16b 100644
--- a/src/test/java/vg/civcraft/mc/civmodcore/uuid/UuidTester.java
+++ b/src/test/java/vg/civcraft/mc/civmodcore/uuid/UuidTests.java
@@ -5,7 +5,7 @@
import org.junit.Test;
import vg.civcraft.mc.civmodcore.util.UuidUtils;
-public class UuidTester {
+public class UuidTests {
@Test
public void testUuidSerialization() {
From 897de5e907e9551631d4dc88c1eb7b23086146e9 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Fri, 9 Apr 2021 14:19:32 +0100
Subject: [PATCH 023/143] Make these ArrayLists empty
---
.../vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java | 2 +-
.../civmodcore/playersettings/impl/collection/ListSetting.java | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java
index 094adfe7..4b4de3fe 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java
@@ -38,7 +38,7 @@ public static boolean isValidInventory(final Inventory inventory) {
*/
public static List getViewingPlayers(final Inventory inventory) {
if (!isValidInventory(inventory)) {
- return new ArrayList<>();
+ return new ArrayList<>(0);
}
return inventory.getViewers().stream()
.filter(entity -> entity instanceof Player)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/collection/ListSetting.java b/src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/collection/ListSetting.java
index 7730c0fd..9eb201c1 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/collection/ListSetting.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/collection/ListSetting.java
@@ -11,7 +11,7 @@ public ListSetting(JavaPlugin owningPlugin, List defaultValue, String name, S
String description, Class elementClass) {
super(owningPlugin, defaultValue, name, identifier, gui, description, elementClass, (c) -> {
if (c == null) {
- return new ArrayList<>();
+ return new ArrayList<>(0);
}
return new ArrayList<>(c);
});
From 11889a31c410a9da5576ab871f7d3437a091534a Mon Sep 17 00:00:00 2001
From: Alexander
Date: Fri, 9 Apr 2021 14:21:26 +0100
Subject: [PATCH 024/143] Re-arrange repositories
---
pom.xml | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/pom.xml b/pom.xml
index 6b067c91..b1b76b19 100644
--- a/pom.xml
+++ b/pom.xml
@@ -90,14 +90,14 @@
-
- aikar
- https://repo.aikar.co/content/groups/aikar/
- civ-github-repohttps://raw.githubusercontent.com/CivClassic/artifacts/master/
+
+ aikar
+ https://repo.aikar.co/content/groups/aikar/
+
From 9400d42afebc98512f4b0768e5618371d7ab7821 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 19 Apr 2021 10:13:12 +0100
Subject: [PATCH 025/143] Update WorldUtils.isWithinBounds() to use new lower
bound method
---
src/main/java/vg/civcraft/mc/civmodcore/world/WorldUtils.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/world/WorldUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/world/WorldUtils.java
index 4cb2801c..68f5db6f 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/world/WorldUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/world/WorldUtils.java
@@ -150,7 +150,7 @@ public static boolean isWithinBounds(final Location location) {
if (world == null) {
return false;
}
- return location.getY() >= 0 && location.getY() < world.getMaxHeight();
+ return location.getY() >= world.getMinHeight() && location.getY() < world.getMaxHeight();
}
From 4e7cd412dee973b0222e4ba65e9c829ae35b7451 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 19 Apr 2021 10:15:23 +0100
Subject: [PATCH 026/143] Fix CivLogger issue if the logger detects a plugin
but the plugin is not enabled yet
---
.../mc/civmodcore/util/CivLogger.java | 24 ++++++++++++-------
1 file changed, 16 insertions(+), 8 deletions(-)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java b/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
index f36f4822..83852f6a 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
@@ -3,6 +3,8 @@
import com.google.common.base.Strings;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
+import javax.annotation.Nonnull;
+import org.apache.commons.lang3.reflect.FieldUtils;
import org.bukkit.plugin.java.PluginClassLoader;
public final class CivLogger extends Logger {
@@ -30,16 +32,22 @@ public void log(final LogRecord record) {
* @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);
- }
+ public static CivLogger getLogger(@Nonnull final Class> clazz) {
final ClassLoader classLoader = clazz.getClassLoader();
- if (!(classLoader instanceof PluginClassLoader)) {
- return new CivLogger(Logger.getLogger(CivLogger.class.getSimpleName()), clazz.getSimpleName());
+ if (classLoader instanceof PluginClassLoader) {
+ final var plugin = ((PluginClassLoader) classLoader).getPlugin();
+ if (plugin != null) {
+ return new CivLogger(plugin.getLogger(), clazz.getSimpleName());
+ }
+ // Plugin has been constructed but not initialised yet
+ final var loaderLoggerField = FieldUtils.getDeclaredField(PluginClassLoader.class, "logger", true);
+ try {
+ final var loaderLogger = (Logger) loaderLoggerField.get(classLoader);
+ return new CivLogger(loaderLogger, clazz.getSimpleName());
+ }
+ catch (final IllegalAccessException ignored) {}
}
- final var plugin = ((PluginClassLoader) classLoader).getPlugin();
- return new CivLogger(plugin.getLogger(), clazz.getSimpleName());
+ return new CivLogger(Logger.getLogger(CivLogger.class.getSimpleName()), clazz.getSimpleName());
}
}
From f6f6e6b86dac5e4fbc551ed0f90ad017bafad9b2 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 19 Apr 2021 10:16:06 +0100
Subject: [PATCH 027/143] Add NBTHelper for common serialisations
---
.../civmodcore/serialization/NBTHelper.java | 74 +++++++++++++++++++
1 file changed, 74 insertions(+)
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java
new file mode 100644
index 00000000..5ee8ddcc
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java
@@ -0,0 +1,74 @@
+package vg.civcraft.mc.civmodcore.serialization;
+
+import java.util.UUID;
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftItemStack;
+import org.bukkit.inventory.ItemStack;
+
+public final class NBTHelper {
+
+ // ------------------------------------------------------------
+ // Location
+ // ------------------------------------------------------------
+
+ private static final String LOCATION_WORLD_KEY = "world";
+ private static final String LOCATION_X_KEY = "x";
+ private static final String LOCATION_Y_KEY = "y";
+ private static final String LOCATION_Z_KEY = "z";
+ private static final String LOCATION_YAW_KEY = "yaw";
+ private static final String LOCATION_PITCH_KEY = "pitch";
+
+ public static Location locationFromNBT(final NBTCompound nbt) {
+ if (nbt == null) {
+ return null;
+ }
+ final UUID worldUUID = nbt.getUUID(LOCATION_WORLD_KEY);
+ return new Location(
+ worldUUID == null ? null : Bukkit.getWorld(worldUUID),
+ nbt.getDouble(LOCATION_X_KEY),
+ nbt.getDouble(LOCATION_Y_KEY),
+ nbt.getDouble(LOCATION_Z_KEY),
+ nbt.getFloat(LOCATION_YAW_KEY),
+ nbt.getFloat(LOCATION_PITCH_KEY));
+ }
+
+ public static NBTCompound locationToNBT(final Location location) {
+ if (location == null) {
+ return null;
+ }
+ final var nbt = new NBTCompound();
+ nbt.setUUID(LOCATION_WORLD_KEY, location.isWorldLoaded() ? location.getWorld().getUID() : null);
+ nbt.setDouble(LOCATION_X_KEY, location.getX());
+ nbt.setDouble(LOCATION_Y_KEY, location.getY());
+ nbt.setDouble(LOCATION_Z_KEY, location.getZ());
+ if (location.getYaw() != 0) {
+ nbt.setFloat(LOCATION_YAW_KEY, location.getYaw());
+ }
+ if (location.getPitch() != 0) {
+ nbt.setFloat(LOCATION_PITCH_KEY, location.getPitch());
+ }
+ return nbt;
+ }
+
+ // ------------------------------------------------------------
+ // ItemStack
+ // ------------------------------------------------------------
+
+ public static ItemStack itemStackFromNBT(final NBTCompound nbt) {
+ if (nbt == null) {
+ return null;
+ }
+ return net.minecraft.server.v1_16_R3.ItemStack.fromCompound(nbt.getRAW()).getBukkitStack();
+ }
+
+ public static NBTCompound itemStackToNBT(final ItemStack item) {
+ if (item == null) {
+ return null;
+ }
+ final var nbt = new NBTCompound();
+ ((CraftItemStack) item).getHandle().save(nbt.getRAW());
+ return nbt;
+ }
+
+}
From 4dfee78404cc3fc7ea340ce41405ca77266df804 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 19 Apr 2021 10:16:50 +0100
Subject: [PATCH 028/143] Update Aikar commands
---
.../mc/civmodcore/CivModCorePlugin.java | 3 +-
.../command/AikarCommandManager.java | 53 +++++++++----------
2 files changed, 25 insertions(+), 31 deletions(-)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
index b7935108..8f9dc2c9 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
@@ -86,10 +86,9 @@ public void onEnable() {
registerListener(new WorldTracker());
registerListener(ChunkOperationManager.INSTANCE);
// Register commands
- this.commands = new AikarCommandManager(this, false);
+ this.commands = new AikarCommandManager(this);
this.commands.registerCommand(new ConfigCommand());
this.commands.registerCommand(ChunkOperationManager.INSTANCE);
- this.commands.init();
// Load APIs
EnchantUtils.loadEnchantAbbreviations(this);
ItemUtils.loadItemNames(this);
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/command/AikarCommandManager.java b/src/main/java/vg/civcraft/mc/civmodcore/command/AikarCommandManager.java
index 27890ad4..cb70637f 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/command/AikarCommandManager.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/command/AikarCommandManager.java
@@ -35,7 +35,6 @@
public class AikarCommandManager {
private final ACivMod plugin;
-
private CustomBukkitManager manager;
/**
@@ -43,7 +42,7 @@ public class AikarCommandManager {
*
* @param plugin The plugin to bind this manager to.
*/
- public AikarCommandManager(ACivMod plugin) {
+ public AikarCommandManager(final ACivMod plugin) {
this(plugin, true);
}
@@ -55,25 +54,17 @@ public AikarCommandManager(ACivMod plugin) {
* {@link AikarCommandManager#registerCommands()} and
* {@link AikarCommandManager#registerCompletions(CommandCompletions)}.
*/
- public AikarCommandManager(ACivMod plugin, boolean autoInit) {
+ public AikarCommandManager(final ACivMod plugin, final boolean autoInit) {
this.plugin = plugin;
if (autoInit) {
init();
}
}
- /**
- * @deprecated Use {@link #init()} instead as it's more indicative of what's happening.
- */
- @Deprecated
- public final void register() {
- init();
- }
-
/**
* Will initialise the manager and register both commands and completions. You should only really use this if
- * you've used {@link AikarCommandManager#reset()} or both {@link AikarCommandManager#deregisterCommands()} and
- * {@link AikarCommandManager#deregisterCompletions()}, otherwise there may be issues.
+ * you've used {@link AikarCommandManager#reset()} or both {@link AikarCommandManager#resetCommands()} and
+ * {@link AikarCommandManager#resetCompletions()}, otherwise there may be issues.
*/
public final void init() {
this.manager = new CustomBukkitManager(plugin);
@@ -83,19 +74,19 @@ public final void init() {
}
/**
- * This is called as part of {@link AikarCommandManager#register()} and should be overridden by an extending class
- * to register all (or as many) commands at once.
+ * This is called as part of {@link AikarCommandManager#init()} and should be overridden by an extending class to
+ * register all (or as many) commands at once.
*/
public void registerCommands() { }
/**
- * This is called as part of {@link AikarCommandManager#register()} and should be overridden by an extending class
- * to register all (or as many) completions at once, though make sure to call super.
+ * This is called as part of {@link AikarCommandManager#init()} and should be overridden by an extending class to
+ * register all (or as many) completions at once, though make sure to call super.
*
* @param completions The completion manager is given. It is the same manager that can be reached via
* {@link CustomBukkitManager#getCommandCompletions()}.
*/
- public void registerCompletions(CommandCompletions completions) {
+ public void registerCompletions(final CommandCompletions completions) {
completions.registerAsyncCompletion("allplayers", context ->
Arrays.stream(Bukkit.getOfflinePlayers())
.map(OfflinePlayer::getName)
@@ -115,24 +106,24 @@ public void registerCompletions(CommandCompletions contexts) { }
+ public void registerContexts(final CommandContexts contexts) { }
/**
* Registers a new command and any attached tab completions.
*
* @param command The command instance to register.
*/
- public final void registerCommand(AikarCommand command) {
+ public final void registerCommand(final AikarCommand command) {
Preconditions.checkArgument(command != null, "Could not register that command: the command was null.");
this.manager.registerCommand(command);
this.plugin.info("Command [" + command.getClass().getSimpleName() + "] registered.");
- for (Map.Entry entry : getTabCompletions(command.getClass()).entrySet()) {
+ for (final var entry : getTabCompletions(command.getClass()).entrySet()) {
if (entry.getValue().async()) {
this.manager.getCommandCompletions().registerAsyncCompletion(entry.getValue().value(), (context) ->
runCommandCompletion(context, command, entry.getValue().value(), entry.getKey()));
@@ -151,7 +142,7 @@ public final void registerCommand(AikarCommand command) {
* @param command The command instance to register.
*/
@SuppressWarnings("unchecked")
- public final void deregisterCommand(AikarCommand command) {
+ public final void deregisterCommand(final AikarCommand command) {
Preconditions.checkArgument(command != null, "Could not deregister that command: the command was null.");
this.manager.unregisterCommand(command);
this.plugin.info("Command [" + command.getClass().getSimpleName() + "] deregistered.");
@@ -170,16 +161,16 @@ public final void deregisterCommand(AikarCommand command) {
}
/**
- * Deregisters all commands.
+ * Resets all commands.
*/
- public final void deregisterCommands() {
+ public final void resetCommands() {
this.manager.unregisterCommands();
}
/**
- * Deregisters all command completions.
+ * Resets all command completions.
*/
- public final void deregisterCompletions() {
+ public final void resetCompletions() {
this.manager.unregisterCompletions();
}
@@ -187,8 +178,8 @@ public final void deregisterCompletions() {
* Resets the manager, resetting all commands and completions.
*/
public final void reset() {
- this.manager.unregisterCommands();
- this.manager.unregisterCompletions();
+ resetCommands();
+ resetCompletions();
this.manager = null;
}
@@ -201,6 +192,10 @@ public final CustomBukkitManager getInternalManager() {
return this.manager;
}
+ public final ACivMod getPlugin() {
+ return this.plugin;
+ }
+
// ------------------------------------------------------------
// Utilities
// ------------------------------------------------------------
From f2fb138f85585905f8b7505658d20a385169620e Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 19 Apr 2021 10:17:28 +0100
Subject: [PATCH 029/143] Allow a ClonedInventory to be force cloned
---
.../mc/civmodcore/inventory/ClonedInventory.java | 16 +++++++++++++++-
1 file changed, 15 insertions(+), 1 deletion(-)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/ClonedInventory.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/ClonedInventory.java
index 8354095f..b9738bc4 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/ClonedInventory.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/ClonedInventory.java
@@ -231,10 +231,24 @@ public Inventory getInventory() {
* @return Returns a clone of the given inventory.
*/
public static ClonedInventory cloneInventory(final Inventory inventory) {
+ return cloneInventory(inventory, false);
+ }
+
+ /**
+ *
Clones the given inventory for the purpose of test manipulating its contents.
+ *
+ *
Note: Do not type check the inventory, it's JUST a contents copy within an inventory wrapper to provide the
+ * relevant and useful methods.
+ *
+ * @param inventory The inventory to clone.
+ * @param forceClone Determines whether the inventory should be cloned even if it's an already cloned inventory.
+ * @return Returns a clone of the given inventory.
+ */
+ public static ClonedInventory cloneInventory(final Inventory inventory, final boolean forceClone) {
if (inventory == null) {
return null;
}
- if (inventory instanceof ClonedInventory) {
+ if (!forceClone && inventory instanceof ClonedInventory) {
return (ClonedInventory) inventory;
}
Inventory clone;
From 228450d9dea38de8fc977a3abcaa836d02a2b911 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 19 Apr 2021 10:20:17 +0100
Subject: [PATCH 030/143] Allow NBTCompound to wrap PersistentDataContainers
---
.../mc/civmodcore/serialization/NBTCompound.java | 16 +++++++++++++---
1 file changed, 13 insertions(+), 3 deletions(-)
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..5952b312 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java
@@ -23,7 +23,9 @@
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftItemStack;
+import org.bukkit.craftbukkit.v1_16_R3.persistence.CraftPersistentDataContainer;
import org.bukkit.inventory.ItemStack;
+import org.bukkit.persistence.PersistentDataContainer;
import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils;
import vg.civcraft.mc.civmodcore.util.NullUtils;
import vg.civcraft.mc.civmodcore.util.Validation;
@@ -38,11 +40,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;
@@ -63,6 +62,15 @@ public NBTCompound(NBTTagCompound tag) {
this.tag = tag == null ? new NBTTagCompound() : tag;
}
+ /**
+ * Creates a new NBTCompound by wrapping an existing PersistentDataContainer.
+ *
+ * @param container The PersistentDataContainer to wrap.
+ */
+ public NBTCompound(final PersistentDataContainer container) {
+ this(container == null ? null : new NBTTagCompound(((CraftPersistentDataContainer) container).getRaw()) {});
+ }
+
/**
* Creates a new NBTCompound by wrapping and serialising an NBTSerializable object.
*
@@ -848,6 +856,7 @@ public void setCompoundArray(String key, NBTCompound[] values) {
* @param key The key to get the value of.
* @return The value of the key, default: empty list
*/
+ @Deprecated
public NBTCompoundList getSerializableList(String key) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(key));
if (!this.tag.hasKeyOfType(key, 9)) {
@@ -862,6 +871,7 @@ public NBTCompoundList getSerializableList(String
* @param key The key to set to value to.
* @param value The value to set to the key.
*/
+ @Deprecated
public void setSerializableList(String key, NBTCompoundList> value) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(key));
if (value == null) {
From 6240e1a6168461470a41fc1304c0128db3ea7926 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 19 Apr 2021 10:28:22 +0100
Subject: [PATCH 031/143] Add MoreCollectionUtils.collectExact() as a safer
version of Arrays.asList()
---
.../civmodcore/util/MoreCollectionUtils.java | 27 +++++++++++++++++++
1 file changed, 27 insertions(+)
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..ab8d5814 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/util/MoreCollectionUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/MoreCollectionUtils.java
@@ -1,6 +1,8 @@
package vg.civcraft.mc.civmodcore.util;
+import it.unimi.dsi.fastutil.ints.Int2ObjectFunction;
import java.util.Collection;
+import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
@@ -34,6 +36,31 @@ public static > K collect(final Supplier construct
return collection;
}
+ /**
+ * Creates a new collection with the exact size of 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.
+ */
+ @SafeVarargs
+ public static > K collectExact(final Int2ObjectFunction constructor,
+ final T... elements) {
+ if (constructor == null) {
+ return null;
+ }
+ if (elements == null) {
+ return constructor.get(0);
+ }
+ final K collection = constructor.get(elements.length);
+ if (collection != null) {
+ Collections.addAll(collection, elements);
+ }
+ return collection;
+ }
+
/**
*
Tests whether there is at least one element in the given collection that passes the criteria of the given
* predicate.
From ff81b4e8e8a1546146532dfc822acccc02612a4f Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 19 Apr 2021 17:37:02 +0100
Subject: [PATCH 032/143] Add UuidUtils.fromString() for less throwy UUID
parsing
---
.../civcraft/mc/civmodcore/util/UuidUtils.java | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/UuidUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/util/UuidUtils.java
index f37ec770..87365222 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/util/UuidUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/UuidUtils.java
@@ -23,6 +23,24 @@ public static boolean isNullOrIdentity(final UUID uuid) {
return uuid == null || IDENTITY.equals(uuid);
}
+ /**
+ * Attempts to parse a UUID from a given string.
+ *
+ * @param value The string to parse.
+ * @return Returns a valid UUID, or null.
+ */
+ public static UUID fromString(final String value) {
+ if (value == null) {
+ return null;
+ }
+ try {
+ return UUID.fromString(value);
+ }
+ catch (final Exception ignored) {
+ return null;
+ }
+ }
+
/**
* Converts a UUID to a byte array.
*
From c3a5f855f70920cfecb3b688621d84f2840f6c86 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 19 Apr 2021 20:14:16 +0100
Subject: [PATCH 033/143] Fix PseudoServer from throwing fits upon second setup
---
src/test/java/org/bukkit/pseudo/PseudoServer.java | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)
diff --git a/src/test/java/org/bukkit/pseudo/PseudoServer.java b/src/test/java/org/bukkit/pseudo/PseudoServer.java
index 12b6c8a6..df3f58cb 100644
--- a/src/test/java/org/bukkit/pseudo/PseudoServer.java
+++ b/src/test/java/org/bukkit/pseudo/PseudoServer.java
@@ -74,10 +74,12 @@ public class PseudoServer implements Server {
private static final Logger LOGGER = Logger.getLogger(PseudoServer.class.getSimpleName());
public static void setup() {
- final var previousLevel = LOGGER.getLevel();
- LOGGER.setLevel(Level.OFF); // This is to prevent unnecessary logging
- Bukkit.setServer(INSTANCE);
- LOGGER.setLevel(previousLevel);
+ if (Bukkit.getServer() == null) { // Ignore highlighter
+ final var previousLevel = LOGGER.getLevel();
+ LOGGER.setLevel(Level.OFF); // This is to prevent unnecessary logging
+ Bukkit.setServer(INSTANCE);
+ LOGGER.setLevel(previousLevel);
+ }
}
@NotNull
From e406d11d5bbd0a341592c3643e420774f0646449 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 19 Apr 2021 20:19:15 +0100
Subject: [PATCH 034/143] Add new serialisation tests
---
.../serialization/SerializationTests.java | 58 +++++++++++--------
1 file changed, 35 insertions(+), 23 deletions(-)
diff --git a/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTests.java b/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTests.java
index 1f888cbf..7b5bf95c 100644
--- a/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTests.java
+++ b/src/test/java/vg/civcraft/mc/civmodcore/serialization/SerializationTests.java
@@ -1,16 +1,26 @@
package vg.civcraft.mc.civmodcore.serialization;
-import java.util.Objects;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.format.NamedTextColor;
+import net.kyori.adventure.text.format.TextDecoration;
+import org.bukkit.Location;
+import org.bukkit.Material;
+import org.bukkit.inventory.ItemStack;
+import org.bukkit.inventory.meta.ItemMeta;
+import org.bukkit.pseudo.PseudoServer;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
+import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils;
+import vg.civcraft.mc.civmodcore.inventory.items.MetaUtils;
import vg.civcraft.mc.civmodcore.util.Validation;
public class SerializationTests {
@BeforeClass
public static void beforeAll() {
+ PseudoServer.setup();
NBTSerialization.registerNBTSerializable(ExampleSerializable.class);
}
@@ -126,31 +136,33 @@ public void testNBTClearing() {
}
@Test
- public void testListValues() {
+ public void testLocationSerialisation() {
// 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);
+ final var location = new Location(null,
+ 123.456d, 789.654d, 321.098d,
+ 1.12344f, 123.234f);
+ // Process
+ final var nbt = NBTHelper.locationToNBT(location);
+ final var parsed = NBTHelper.locationFromNBT(nbt);
+ // Check
+ Assert.assertEquals(location, parsed);
+ }
+
+ @Test
+ public void testItemStackSerialisation() {
+ // Setup
+ final var item = new ItemStack(Material.STONE);
+ ItemUtils.handleItemMeta(item, (ItemMeta meta) -> {
+ meta.displayName(Component.text("Hello World!"));
+ MetaUtils.setComponentLore(meta, Component.text("Testing!",
+ NamedTextColor.YELLOW, TextDecoration.UNDERLINED));
+ return true;
+ });
// Process
- NBTCompound beforeNBT = new NBTCompound();
- beforeNBT.setSerializableList(LIST_KEY, list);
- byte[] data = NBTCompound.toBytes(beforeNBT);
- NBTCompound afterNBT = NBTCompound.fromBytes(data);
+ final var nbt = NBTHelper.itemStackToNBT(item);
+ final var parsed = NBTHelper.itemStackFromNBT(nbt);
// Check
- Assert.assertNotNull(afterNBT);
- Assert.assertEquals(expectedString, Objects.requireNonNull(
- afterNBT.getSerializableList(LIST_KEY).get(0)).getMessage());
+ Assert.assertEquals(item, parsed);
}
}
From f306c783b7d3092e8f468ccd8d8898da95e6ad0c Mon Sep 17 00:00:00 2001
From: Alexander
Date: Tue, 20 Apr 2021 18:23:09 +0100
Subject: [PATCH 035/143] Add self GUI system
---
.../mc/civmodcore/CivModCorePlugin.java | 18 ++-
.../inventory/gui/self/SelfGUI.java | 34 ++++
.../inventory/gui/self/SelfGUIManager.java | 153 ++++++++++++++++++
.../mc/civmodcore/util/Resettable.java | 18 +++
4 files changed, 217 insertions(+), 6 deletions(-)
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUIManager.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/Resettable.java
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
index 8f9dc2c9..f06921c6 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
@@ -11,6 +11,7 @@
import vg.civcraft.mc.civmodcore.command.AikarCommandManager;
import vg.civcraft.mc.civmodcore.dao.ManagedDatasource;
import vg.civcraft.mc.civmodcore.events.CustomEventMapper;
+import vg.civcraft.mc.civmodcore.inventory.gui.self.SelfGUIManager;
import vg.civcraft.mc.civmodcore.inventory.items.EnchantUtils;
import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils;
import vg.civcraft.mc.civmodcore.inventory.items.MoreTags;
@@ -42,7 +43,13 @@ public final class CivModCorePlugin extends ACivMod {
private GlobalChunkMetaManager chunkMetaManager;
private ManagedDatasource database;
private WorldIDManager worldIdManager;
- private AikarCommandManager commands;
+ private final AikarCommandManager commands;
+ private final SelfGUIManager selfGUIManager;
+
+ public CivModCorePlugin() {
+ this.commands = new AikarCommandManager(this, false);
+ this.selfGUIManager = new SelfGUIManager(this);
+ }
@Override
public void onEnable() {
@@ -86,7 +93,7 @@ public void onEnable() {
registerListener(new WorldTracker());
registerListener(ChunkOperationManager.INSTANCE);
// Register commands
- this.commands = new AikarCommandManager(this);
+ this.commands.init();
this.commands.registerCommand(new ConfigCommand());
this.commands.registerCommand(ChunkOperationManager.INSTANCE);
// Load APIs
@@ -99,12 +106,14 @@ public void onEnable() {
BottomLineAPI.init();
newCommandHandler.registerCommand(new ConfigSetAnyCommand());
newCommandHandler.registerCommand(new ConfigGetAnyCommand());
+ this.selfGUIManager.init();
// Deprecated
PotionNames.loadPotionNames();
}
@Override
public void onDisable() {
+ this.selfGUIManager.reset();
Bukkit.getOnlinePlayers().forEach(HumanEntity::closeInventory);
PotionNames.resetPotionNames();
ChunkMetaAPI.saveAll();
@@ -124,10 +133,7 @@ public void onDisable() {
PlayerSettingAPI.saveAll();
ConfigurationSerialization.unregisterClass(ManagedDatasource.class);
NBTSerialization.clearAllRegistrations();
- if (this.commands != null) {
- this.commands.reset();
- this.commands = null;
- }
+ this.commands.reset();
super.onDisable();
}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUI.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUI.java
new file mode 100644
index 00000000..5ebb0c70
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUI.java
@@ -0,0 +1,34 @@
+package vg.civcraft.mc.civmodcore.inventory.gui.self;
+
+import java.util.Objects;
+import org.bukkit.event.inventory.InventoryEvent;
+import org.bukkit.inventory.Inventory;
+
+public abstract class SelfGUI {
+
+ private final T inventory;
+
+ public SelfGUI(final T inventory) {
+ this.inventory = Objects.requireNonNull(inventory);
+ }
+
+ /**
+ * @return Returns the wrapped inventory this GUI represents.
+ */
+ public final T getInventory() {
+ return this.inventory;
+ }
+
+ protected void handleTrackingStart() {
+
+ }
+
+ protected void handleTrackingEnd() {
+
+ }
+
+ protected void handleEvent(final InventoryEvent event) {
+
+ }
+
+}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUIManager.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUIManager.java
new file mode 100644
index 00000000..88a517a7
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUIManager.java
@@ -0,0 +1,153 @@
+package vg.civcraft.mc.civmodcore.inventory.gui.self;
+
+import com.destroystokyo.paper.event.block.AnvilDamagedEvent;
+import com.destroystokyo.paper.event.inventory.PrepareResultEvent;
+import java.util.Hashtable;
+import java.util.Map;
+import java.util.Objects;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.HandlerList;
+import org.bukkit.event.Listener;
+import org.bukkit.event.enchantment.EnchantItemEvent;
+import org.bukkit.event.enchantment.PrepareItemEnchantEvent;
+import org.bukkit.event.inventory.CraftItemEvent;
+import org.bukkit.event.inventory.InventoryCloseEvent;
+import org.bukkit.event.inventory.InventoryCreativeEvent;
+import org.bukkit.event.inventory.InventoryDragEvent;
+import org.bukkit.event.inventory.InventoryEvent;
+import org.bukkit.event.inventory.InventoryOpenEvent;
+import org.bukkit.event.inventory.PrepareItemCraftEvent;
+import org.bukkit.event.inventory.TradeSelectEvent;
+import org.bukkit.inventory.Inventory;
+import vg.civcraft.mc.civmodcore.CivModCorePlugin;
+import vg.civcraft.mc.civmodcore.util.Resettable;
+
+public final class SelfGUIManager implements Resettable, Listener {
+
+ private static SelfGUIManager instance;
+
+ private final CivModCorePlugin plugin;
+ private final Map> guis;
+
+ public SelfGUIManager(final CivModCorePlugin plugin) {
+ if (instance != null) {
+ throw new IllegalStateException("Cannot create more than one self GUI manager!");
+ }
+ instance = this;
+ this.plugin = Objects.requireNonNull(plugin);
+ this.guis = new Hashtable<>();
+ }
+
+ @Override
+ public void init() {
+ this.plugin.registerListener(this);
+ }
+
+ @Override
+ public void reset() {
+ for (final var gui : this.guis.values()) {
+ gui.handleTrackingEnd();
+ }
+ this.guis.clear();
+ HandlerList.unregisterAll(this);
+ }
+
+ public static void registerInventory(final SelfGUI gui) {
+ if (instance == null) {
+ throw new IllegalStateException(SelfGUIManager.class.getSimpleName() + " has not been constructed!");
+ }
+ if (gui == null) {
+ return;
+ }
+ instance.guis.compute(gui.getInventory(), (inventory, existing) -> {
+ if (existing != null) {
+ existing.handleTrackingEnd();
+ }
+ gui.handleTrackingStart();
+ return gui;
+ });
+ }
+
+ public static void unregisterInventory(final SelfGUI gui) {
+ if (instance == null) {
+ throw new IllegalStateException(SelfGUIManager.class.getSimpleName() + " has not been constructed!");
+ }
+ if (gui == null) {
+ return;
+ }
+ final var removed = instance.guis.remove(gui.getInventory());
+ if (gui != removed) {
+ removed.handleTrackingEnd();
+ }
+ gui.handleTrackingEnd();
+ }
+
+ // ------------------------------------------------------------
+ // Event Listeners - Should be comprehensive
+ // ------------------------------------------------------------
+
+ public void relayInventoryEvent(final InventoryEvent event) {
+ final var gui = this.guis.get(event.getInventory());
+ if (gui == null) {
+ return;
+ }
+ gui.handleEvent(event);
+ }
+
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
+ public void relayInventoryOpen(final InventoryOpenEvent event) {
+ relayInventoryEvent(event);
+ }
+
+ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
+ public void relayInventoryClose(final InventoryCloseEvent event) {
+ relayInventoryEvent(event);
+ }
+
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
+ public void relayInventoryDrag(final InventoryDragEvent event) {
+ relayInventoryEvent(event);
+ }
+
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
+ public void relayTradeSelect(final TradeSelectEvent event) {
+ relayInventoryEvent(event);
+ }
+
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
+ public void relayCraftEvent(final CraftItemEvent event) {
+ relayInventoryEvent(event);
+ }
+
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
+ public void relayCreativeEvent(final InventoryCreativeEvent event) {
+ relayInventoryEvent(event);
+ }
+
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
+ public void relayAnvilDamage(final AnvilDamagedEvent event) {
+ relayInventoryEvent(event);
+ }
+
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
+ public void relayEnchantItem(final EnchantItemEvent event) {
+ relayInventoryEvent(event);
+ }
+
+ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
+ public void relayPrepareCrafting(final PrepareItemCraftEvent event) {
+ relayInventoryEvent(event);
+ }
+
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
+ public void relayPrepareEnchant(final PrepareItemEnchantEvent event) {
+ relayInventoryEvent(event);
+ }
+
+ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
+ public void relayPrepareResult(final PrepareResultEvent event) {
+ relayInventoryEvent(event);
+ }
+
+}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/Resettable.java b/src/main/java/vg/civcraft/mc/civmodcore/util/Resettable.java
new file mode 100644
index 00000000..85fddcf4
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/Resettable.java
@@ -0,0 +1,18 @@
+package vg.civcraft.mc.civmodcore.util;
+
+/**
+ * This exists to try and standardise initialising and resetting objects.
+ */
+public interface Resettable {
+
+ /**
+ * Initialises this object, which is irrelevant to construction.
+ */
+ void init();
+
+ /**
+ * Resets this object, which is irrelevant to finalisation / closure.
+ */
+ void reset();
+
+}
From 0a1586cd0759ca9fc1fb04fd9b25f8205abd49a4 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Tue, 20 Apr 2021 18:23:36 +0100
Subject: [PATCH 036/143] Add ChatUtils.newComponent()
---
.../mc/civmodcore/chat/ChatUtils.java | 21 +++++++++++++++++++
1 file changed, 21 insertions(+)
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 63a820b9..1f8a0a96 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java
@@ -3,7 +3,9 @@
import com.google.common.base.Strings;
import java.awt.Color;
import java.util.List;
+import java.util.Objects;
import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.md_5.bungee.api.ChatColor;
@@ -182,6 +184,25 @@ public static boolean isNullOrEmpty(final Component component) {
return Strings.isNullOrEmpty(LegacyComponentSerializer.legacyAmpersand().serialize(component));
}
+ /**
+ * @return Generates a new text component that's specifically NOT italicised. Use this for item names and
+ * lore.
+ */
+ public static net.kyori.adventure.text.TextComponent newComponent() {
+ return newComponent("");
+ }
+
+ /**
+ * Generates a new text component that's specifically NOT italicised. Use this for item names and lore.
+ *
+ * @param content The text content for the component.
+ * @return Returns the generated text component.
+ */
+ public static net.kyori.adventure.text.TextComponent newComponent(final String content) {
+ return Component.text(Objects.requireNonNull(content))
+ .decoration(TextDecoration.ITALIC, TextDecoration.State.FALSE);
+ }
+
/**
* This is an easy way to create a text component when all you want to do is colour it.
*
From 502fc3b441a8cf8c513b6b3218d45de10688b09b Mon Sep 17 00:00:00 2001
From: Alexander
Date: Tue, 20 Apr 2021 18:26:04 +0100
Subject: [PATCH 037/143] Add BatchedNbtStorage
---
.../storage/nbt/BatchedNbtStorage.java | 124 ++++++++++++++++++
1 file changed, 124 insertions(+)
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/storage/nbt/BatchedNbtStorage.java
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/storage/nbt/BatchedNbtStorage.java b/src/main/java/vg/civcraft/mc/civmodcore/storage/nbt/BatchedNbtStorage.java
new file mode 100644
index 00000000..5df82f57
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/storage/nbt/BatchedNbtStorage.java
@@ -0,0 +1,124 @@
+package vg.civcraft.mc.civmodcore.storage.nbt;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import java.io.File;
+import java.util.Objects;
+import java.util.stream.Stream;
+import org.apache.commons.lang3.ArrayUtils;
+import org.bukkit.craftbukkit.libs.org.apache.commons.io.FileUtils;
+import org.bukkit.craftbukkit.libs.org.apache.commons.io.FilenameUtils;
+import vg.civcraft.mc.civmodcore.ACivMod;
+import vg.civcraft.mc.civmodcore.serialization.NBTCompound;
+import vg.civcraft.mc.civmodcore.util.CivLogger;
+
+public abstract class BatchedNbtStorage {
+
+ protected static final String EXTENSION = "nbt";
+
+ protected final CivLogger logger;
+ protected final File storageFolder;
+
+ public BatchedNbtStorage(final ACivMod plugin, final String folder) {
+ Preconditions.checkArgument(!Strings.isNullOrEmpty(folder));
+ this.logger = CivLogger.getLogger(getClass());
+ this.storageFolder = new File(plugin.getDataFolder(), folder);
+ }
+
+ /**
+ * Loads all the ".nbt" files from the storage folder.
+ *
+ * @return Returns a stream of all the correct parsed nbt files into their appropriate container.
+ */
+ public Stream loadAll() {
+ if (!this.storageFolder.isDirectory()) {
+ return Stream.empty().parallel();
+ }
+ final var files = this.storageFolder.listFiles();
+ if (ArrayUtils.isEmpty(files)) {
+ return Stream.empty().parallel();
+ }
+ assert files != null;
+ return Stream.of(files)
+ .parallel()
+ .filter(file -> FilenameUtils.isExtension(file.getName(), EXTENSION))
+ .map(this::loadFile)
+ .filter(Objects::nonNull);
+ }
+
+ /**
+ * Saves a given stream of elements to their respective files.
+ *
+ * @param elements The elements to save.
+ * @return Returns a stream of all elements that were successfully saved.
+ */
+ public Stream saveSelected(final Stream elements) {
+ if (elements == null) {
+ return Stream.empty().parallel();
+ }
+ return elements.parallel()
+ .filter(Objects::nonNull)
+ .map(this::saveElement)
+ .filter(Objects::nonNull); // Remove unsuccessful saves
+ }
+
+ /**
+ * Removes all given elements' respective files.
+ *
+ * @param elements The elements to remove the files of.
+ * @return Returns a stream of elements whose files could not be removed.
+ */
+ public Stream removeSelected(final Stream elements) {
+ if (elements == null) {
+ return Stream.empty().parallel();
+ }
+ return elements.parallel()
+ .map(this::removeElement)
+ .filter(Objects::nonNull); // Remove successful deletions
+ }
+
+ /**
+ * This method is called during {@link #loadAll()} and is used to read and parse the data within the given file. You
+ * should also check the file's name using maybe {@link FilenameUtils#getBaseName(String)} to ensure it's correctly
+ * formatted. I'd recommend using {@link FileUtils#readFileToByteArray(File)} to read the file, then using
+ * {@link NBTCompound#fromBytes(byte[])} to convert that into a usable NBT instance. If for whatever reason the file
+ * cannot be correctly parsed, the correct course of action is to log the error using {@link this#logger} and
+ * returning null.
+ *
+ * @param file The file to read and parse.
+ * @return Returns a valid instance of the resulting container, or null if something went wrong.
+ */
+ protected abstract T loadFile(final File file);
+
+ /**
+ * This method is called during {@link #saveSelected(Stream)} and is used to save particular elements to their
+ * respective files. You can use {@link #generateFileName(Object)} to determine what that filename should be. I'd
+ * recommend you use {@link FileUtils#writeByteArrayToFile(File, byte[])} via
+ * {@link NBTCompound#toBytes(NBTCompound)}. If the element was successfully saved, return the element or otherwise
+ * return null.
+ *
+ * @param element The element to save to its respective file.
+ * @return Returns the element if successfully saved, otherwise null.
+ */
+ protected abstract T saveElement(final T element);
+
+ /**
+ * This method is called during {@link #removeSelected(Stream)} and is used to delete particular elements' files.
+ * You can use {@link #generateFileName(Object)} to determine what the file's name should be.
+ *
+ * @param element The element to delete the file of.
+ * @return Returns null if the file was successfully deleted, otherwise return the given element.
+ */
+ protected abstract T removeElement(final T element);
+
+ /**
+ * Generates a filename based on the given object.
+ *
+ * @param object The object to base the filename off.
+ * @return Returns a file name with the appropriate extension.
+ */
+ protected String generateFileName(final Object object) {
+ return object + "." + EXTENSION;
+ }
+
+}
From a87daecb8337c7da64e269fb2ad685f5af8eaf82 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Tue, 20 Apr 2021 18:29:40 +0100
Subject: [PATCH 038/143] Fix NBTHelper ItemStack serialisation
---
.../java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java
index 5ee8ddcc..ea854a9e 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java
@@ -67,7 +67,7 @@ public static NBTCompound itemStackToNBT(final ItemStack item) {
return null;
}
final var nbt = new NBTCompound();
- ((CraftItemStack) item).getHandle().save(nbt.getRAW());
+ CraftItemStack.asNMSCopy(item).save(nbt.getRAW());
return nbt;
}
From 39ca103769923a083956709c1669e823d383648b Mon Sep 17 00:00:00 2001
From: Alexander
Date: Tue, 20 Apr 2021 18:30:19 +0100
Subject: [PATCH 039/143] Add NBTCompound#getCompound() version that ensures
non-null
---
.../mc/civmodcore/serialization/NBTCompound.java | 14 ++++++++++++++
1 file changed, 14 insertions(+)
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 5952b312..b37cb721 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java
@@ -437,8 +437,22 @@ public void setString(String key, String value) {
* @return The value of the key, default: NULL
*/
public NBTCompound getCompound(String key) {
+ return getCompound(key, false);
+ }
+
+ /**
+ * Gets a tag compound value from a key.
+ *
+ * @param key The key to get the value of.
+ * @param forceNonNull Whether to force the returned value to be non-null.
+ * @return The value of the key, which is never null.
+ */
+ public NBTCompound getCompound(final String key, final boolean forceNonNull) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(key));
if (!this.tag.hasKeyOfType(key, 10)) {
+ if (forceNonNull) {
+ return new NBTCompound();
+ }
return null;
}
return new NBTCompound(this.tag.getCompound(key));
From cee3c43498a113e61e44dc7aee4f4547e96ee714 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Tue, 20 Apr 2021 18:30:47 +0100
Subject: [PATCH 040/143] Add chest row amount values
---
.../civcraft/mc/civmodcore/inventory/InventoryUtils.java | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java
index 4b4de3fe..8d83053f 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java
@@ -14,6 +14,13 @@
public final class InventoryUtils {
+ public static final int CHEST_1_ROW = 9;
+ public static final int CHEST_2_ROWS = 9 * 2;
+ public static final int CHEST_3_ROWS = 9 * 3;
+ public static final int CHEST_4_ROWS = 9 * 4;
+ public static final int CHEST_5_ROWS = 9 * 5;
+ public static final int CHEST_6_ROWS = 9 * 6;
+
/**
* Tests an inventory to see if it's valid.
*
From 52a6b86cd2bf0454a47a2488978aa4abc7a760fe Mon Sep 17 00:00:00 2001
From: Alexander
Date: Wed, 21 Apr 2021 17:06:51 +0100
Subject: [PATCH 041/143] Self GUI was a dud, remove
---
.../mc/civmodcore/CivModCorePlugin.java | 5 -
.../inventory/gui/self/SelfGUI.java | 34 ----
.../inventory/gui/self/SelfGUIManager.java | 153 ------------------
3 files changed, 192 deletions(-)
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUI.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUIManager.java
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
index 00d9d484..639741a4 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
@@ -9,7 +9,6 @@
import vg.civcraft.mc.civmodcore.command.AikarCommandManager;
import vg.civcraft.mc.civmodcore.dao.ManagedDatasource;
import vg.civcraft.mc.civmodcore.events.CustomEventMapper;
-import vg.civcraft.mc.civmodcore.inventory.gui.self.SelfGUIManager;
import vg.civcraft.mc.civmodcore.inventory.items.EnchantUtils;
import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils;
import vg.civcraft.mc.civmodcore.inventory.items.MoreTags;
@@ -41,11 +40,9 @@ public final class CivModCorePlugin extends ACivMod {
private ManagedDatasource database;
private WorldIDManager worldIdManager;
private final AikarCommandManager commands;
- private final SelfGUIManager selfGUIManager;
public CivModCorePlugin() {
this.commands = new AikarCommandManager(this, false);
- this.selfGUIManager = new SelfGUIManager(this);
}
@Override
@@ -102,12 +99,10 @@ public void onEnable() {
BottomLineAPI.init();
this.newCommandHandler.registerCommand(new ConfigSetAnyCommand());
this.newCommandHandler.registerCommand(new ConfigGetAnyCommand());
- this.selfGUIManager.init();
}
@Override
public void onDisable() {
- this.selfGUIManager.reset();
Bukkit.getOnlinePlayers().forEach(HumanEntity::closeInventory);
ChunkMetaAPI.saveAll();
this.chunkMetaManager = null;
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUI.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUI.java
deleted file mode 100644
index 5ebb0c70..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUI.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package vg.civcraft.mc.civmodcore.inventory.gui.self;
-
-import java.util.Objects;
-import org.bukkit.event.inventory.InventoryEvent;
-import org.bukkit.inventory.Inventory;
-
-public abstract class SelfGUI {
-
- private final T inventory;
-
- public SelfGUI(final T inventory) {
- this.inventory = Objects.requireNonNull(inventory);
- }
-
- /**
- * @return Returns the wrapped inventory this GUI represents.
- */
- public final T getInventory() {
- return this.inventory;
- }
-
- protected void handleTrackingStart() {
-
- }
-
- protected void handleTrackingEnd() {
-
- }
-
- protected void handleEvent(final InventoryEvent event) {
-
- }
-
-}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUIManager.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUIManager.java
deleted file mode 100644
index 88a517a7..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/self/SelfGUIManager.java
+++ /dev/null
@@ -1,153 +0,0 @@
-package vg.civcraft.mc.civmodcore.inventory.gui.self;
-
-import com.destroystokyo.paper.event.block.AnvilDamagedEvent;
-import com.destroystokyo.paper.event.inventory.PrepareResultEvent;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Objects;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.EventPriority;
-import org.bukkit.event.HandlerList;
-import org.bukkit.event.Listener;
-import org.bukkit.event.enchantment.EnchantItemEvent;
-import org.bukkit.event.enchantment.PrepareItemEnchantEvent;
-import org.bukkit.event.inventory.CraftItemEvent;
-import org.bukkit.event.inventory.InventoryCloseEvent;
-import org.bukkit.event.inventory.InventoryCreativeEvent;
-import org.bukkit.event.inventory.InventoryDragEvent;
-import org.bukkit.event.inventory.InventoryEvent;
-import org.bukkit.event.inventory.InventoryOpenEvent;
-import org.bukkit.event.inventory.PrepareItemCraftEvent;
-import org.bukkit.event.inventory.TradeSelectEvent;
-import org.bukkit.inventory.Inventory;
-import vg.civcraft.mc.civmodcore.CivModCorePlugin;
-import vg.civcraft.mc.civmodcore.util.Resettable;
-
-public final class SelfGUIManager implements Resettable, Listener {
-
- private static SelfGUIManager instance;
-
- private final CivModCorePlugin plugin;
- private final Map> guis;
-
- public SelfGUIManager(final CivModCorePlugin plugin) {
- if (instance != null) {
- throw new IllegalStateException("Cannot create more than one self GUI manager!");
- }
- instance = this;
- this.plugin = Objects.requireNonNull(plugin);
- this.guis = new Hashtable<>();
- }
-
- @Override
- public void init() {
- this.plugin.registerListener(this);
- }
-
- @Override
- public void reset() {
- for (final var gui : this.guis.values()) {
- gui.handleTrackingEnd();
- }
- this.guis.clear();
- HandlerList.unregisterAll(this);
- }
-
- public static void registerInventory(final SelfGUI gui) {
- if (instance == null) {
- throw new IllegalStateException(SelfGUIManager.class.getSimpleName() + " has not been constructed!");
- }
- if (gui == null) {
- return;
- }
- instance.guis.compute(gui.getInventory(), (inventory, existing) -> {
- if (existing != null) {
- existing.handleTrackingEnd();
- }
- gui.handleTrackingStart();
- return gui;
- });
- }
-
- public static void unregisterInventory(final SelfGUI gui) {
- if (instance == null) {
- throw new IllegalStateException(SelfGUIManager.class.getSimpleName() + " has not been constructed!");
- }
- if (gui == null) {
- return;
- }
- final var removed = instance.guis.remove(gui.getInventory());
- if (gui != removed) {
- removed.handleTrackingEnd();
- }
- gui.handleTrackingEnd();
- }
-
- // ------------------------------------------------------------
- // Event Listeners - Should be comprehensive
- // ------------------------------------------------------------
-
- public void relayInventoryEvent(final InventoryEvent event) {
- final var gui = this.guis.get(event.getInventory());
- if (gui == null) {
- return;
- }
- gui.handleEvent(event);
- }
-
- @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
- public void relayInventoryOpen(final InventoryOpenEvent event) {
- relayInventoryEvent(event);
- }
-
- @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
- public void relayInventoryClose(final InventoryCloseEvent event) {
- relayInventoryEvent(event);
- }
-
- @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
- public void relayInventoryDrag(final InventoryDragEvent event) {
- relayInventoryEvent(event);
- }
-
- @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
- public void relayTradeSelect(final TradeSelectEvent event) {
- relayInventoryEvent(event);
- }
-
- @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
- public void relayCraftEvent(final CraftItemEvent event) {
- relayInventoryEvent(event);
- }
-
- @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
- public void relayCreativeEvent(final InventoryCreativeEvent event) {
- relayInventoryEvent(event);
- }
-
- @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
- public void relayAnvilDamage(final AnvilDamagedEvent event) {
- relayInventoryEvent(event);
- }
-
- @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
- public void relayEnchantItem(final EnchantItemEvent event) {
- relayInventoryEvent(event);
- }
-
- @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
- public void relayPrepareCrafting(final PrepareItemCraftEvent event) {
- relayInventoryEvent(event);
- }
-
- @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
- public void relayPrepareEnchant(final PrepareItemEnchantEvent event) {
- relayInventoryEvent(event);
- }
-
- @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
- public void relayPrepareResult(final PrepareResultEvent event) {
- relayInventoryEvent(event);
- }
-
-}
From 9acf0c4e42ee31fb9d86b516dd1919feab0280da Mon Sep 17 00:00:00 2001
From: Alexander
Date: Wed, 21 Apr 2021 17:41:12 +0100
Subject: [PATCH 042/143] Custom merchant handling
---
.../merchant/CustomBukkitMerchant.java | 61 ++++++++++++++
.../entities/merchant/CustomNMSMerchant.java | 80 +++++++++++++++++++
2 files changed, 141 insertions(+)
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomBukkitMerchant.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomBukkitMerchant.java b/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomBukkitMerchant.java
new file mode 100644
index 00000000..de4f8617
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomBukkitMerchant.java
@@ -0,0 +1,61 @@
+package vg.civcraft.mc.civmodcore.entities.merchant;
+
+import io.papermc.paper.event.player.PlayerTradeEvent;
+import java.lang.reflect.Field;
+import java.util.logging.Level;
+import net.kyori.adventure.text.Component;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.bukkit.Bukkit;
+import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftMerchant;
+import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftMerchantCustom;
+import vg.civcraft.mc.civmodcore.util.CivLogger;
+
+/**
+ * This is an alternative to {@link Bukkit#createMerchant(Component)} that re-adds
+ * {@link PlayerTradeEvent} emissions. Just do: {@code new CustomBukkitMerchant(Component)}
+ */
+public class CustomBukkitMerchant extends CraftMerchantCustom {
+
+ private static final CivLogger LOGGER;
+ private static final Field MERCHANT_FIELD;
+
+ static {
+ LOGGER = CivLogger.getLogger(CustomBukkitMerchant.class);
+ MERCHANT_FIELD = FieldUtils.getField(CraftMerchant.class, "merchant", true);
+ FieldUtils.removeFinalModifier(MERCHANT_FIELD);
+ }
+
+ public CustomBukkitMerchant(final Component title) {
+ super(title);
+ final var nmsMerchant = new CustomNMSMerchant(this, title);
+ try {
+ FieldUtils.writeField(MERCHANT_FIELD, this, nmsMerchant, true);
+ }
+ catch (final IllegalAccessException exception) {
+ LOGGER.log(Level.SEVERE,
+ "Could not re-set merchant to [" + nmsMerchant + "]",
+ exception);
+ }
+ }
+
+ public CustomNMSMerchant getNMSMerchant() {
+ return (CustomNMSMerchant) super.getMerchant();
+ }
+
+ /**
+ * Use {@link #getNMSMerchant()} instead. The only reason why this is being kept is because
+ * the super constructor calls this function and expects this type, not {@link CustomNMSMerchant}.
+ */
+ @Deprecated
+ @Override
+ public CraftMerchantCustom.MinecraftMerchant getMerchant() {
+ return super.getMerchant();
+ }
+
+ @Override
+ public String toString() {
+ /** Stolen from {@link Object#toString()} because the super version is garbage */
+ return getClass().getName() + "@" + Integer.toHexString(hashCode());
+ }
+
+}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java b/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java
new file mode 100644
index 00000000..0d5347da
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java
@@ -0,0 +1,80 @@
+package vg.civcraft.mc.civmodcore.entities.merchant;
+
+import io.papermc.paper.event.player.PlayerTradeEvent;
+import java.lang.reflect.Field;
+import java.util.Objects;
+import net.kyori.adventure.text.Component;
+import net.minecraft.server.v1_16_R3.Entity;
+import net.minecraft.server.v1_16_R3.EntityExperienceOrb;
+import net.minecraft.server.v1_16_R3.EntityPlayer;
+import net.minecraft.server.v1_16_R3.EntityVillagerAbstract;
+import net.minecraft.server.v1_16_R3.EntityVillagerTrader;
+import net.minecraft.server.v1_16_R3.MerchantRecipe;
+import net.minecraft.server.v1_16_R3.MerchantRecipeList;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftMerchantCustom;
+import org.bukkit.entity.AbstractVillager;
+import org.bukkit.entity.ExperienceOrb;
+
+public class CustomNMSMerchant extends CraftMerchantCustom.MinecraftMerchant {
+
+ private static final Field TRADES_FIELD;
+
+ static {
+ TRADES_FIELD = FieldUtils.getField(CraftMerchantCustom.MinecraftMerchant.class, "trades", true);
+ FieldUtils.removeFinalModifier(TRADES_FIELD);
+ }
+
+ CustomNMSMerchant(final CustomBukkitMerchant merchant, final Component title) {
+ super(title);
+ this.craftMerchant = Objects.requireNonNull(merchant);
+ }
+
+ /**
+ * @return Returns the raw offers object (which is mutable) via reflection.
+ */
+ public MerchantRecipeList getRawOffers() {
+ try {
+ return (MerchantRecipeList) FieldUtils.readField(TRADES_FIELD, this, true);
+ }
+ catch (final IllegalAccessException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ /**
+ * This is based heavily on {@link EntityVillagerAbstract#a(MerchantRecipe)}. This method is called
+ * by NMS when a trade is being purchased.
+ */
+ @Override
+ public void a(final MerchantRecipe trade) {
+ if (getTrader() instanceof EntityPlayer) {
+ final var trader = (EntityPlayer) getTrader();
+ final var event = new PlayerTradeEvent(
+ trader.getBukkitEntity(),
+ (AbstractVillager) getCraftMerchant(),
+ trade.asBukkit(),
+ true, // reward xp?
+ true); // should increase uses?
+ event.callEvent();
+ if (event.isCancelled()) {
+ return;
+ }
+ final var eventTrade = event.getTrade();
+ if (event.willIncreaseTradeUses()) {
+ eventTrade.setUses(eventTrade.getUses() + 1);
+ }
+ if (event.isRewardingExp() && eventTrade.hasExperienceReward()) {
+ /** Based on {@link EntityVillagerTrader#b(MerchantRecipe)} */
+ final int xp = 3 + Entity.SHARED_RANDOM.nextInt(4);
+ final var world = trader.getWorld();
+ world.addEntity(new EntityExperienceOrb(
+ world, trader.locX(), trader.locY() + 0.5d, trader.locZ(),
+ xp, ExperienceOrb.SpawnReason.VILLAGER_TRADE, trader, null));
+ }
+ return;
+ }
+ super.a(trade);
+ }
+
+}
From 722cc61879b8bcea0ee199bb3fa287fc79543e15 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Wed, 21 Apr 2021 18:55:04 +0100
Subject: [PATCH 043/143] =?UTF-8?q?PlayerTradeEvent=20requires=20a=20non-n?=
=?UTF-8?q?ull=20villager=E2=80=A6=20so=20be=20it?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../entities/merchant/CustomNMSMerchant.java | 37 +++++++++++++++++--
1 file changed, 33 insertions(+), 4 deletions(-)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java b/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java
index 0d5347da..ff3780e0 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java
@@ -2,18 +2,22 @@
import io.papermc.paper.event.player.PlayerTradeEvent;
import java.lang.reflect.Field;
+import java.util.Collections;
import java.util.Objects;
import net.kyori.adventure.text.Component;
import net.minecraft.server.v1_16_R3.Entity;
import net.minecraft.server.v1_16_R3.EntityExperienceOrb;
import net.minecraft.server.v1_16_R3.EntityPlayer;
+import net.minecraft.server.v1_16_R3.EntityTypes;
+import net.minecraft.server.v1_16_R3.EntityVillager;
import net.minecraft.server.v1_16_R3.EntityVillagerAbstract;
import net.minecraft.server.v1_16_R3.EntityVillagerTrader;
import net.minecraft.server.v1_16_R3.MerchantRecipe;
import net.minecraft.server.v1_16_R3.MerchantRecipeList;
+import net.minecraft.server.v1_16_R3.World;
import org.apache.commons.lang3.reflect.FieldUtils;
+import org.bukkit.craftbukkit.v1_16_R3.entity.CraftVillager;
import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftMerchantCustom;
-import org.bukkit.entity.AbstractVillager;
import org.bukkit.entity.ExperienceOrb;
public class CustomNMSMerchant extends CraftMerchantCustom.MinecraftMerchant {
@@ -50,13 +54,15 @@ public MerchantRecipeList getRawOffers() {
public void a(final MerchantRecipe trade) {
if (getTrader() instanceof EntityPlayer) {
final var trader = (EntityPlayer) getTrader();
+ final var villager = createDisposableVillager(trader.getWorld());
final var event = new PlayerTradeEvent(
trader.getBukkitEntity(),
- (AbstractVillager) getCraftMerchant(),
+ villager, // Have to spawn a useless villager because this is @Nonnull
trade.asBukkit(),
- true, // reward xp?
- true); // should increase uses?
+ true, // reward xp?
+ true); // should increase uses?
event.callEvent();
+ killDisposableVillager(villager);
if (event.isCancelled()) {
return;
}
@@ -77,4 +83,27 @@ public void a(final MerchantRecipe trade) {
super.a(trade);
}
+ // ------------------------------------------------------------
+ // Unfortunate but necessary villager management
+ // ------------------------------------------------------------
+
+ private static CraftVillager createDisposableVillager(final World world) {
+ final var villager = new CraftVillager(world.getServer(),
+ new EntityVillager(EntityTypes.VILLAGER, world));
+ villager.setAI(false);
+ villager.setGravity(false);
+ villager.setCanPickupItems(false);
+ villager.setSilent(true);
+ villager.setVillagerExperience(0);
+ villager.setInvisible(true);
+ villager.setRecipes(Collections.emptyList());
+ return villager;
+ }
+
+ private static void killDisposableVillager(final CraftVillager villager) {
+ villager.getHandle().dead = true;
+ villager.getHandle().setHealth(0);
+ villager.getHandle().shouldBeRemoved = true;
+ }
+
}
From c249138e08e14b5311447c5f7062e91bc129b313 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Thu, 22 Apr 2021 20:27:31 +0100
Subject: [PATCH 044/143] Use more appropriate serialisation for
ChatUtils.isNullOrEmpty()
---
src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
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 1f8a0a96..12f5ae57 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java
@@ -8,6 +8,7 @@
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
+import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
@@ -181,7 +182,7 @@ public static boolean isNullOrEmpty(final Component component) {
if (component == null) {
return true;
}
- return Strings.isNullOrEmpty(LegacyComponentSerializer.legacyAmpersand().serialize(component));
+ return StringUtils.isBlank(PlainComponentSerializer.plain().serialize(component));
}
/**
From 4cc75aeee8d5bf6266c25a816f050aff92de9197 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Thu, 22 Apr 2021 20:29:50 +0100
Subject: [PATCH 045/143] Fix another CivLogger bug, hopefully last one
It's weird because the issue I was having before was fix with the last change.. maybe PaperMC changed something? Either way, the nuclear option should the plugin be loaded but not instantiated is to create a replicant logger since PaperMC doesn't define the logger until after the plugin has been constructed.
---
.../java/vg/civcraft/mc/civmodcore/util/CivLogger.java | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java b/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
index 83852f6a..018bfae4 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
@@ -1,10 +1,12 @@
package vg.civcraft.mc.civmodcore.util;
+import com.destroystokyo.paper.utils.PaperPluginLogger;
import com.google.common.base.Strings;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.reflect.FieldUtils;
+import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.PluginClassLoader;
public final class CivLogger extends Logger {
@@ -40,10 +42,11 @@ public static CivLogger getLogger(@Nonnull final Class> clazz) {
return new CivLogger(plugin.getLogger(), clazz.getSimpleName());
}
// Plugin has been constructed but not initialised yet
- final var loaderLoggerField = FieldUtils.getDeclaredField(PluginClassLoader.class, "logger", true);
+ final var descriptionField = FieldUtils.getDeclaredField(PluginClassLoader.class, "description", true);
try {
- final var loaderLogger = (Logger) loaderLoggerField.get(classLoader);
- return new CivLogger(loaderLogger, clazz.getSimpleName());
+ final var description = (PluginDescriptionFile) descriptionField.get(classLoader);
+ final var logger = PaperPluginLogger.getLogger(description);
+ return new CivLogger(logger, clazz.getSimpleName());
}
catch (final IllegalAccessException ignored) {}
}
From 818ec41828c09fe336009e3724e5402e7e225660 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Fri, 23 Apr 2021 00:13:54 +0100
Subject: [PATCH 046/143] Fallback on Bukkit logger
---
src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java b/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
index 018bfae4..ef3ddb94 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
@@ -6,6 +6,7 @@
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.reflect.FieldUtils;
+import org.bukkit.Bukkit;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.PluginClassLoader;
@@ -50,7 +51,7 @@ public static CivLogger getLogger(@Nonnull final Class> clazz) {
}
catch (final IllegalAccessException ignored) {}
}
- return new CivLogger(Logger.getLogger(CivLogger.class.getSimpleName()), clazz.getSimpleName());
+ return new CivLogger(Bukkit.getLogger(), clazz.getSimpleName());
}
}
From 7126b568c8e1b1622d7331335d88a9335e20817a Mon Sep 17 00:00:00 2001
From: Alexander
Date: Sat, 24 Apr 2021 16:22:52 +0100
Subject: [PATCH 047/143] Add clone component function
---
.../vg/civcraft/mc/civmodcore/chat/ChatUtils.java | 15 +++++++++++++++
1 file changed, 15 insertions(+)
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 12f5ae57..e6162799 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java
@@ -7,6 +7,7 @@
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.minimessage.MiniMessage;
+import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
import net.md_5.bungee.api.ChatColor;
@@ -204,6 +205,20 @@ public static net.kyori.adventure.text.TextComponent newComponent(final String c
.decoration(TextDecoration.ITALIC, TextDecoration.State.FALSE);
}
+ /**
+ * Clones a component.
+ *
+ * @param component The component to clone.
+ * @return Returns a clone of the given component.
+ */
+ public static Component cloneComponent(final Component component) {
+ if (component == null) {
+ return null;
+ }
+ final var raw = GsonComponentSerializer.gson().serialize(component);
+ return GsonComponentSerializer.gson().deserialize(raw);
+ }
+
/**
* This is an easy way to create a text component when all you want to do is colour it.
*
From 4c5df272053584757715c311e5baa2b6b61d6fcd Mon Sep 17 00:00:00 2001
From: Alexander
Date: Sat, 24 Apr 2021 21:52:15 +0100
Subject: [PATCH 048/143] Allow AikarCommandManager.getPlugin() to be
overridden
---
.../vg/civcraft/mc/civmodcore/command/AikarCommandManager.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/command/AikarCommandManager.java b/src/main/java/vg/civcraft/mc/civmodcore/command/AikarCommandManager.java
index cb70637f..f5fb95af 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/command/AikarCommandManager.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/command/AikarCommandManager.java
@@ -192,7 +192,7 @@ public final CustomBukkitManager getInternalManager() {
return this.manager;
}
- public final ACivMod getPlugin() {
+ public ACivMod getPlugin() {
return this.plugin;
}
From b21938af999ed5fcc83fc291c6aa9af79eed621c Mon Sep 17 00:00:00 2001
From: Alexander
Date: Sun, 25 Apr 2021 14:01:56 +0100
Subject: [PATCH 049/143] Add fastutil as a provided dependency
---
pom.xml | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/pom.xml b/pom.xml
index b1b76b19..39d74652 100644
--- a/pom.xml
+++ b/pom.xml
@@ -80,6 +80,13 @@
jsr3053.0.2
+
+
+ it.unimi.dsi
+ fastutil
+ 8.2.2
+ provided
+ junit
From cbef0d31ad763133aa666386f572f1310d0e8c5d Mon Sep 17 00:00:00 2001
From: Alexander
Date: Sun, 25 Apr 2021 14:16:37 +0100
Subject: [PATCH 050/143] Add MapColours enum
---
.../mc/civmodcore/CivModCorePlugin.java | 2 +
.../mc/civmodcore/maps/MapColours.java | 103 ++++++++++++++++++
2 files changed, 105 insertions(+)
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/maps/MapColours.java
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
index 639741a4..d0807d1f 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
@@ -21,6 +21,7 @@
import vg.civcraft.mc.civmodcore.locations.chunkmeta.api.ChunkMetaAPI;
import vg.civcraft.mc.civmodcore.locations.global.CMCWorldDAO;
import vg.civcraft.mc.civmodcore.locations.global.WorldIDManager;
+import vg.civcraft.mc.civmodcore.maps.MapColours;
import vg.civcraft.mc.civmodcore.playersettings.PlayerSettingAPI;
import vg.civcraft.mc.civmodcore.playersettings.gui.ConfigCommand;
import vg.civcraft.mc.civmodcore.playersettings.gui.ConfigGetAnyCommand;
@@ -97,6 +98,7 @@ public void onEnable() {
SpawnEggUtils.init();
TreeTypeUtils.init();
BottomLineAPI.init();
+ MapColours.init();
this.newCommandHandler.registerCommand(new ConfigSetAnyCommand());
this.newCommandHandler.registerCommand(new ConfigGetAnyCommand());
}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/maps/MapColours.java b/src/main/java/vg/civcraft/mc/civmodcore/maps/MapColours.java
new file mode 100644
index 00000000..184e3853
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/maps/MapColours.java
@@ -0,0 +1,103 @@
+package vg.civcraft.mc.civmodcore.maps;
+
+import java.util.Collection;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import javax.annotation.Nonnull;
+import net.minecraft.server.v1_16_R3.MaterialMapColor;
+import org.apache.commons.collections4.CollectionUtils;
+import vg.civcraft.mc.civmodcore.util.CivLogger;
+
+/**
+ * Reference
+ */
+public enum MapColours {
+
+ NONE(MaterialMapColor.b),
+ GRASS(MaterialMapColor.c),
+ SAND(MaterialMapColor.d),
+ WOOL(MaterialMapColor.e), // White wool
+ FIRE(MaterialMapColor.f),
+ ICE(MaterialMapColor.g),
+ METAL(MaterialMapColor.h),
+ PLANT(MaterialMapColor.i),
+ SNOW(MaterialMapColor.j),
+ CLAY(MaterialMapColor.k),
+ DIRT(MaterialMapColor.l),
+ STONE(MaterialMapColor.m),
+ WATER(MaterialMapColor.n),
+ WOOD(MaterialMapColor.o),
+ QUARTZ(MaterialMapColor.p),
+ COLOR_ORANGE(MaterialMapColor.q),
+ COLOR_MAGENTA(MaterialMapColor.r),
+ COLOR_LIGHT_BLUE(MaterialMapColor.s),
+ COLOR_YELLOW(MaterialMapColor.t),
+ COLOR_LIGHT_GREEN(MaterialMapColor.u),
+ COLOR_PINK(MaterialMapColor.v),
+ COLOR_GRAY(MaterialMapColor.w),
+ COLOR_LIGHT_GRAY(MaterialMapColor.x),
+ COLOR_CYAN(MaterialMapColor.y),
+ COLOR_PURPLE(MaterialMapColor.z),
+ COLOR_BLUE(MaterialMapColor.A),
+ COLOR_BROWN(MaterialMapColor.B),
+ COLOR_GREEN(MaterialMapColor.C),
+ COLOR_RED(MaterialMapColor.D),
+ COLOR_BLACK(MaterialMapColor.E),
+ GOLD(MaterialMapColor.F),
+ DIAMOND(MaterialMapColor.G),
+ LAPIS(MaterialMapColor.H),
+ EMERALD(MaterialMapColor.I),
+ PODZOL(MaterialMapColor.J),
+ NETHER(MaterialMapColor.K),
+ TERRACOTTA_WHITE(MaterialMapColor.L),
+ TERRACOTTA_ORANGE(MaterialMapColor.M),
+ TERRACOTTA_MAGENTA(MaterialMapColor.N),
+ TERRACOTTA_LIGHT_BLUE(MaterialMapColor.O),
+ TERRACOTTA_YELLOW(MaterialMapColor.P),
+ TERRACOTTA_LIGHT_GREEN(MaterialMapColor.Q),
+ TERRACOTTA_PINK(MaterialMapColor.R),
+ TERRACOTTA_GRAY(MaterialMapColor.S),
+ TERRACOTTA_LIGHT_GRAY(MaterialMapColor.T),
+ TERRACOTTA_CYAN(MaterialMapColor.U),
+ TERRACOTTA_PURPLE(MaterialMapColor.V),
+ TERRACOTTA_BLUE(MaterialMapColor.W),
+ TERRACOTTA_BROWN(MaterialMapColor.X),
+ TERRACOTTA_GREEN(MaterialMapColor.Y),
+ TERRACOTTA_RED(MaterialMapColor.Z),
+ TERRACOTTA_BLACK(MaterialMapColor.aa),
+ CRIMSON_NYLIUM(MaterialMapColor.ab),
+ CRIMSON_STEM(MaterialMapColor.ac),
+ CRIMSON_HYPHAE(MaterialMapColor.ad),
+ WARPED_NYLIUM(MaterialMapColor.ae),
+ WARPED_STEM(MaterialMapColor.af),
+ WARPED_HYPHAE(MaterialMapColor.ag),
+ WARPED_WART_BLOCK(MaterialMapColor.ah);
+
+ private final MaterialMapColor nms;
+
+ MapColours(@Nonnull final MaterialMapColor nms) {
+ this.nms = Objects.requireNonNull(nms);
+ }
+
+ public MaterialMapColor asNMS() {
+ return this.nms;
+ }
+
+ public static void init() {
+ final Set coreMapColours = Set.of(Stream.of(values())
+ .map(MapColours::asNMS)
+ .toArray(MaterialMapColor[]::new));
+ final Set baseMapColours = Set.of(MaterialMapColor.a);
+ final Collection missing = CollectionUtils.disjunction(coreMapColours, baseMapColours);
+ missing.removeIf(Objects::isNull); // Remove all empty colors from baseMapColors
+ if (!missing.isEmpty()) {
+ final CivLogger logger = CivLogger.getLogger(MapColours.class);
+ logger.warning("The following map colours are missing: " + missing.stream()
+ .map(e -> Integer.toString(e.aj))
+ .collect(Collectors.joining(",")));
+ }
+ }
+
+}
From ea28f3a568d7bfb366a49003d7bd4291902fc2e1 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Sun, 25 Apr 2021 14:20:19 +0100
Subject: [PATCH 051/143] Add TaskChain dependency (#80)
---
pom.xml | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/pom.xml b/pom.xml
index 39d74652..ce4ded8e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -46,6 +46,11 @@
adventure-text-minimessage4.1.0-SNAPSHOT
+
+ co.aikar
+ taskchain-bukkit
+ 3.7.2
+ org.apache.commonscommons-lang3
From 73a3d08647102aeb0cd649bc06b5788f1a1fc757 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 26 Apr 2021 17:09:20 +0100
Subject: [PATCH 052/143] Replace PagedGUI with Canvas
---
pom.xml | 9 +
.../org/ipvp/canvas/type/AbstractCivMenu.java | 317 ++++++++++++++++
.../org/ipvp/canvas/type/CivChestMenu.java | 91 +++++
.../org/ipvp/canvas/type/OpenHandler.java | 16 +
.../org/ipvp/canvas/type/UpdateHandler.java | 17 +
.../inventory/gui/canvas/MenuPagination.java | 241 ++++++++++++
.../inventory/gui/canvas/MenuUtils.java | 102 +++++
.../inventorygui/paged/PagedGUI.java | 356 ------------------
.../inventorygui/paged/PagedGUIManager.java | 77 ----
9 files changed, 793 insertions(+), 433 deletions(-)
create mode 100644 src/main/java/org/ipvp/canvas/type/AbstractCivMenu.java
create mode 100644 src/main/java/org/ipvp/canvas/type/CivChestMenu.java
create mode 100644 src/main/java/org/ipvp/canvas/type/OpenHandler.java
create mode 100644 src/main/java/org/ipvp/canvas/type/UpdateHandler.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuPagination.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuUtils.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUI.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUIManager.java
diff --git a/pom.xml b/pom.xml
index ce4ded8e..37d4e139 100644
--- a/pom.xml
+++ b/pom.xml
@@ -51,6 +51,11 @@
taskchain-bukkit3.7.2
+
+ com.github.IPVP-MC
+ canvas
+ 91ec97f076
+ org.apache.commonscommons-lang3
@@ -110,6 +115,10 @@
aikarhttps://repo.aikar.co/content/groups/aikar/
+
+ jitpack.io
+ https://jitpack.io
+
diff --git a/src/main/java/org/ipvp/canvas/type/AbstractCivMenu.java b/src/main/java/org/ipvp/canvas/type/AbstractCivMenu.java
new file mode 100644
index 00000000..73e35e31
--- /dev/null
+++ b/src/main/java/org/ipvp/canvas/type/AbstractCivMenu.java
@@ -0,0 +1,317 @@
+package org.ipvp.canvas.type;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import net.kyori.adventure.text.Component;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.commons.lang3.reflect.MethodUtils;
+import org.bukkit.Bukkit;
+import org.bukkit.entity.Player;
+import org.bukkit.event.inventory.InventoryType;
+import org.bukkit.inventory.Inventory;
+import org.bukkit.inventory.InventoryHolder;
+import org.ipvp.canvas.Menu;
+import org.ipvp.canvas.slot.DefaultSlot;
+import org.ipvp.canvas.slot.Slot;
+import vg.civcraft.mc.civmodcore.chat.ChatUtils;
+import vg.civcraft.mc.civmodcore.inventory.InventoryUtils;
+import vg.civcraft.mc.civmodcore.inventory.gui.canvas.MenuUtils;
+import vg.civcraft.mc.civmodcore.util.NullUtils;
+
+public abstract class AbstractCivMenu extends AbstractMenu {
+
+ private static final Field VIEWERS_FIELD;
+ private static final Field SLOTS_FIELD;
+ private static final Method UPDATE_INV_CONTENTS_METHOD;
+
+ static {
+ VIEWERS_FIELD = FieldUtils.getDeclaredField(AbstractMenu.class, "viewers", true);
+ SLOTS_FIELD = FieldUtils.getDeclaredField(AbstractMenu.class, "slots", true);
+ UPDATE_INV_CONTENTS_METHOD = MethodUtils.getMatchingMethod(AbstractMenu.class,
+ "updateInventoryContents", Player.class, Inventory.class);
+ UPDATE_INV_CONTENTS_METHOD.setAccessible(true);
+ }
+
+ private final Component title;
+ private OpenHandler openHandler;
+ private UpdateHandler updateHandler;
+ protected boolean callCloseHandlerRegardless;
+
+ protected AbstractCivMenu(final Component title,
+ final int slots,
+ final Menu parent,
+ final boolean redraw) {
+ super(null, slots, parent, redraw);
+ if (!InventoryUtils.isValidChestSize(slots)) {
+ throw new IllegalArgumentException("Not a valid chest size.");
+ }
+ this.title = ChatUtils.isNullOrEmpty(title) ? InventoryType.CHEST.defaultTitle() : title;
+ }
+
+ protected AbstractCivMenu(final Component title,
+ final InventoryType type,
+ final Menu parent,
+ final boolean redraw) {
+ super(null, type, parent, redraw);
+ this.title = ChatUtils.isNullOrEmpty(title) ? type.defaultTitle() : title;
+ this.inventorySlots = type.getDefaultSize();
+ }
+
+ /**
+ * @return Returns a clone of this menu's title.
+ */
+ protected Component getTitle() {
+ return ChatUtils.cloneComponent(this.title);
+ }
+
+ /**
+ * @return Retrieves this menu's open event handler.
+ */
+ public Optional getOpenHandler() {
+ return Optional.ofNullable(this.openHandler);
+ }
+
+ /**
+ * Sets the open event handler for this menu. Use
+ * {@link MenuUtils#overrideOpenHandler(AbstractCivMenu, OpenHandler, boolean)} instead if you'd prefer to
+ * override the event handler rather than replace it.
+ *
+ * @param openHandler The open event handler to set for this menu.
+ */
+ public void setOpenHandler(final OpenHandler openHandler) {
+ this.openHandler = openHandler;
+ }
+
+ /**
+ * @return Retrieves this menu's update event handler.
+ */
+ public Optional getUpdateHandler() {
+ return Optional.ofNullable(this.updateHandler);
+ }
+
+ /**
+ * Sets the update event handler for this menu. Use
+ * {@link MenuUtils#overrideUpdateHandler(AbstractCivMenu, UpdateHandler, boolean)} instead if you'd prefer to
+ * override the event handler rather than replace it.
+ *
+ * @param updateHandler The update event handler to set for this menu.
+ */
+ public void setUpdateHandler(final UpdateHandler updateHandler) {
+ this.updateHandler = updateHandler;
+ }
+
+ /**
+ * Sets the close event handler for this menu. Use
+ * {@link MenuUtils#overrideCloseHandler(AbstractCivMenu, CloseHandler, boolean)} instead if you'd prefer to
+ * override the event handler rather than replace it.
+ *
+ * @param closeHandler The close event handler to set for this menu.
+ */
+ @Override
+ public void setCloseHandler(final CloseHandler closeHandler) {
+ super.setCloseHandler(closeHandler);
+ }
+
+ /**
+ * @return Returns whether or not this menu will invoke its close event handler regardless of whether
+ * {@link #closedByPlayer(Player, boolean)}'s second parameter, "triggerCloseHandler", is false.
+ */
+ public boolean isCallingCloseHandlerRegardless() {
+ return this.callCloseHandlerRegardless;
+ }
+
+ /**
+ * @param callCloseHandlerRegardless Set this to true if you want this menu to invoke its close event handler
+ * regardless of whether {@link #closedByPlayer(Player, boolean)}'s second
+ * parameter, "triggerCloseHandler", is false.
+ */
+ public void setCallCloseHandlerRegardless(final boolean callCloseHandlerRegardless) {
+ this.callCloseHandlerRegardless = callCloseHandlerRegardless;
+ }
+
+ /**
+ * @return Returns the total slot count for this menu.
+ */
+ protected int getSlotCount() {
+ return this.inventorySlots;
+ }
+
+ /**
+ * @return Returns the underlying viewers via reflection.
+ */
+ @SuppressWarnings("unchecked")
+ protected final Set getRawViewers() {
+ try {
+ return (Set) FieldUtils.readField(VIEWERS_FIELD, this);
+ }
+ catch (final IllegalAccessException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ /**
+ * @return Returns the underlying slots via reflection.
+ */
+ protected final DefaultSlot[] getRawSlots() {
+ try {
+ return (DefaultSlot[]) FieldUtils.readField(SLOTS_FIELD, this);
+ }
+ catch (final IllegalAccessException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ /**
+ * Switches from this menu to a given menu.
+ *
+ * @param viewer The viewer to switch.
+ * @param otherMenu The other menu to switch to.
+ */
+ public void openOtherMenu(final Player viewer, final AbstractCivMenu otherMenu) {
+ if (otherMenu == null) {
+ viewer.closeInventory();
+ return;
+ }
+ otherMenu.open(viewer);
+ }
+
+ /**
+ * Opens this menu's parent, or closes if it doesn't exist.
+ *
+ * @param viewer The viewer to navigate.
+ */
+ public void openParent(final Player viewer) {
+ final var parent = getParent().orElse(null);
+ if (parent == null) {
+ viewer.closeInventory();
+ return;
+ }
+ if (parent instanceof AbstractCivMenu) {
+ ((AbstractCivMenu) parent).openOtherMenu(viewer, this);
+ return;
+ }
+ parent.open(viewer);
+ }
+
+ /**
+ * Basically a carbon copy of {@link AbstractMenu#closedByPlayer(Player, boolean)}, except
+ * for the additional logic of {@link #callCloseHandlerRegardless} to force the menu to call
+ * the close handler even if {@code triggerCloseHandler} is false.
+ *
+ * @param viewer The closing viewer.
+ * @param triggerCloseHandler Whether to call the close handler, which defers to
+ * {@link #callCloseHandlerRegardless}.
+ */
+ @Override
+ public void closedByPlayer(final Player viewer, final boolean triggerCloseHandler) {
+ final var currentInventory = viewer.getOpenInventory().getTopInventory().getHolder();
+ final var viewers = getRawViewers();
+ if (!(currentInventory instanceof MenuHolder)
+ || !viewers.contains(currentInventory)) {
+ return;
+ }
+ if (triggerCloseHandler || this.callCloseHandlerRegardless) {
+ getCloseHandler().ifPresent(handler -> handler.close(viewer, this));
+ }
+ viewers.remove((MenuHolder) currentInventory);
+ }
+
+ /**
+ * @param viewer The viewer to update this menu for.
+ */
+ @Override
+ public void update(final Player viewer) throws IllegalStateException {
+ if (!isOpen(viewer)) {
+ return;
+ }
+
+ final var currentHolder = viewer.getOpenInventory().getTopInventory().getHolder();
+ final var currentInventory = NullUtils.isNotNull(currentHolder).getInventory();
+
+ for (final Slot slot : getRawSlots()) {
+ currentInventory.setItem(slot.getIndex(), slot.getItem(viewer));
+ }
+
+ getUpdateHandler().ifPresent(handler -> handler.handle(viewer, this));
+ viewer.updateInventory();
+ }
+
+ /**
+ * Basically a carbon copy of {@link AbstractMenu#open(Player)}, which is needed to override the
+ * {@code createInventory()} method, but it's private so the entire function needs to be copied,
+ * alongside its other dependent private methods.
+ */
+ @Override
+ public void open(final Player viewer) {
+ final var currentHolder = viewer.getOpenInventory().getTopInventory().getHolder();
+ final MenuHolder holder;
+ if (currentHolder instanceof MenuHolder) {
+ holder = (MenuHolder) currentHolder;
+ final var currentMenu = holder.getMenu();
+
+ if (currentMenu == this) {
+ return;
+ }
+
+ Inventory inventory;
+ if (isRedraw() && Objects.equals(getDimensions(), currentMenu.getDimensions())) {
+ inventory = holder.getInventory();
+ if (currentMenu instanceof AbstractMenu) {
+ ((AbstractMenu) currentMenu).closedByPlayer(viewer, false);
+ }
+ }
+ else {
+ currentMenu.close(viewer);
+ inventory = createInventory(holder);
+ holder.setInventory(inventory);
+ viewer.openInventory(inventory);
+ }
+
+ updateInventoryContents(viewer, inventory);
+ holder.setMenu(this);
+ }
+ else {
+ // Create new MenuHolder for the player
+ holder = new MenuHolder(viewer, this);
+ final var inventory = createInventory(holder);
+ updateInventoryContents(viewer, inventory);
+ holder.setInventory(inventory);
+ viewer.openInventory(inventory);
+ }
+ getRawViewers().add(holder);
+ getOpenHandler().ifPresent(handler -> handler.handle(viewer, this));
+ }
+
+ /**
+ * Basically a carbon copy of {@link AbstractMenu}'s version, but uses a component title instead.
+ *
+ * @param holder The menu's inventory holder.
+ * @return Returns the new inventory.
+ */
+ protected Inventory createInventory(final InventoryHolder holder) {
+ if (this.inventoryType == null) {
+ return Bukkit.createInventory(holder, this.inventorySlots, this.title);
+ }
+ return Bukkit.createInventory(holder, this.inventoryType, this.title);
+ }
+
+ /**
+ * Invokes {@link AbstractMenu}'s version via reflection.
+ *
+ * @param viewer The viewer to update.
+ * @param inventory The inventory to update.
+ */
+ protected void updateInventoryContents(final Player viewer, final Inventory inventory) {
+ try {
+ UPDATE_INV_CONTENTS_METHOD.invoke(this, viewer, inventory);
+ }
+ catch (final InvocationTargetException | IllegalAccessException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+}
diff --git a/src/main/java/org/ipvp/canvas/type/CivChestMenu.java b/src/main/java/org/ipvp/canvas/type/CivChestMenu.java
new file mode 100644
index 00000000..95252097
--- /dev/null
+++ b/src/main/java/org/ipvp/canvas/type/CivChestMenu.java
@@ -0,0 +1,91 @@
+package org.ipvp.canvas.type;
+
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
+import org.apache.commons.lang3.StringUtils;
+import org.ipvp.canvas.Menu;
+import vg.civcraft.mc.civmodcore.chat.ChatUtils;
+
+public class CivChestMenu extends AbstractCivMenu {
+
+ private Dimension dimension;
+
+ public CivChestMenu(final Component title, final int rows) {
+ this(title, rows, true);
+ }
+
+ public CivChestMenu(final Component title, final int rows, final boolean redraw) {
+ this(title, rows, null, redraw);
+ }
+
+ public CivChestMenu(final Component title, final int rows, final Menu parent, final boolean redraw) {
+ super(title, rows * 9, parent, redraw);
+ }
+
+ /**
+ * @return Return this chest menu's row and column counts.
+ */
+ @Override
+ public Dimension getDimensions() {
+ if (this.dimension == null) {
+ this.dimension = new Dimension(getSlotCount() / 9, 9);
+ }
+ return this.dimension;
+ }
+
+ /**
+ * Returns a new builder.
+ *
+ * @param rows The amount of rows for the inventory to contain
+ * @throws IllegalArgumentException if rows is not between 1 and 6 inclusive
+ */
+ public static Builder builder(final int rows) {
+ if (rows < 1 || rows > 6) {
+ throw new IllegalArgumentException("rows must be a value from 1 to 6");
+ }
+ return new Builder(rows);
+ }
+
+ /**
+ * A builder for creating a CustomChestMenu instance.
+ */
+ public static class Builder extends AbstractMenu.Builder {
+
+ private Component title;
+
+ Builder(final int rows) {
+ super(new Dimension(rows, 9));
+ }
+
+ @Deprecated
+ @Override
+ public Builder title(final String title) {
+ if (StringUtils.isBlank(title)) {
+ this.title = null;
+ return this;
+ }
+ this.title = LegacyComponentSerializer.legacyAmpersand().deserialize(title);
+ if (ChatUtils.isNullOrEmpty(this.title)) {
+ this.title = null;
+ }
+ return this;
+ }
+
+ public Builder title(final Component title) {
+ this.title = title;
+ return this;
+ }
+
+ public Component getComponentTitle() {
+ return this.title;
+ }
+
+ @Override
+ public CivChestMenu build() {
+ return new CivChestMenu(getComponentTitle(),
+ getDimensions().getArea(), getParent(), isRedraw());
+ }
+
+ }
+
+}
diff --git a/src/main/java/org/ipvp/canvas/type/OpenHandler.java b/src/main/java/org/ipvp/canvas/type/OpenHandler.java
new file mode 100644
index 00000000..a845cb52
--- /dev/null
+++ b/src/main/java/org/ipvp/canvas/type/OpenHandler.java
@@ -0,0 +1,16 @@
+package org.ipvp.canvas.type;
+
+import org.bukkit.entity.Player;
+
+@FunctionalInterface
+public interface OpenHandler {
+
+ /**
+ * Is called by {@link AbstractCivMenu} when one of its menus are opened by a viewer.
+ *
+ * @param viewer The viewer of the opened menu.
+ * @param menu The menu being opened.
+ */
+ void handle(Player viewer, AbstractCivMenu menu);
+
+}
diff --git a/src/main/java/org/ipvp/canvas/type/UpdateHandler.java b/src/main/java/org/ipvp/canvas/type/UpdateHandler.java
new file mode 100644
index 00000000..e145b975
--- /dev/null
+++ b/src/main/java/org/ipvp/canvas/type/UpdateHandler.java
@@ -0,0 +1,17 @@
+package org.ipvp.canvas.type;
+
+import org.bukkit.entity.Player;
+
+@FunctionalInterface
+public interface UpdateHandler {
+
+ /**
+ * Is called by {@link AbstractCivMenu} when one of its menus are updated. This is called after the menu has been
+ * updated but before the update packets have been sent to the player.
+ *
+ * @param viewer The viewer of the updating menu.
+ * @param menu The menu being updated.
+ */
+ void handle(Player viewer, AbstractCivMenu menu);
+
+}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuPagination.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuPagination.java
new file mode 100644
index 00000000..78e04292
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuPagination.java
@@ -0,0 +1,241 @@
+package vg.civcraft.mc.civmodcore.inventory.gui.canvas;
+
+import it.unimi.dsi.fastutil.objects.Object2ObjectAVLTreeMap;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import org.apache.commons.collections4.CollectionUtils;
+import org.bukkit.entity.Player;
+import org.ipvp.canvas.slot.SlotSettings;
+import org.ipvp.canvas.type.AbstractCivMenu;
+
+/**
+ * Better version of {@link org.ipvp.canvas.paginate.PaginatedMenuBuilder} as it allows you to apply pagination to an
+ * already existing menu, rather than using a builder to spawn a bunch of new menu instances that'll just be used by a
+ * single player before promptly discarded.
+ */
+public final class MenuPagination {
+
+ private final AbstractCivMenu menu;
+ private final Map playerPages;
+ private final List menuBar;
+ private final ElementSupplier supplier;
+ private final int buttonSlots;
+
+ private MenuPagination(final AbstractCivMenu menu,
+ final ElementSupplier supplier,
+ final List menuBar) {
+ this.menu = Objects.requireNonNull(menu, "Menu cannot be null");
+ final int rows = menu.getDimensions().getRows();
+ if (rows < 2 || rows > 5) {
+ throw new IllegalArgumentException("Row count must be between 2 and 5 inclusively");
+ }
+ this.playerPages = new Object2ObjectAVLTreeMap<>();
+ this.menuBar = List.copyOf(menuBar);
+ if (menuBar.size() > 9) {
+ throw new IllegalArgumentException("Bar cannot contain more than 9 buttons");
+ }
+ this.supplier = Objects.requireNonNull(supplier, "Element supplier cannot be null");
+ this.buttonSlots = (rows * 9) - 9;
+
+ MenuUtils.overrideOpenHandler(menu, (viewer, opened) -> {
+ final var pager = INTERNAL_getPlayerPager(viewer);
+ pager.pageNumber = 0;
+ pager.elements = this.supplier.generate(viewer, opened);
+ INTERNAL_applyPlayerPage(viewer, opened, INTERNAL_getPlayerPager(viewer));
+ }, true);
+
+ MenuUtils.overrideUpdateHandler(menu, (viewer, updated) -> {
+ INTERNAL_applyPlayerPage(viewer, updated, INTERNAL_getPlayerPager(viewer));
+ }, true);
+
+ menu.setCallCloseHandlerRegardless(true);
+ MenuUtils.overrideCloseHandler(menu, (viewer, ignored) -> {
+ this.playerPages.remove(viewer.getUniqueId());
+ }, true);
+
+ for (int i = 0; i < this.buttonSlots; i++) {
+ menu.getSlot(i).setClickHandler((viewer, click) -> {
+ final var pager = INTERNAL_getPlayerPager(viewer);
+ final int buttonIndex = INTERNAL_calculateElementIndex(pager, click.getClickedSlot().getIndex());
+ if (buttonIndex >= pager.elements.size()) {
+ return;
+ }
+ final var handler = pager.elements.get(buttonIndex).getClickHandler();
+ if (handler == null) {
+ return;
+ }
+ handler.click(viewer, click);
+ });
+ }
+
+ for (int i = 0; i < 9; i++) {
+ final var slotIndex = INTERNAL_calculateBarIndex(i);
+ if (i >= this.menuBar.size()) {
+ menu.getSlot(slotIndex).setSettings(MenuUtils.createEmptySlot());
+ break;
+ }
+ final var barElement = this.menuBar.get(i);
+ if (barElement == null) {
+ menu.getSlot(slotIndex).setSettings(MenuUtils.createEmptySlot());
+ continue;
+ }
+ menu.getSlot(slotIndex).setSettings(barElement);
+ }
+ }
+
+ /**
+ * @param viewer The viewer to send to the next page.
+ */
+ public void nextPage(final Player viewer) {
+ final var pager = INTERNAL_getPlayerPager(viewer);
+ pager.pageNumber++;
+ this.menu.update(viewer);
+ }
+
+ /**
+ * @param viewer The viewer to send to the previous page.
+ */
+ public void previousPage(final Player viewer) {
+ final var pager = INTERNAL_getPlayerPager(viewer);
+ pager.pageNumber--;
+ this.menu.update(viewer);
+ }
+
+ /**
+ * @param viewer The viewer to check if they have a next page.
+ * @return Returns whether the viewer has a next page.
+ */
+ public boolean hasNextPage(final Player viewer) {
+ final var pager = INTERNAL_getPlayerPager(viewer);
+ final int elementsSize = CollectionUtils.size(pager.elements);
+ final int totalPages = elementsSize / this.buttonSlots;
+ if (totalPages == 0) {
+ return false;
+ }
+ return pager.pageNumber >= totalPages;
+ }
+
+ /**
+ * @param viewer The viewer to check if they have a previous page.
+ * @return Returns whether the viewer has a previous page.
+ */
+ public boolean hasPreviousPage(final Player viewer) {
+ final var pager = INTERNAL_getPlayerPager(viewer);
+ final int elementsSize = CollectionUtils.size(pager.elements);
+ final int totalPages = elementsSize / this.buttonSlots;
+ if (totalPages == 0) {
+ return false;
+ }
+ return pager.pageNumber < totalPages;
+ }
+
+ protected void INTERNAL_applyPlayerPage(final Player viewer,
+ final AbstractCivMenu menu,
+ final INTERNAL_PlayerPager pager) {
+ pager.pageNumber = Math.max(pager.pageNumber, 0);
+ pager.pageNumber = Math.min(pager.pageNumber, pager.elements.size() / this.buttonSlots);
+ for (int i = 0; i < this.buttonSlots; i++) {
+ final int buttonIndex = INTERNAL_calculateElementIndex(pager, i);
+ if (buttonIndex >= pager.elements.size()) {
+ menu.getSlot(i).setRawItem(viewer, null);
+ continue;
+ }
+ final var template = pager.elements.get(buttonIndex).getItemTemplate();
+ if (template == null) {
+ menu.getSlot(i).setRawItem(viewer, null);
+ continue;
+ }
+ menu.getSlot(i).setRawItem(viewer, template.getItem(viewer));
+ }
+ }
+
+ protected INTERNAL_PlayerPager INTERNAL_getPlayerPager(final Player viewer) {
+ return this.playerPages.computeIfAbsent(viewer.getUniqueId(), (uuid) -> new INTERNAL_PlayerPager());
+ }
+
+ protected int INTERNAL_calculateElementIndex(final INTERNAL_PlayerPager pager, final int slot) {
+ return (pager.pageNumber * this.buttonSlots) + slot;
+ }
+
+ protected int INTERNAL_calculateBarIndex(final int slot) {
+ return this.buttonSlots + slot;
+ }
+
+ protected static class INTERNAL_PlayerPager {
+ private int pageNumber;
+ private List elements;
+ }
+
+ @FunctionalInterface
+ public interface ElementSupplier {
+ List generate(Player viewer, AbstractCivMenu menu);
+ }
+
+ /**
+ * @return Returns a new pagination builder.
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static class Builder {
+
+ private AbstractCivMenu menu;
+ private ElementSupplier supplier;
+ private final SlotSettings[] menuBar;
+
+ Builder() {
+ this.menuBar = new SlotSettings[] {
+ MenuUtils.createEmptySlot(),
+ MenuUtils.createEmptySlot(),
+ MenuUtils.createEmptySlot(),
+ MenuUtils.createEmptySlot(),
+ MenuUtils.createEmptySlot(),
+ MenuUtils.createEmptySlot(),
+ MenuUtils.createEmptySlot(),
+ MenuUtils.createEmptySlot(),
+ MenuUtils.createEmptySlot()
+ };
+ }
+
+ /**
+ * @param menu The menu to paginate.
+ * @return Returns this builder.
+ */
+ public Builder setMenu(final AbstractCivMenu menu) {
+ this.menu = menu;
+ return this;
+ }
+
+ /**
+ * @param supplier Supplier method to return all the elements to be paginated.
+ * @return Returns this builder.
+ */
+ public Builder setElementSupplier(final ElementSupplier supplier) {
+ this.supplier = supplier;
+ return this;
+ }
+
+ /**
+ * @param index The index of the menu bar element from 0-8 inclusively.
+ * @param element The menu bar element to add.
+ * @return Returns this builder.
+ */
+ public Builder setMenuBarElement(final int index, final SlotSettings element) {
+ this.menuBar[index] = element == null ? MenuUtils.createEmptySlot() : element;
+ return this;
+ }
+
+ /**
+ * @return Returns a constructed menu pagination based on this builder.
+ */
+ public MenuPagination build() {
+ return new MenuPagination(this.menu, this.supplier, Arrays.asList(this.menuBar));
+ }
+
+ }
+
+}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuUtils.java
new file mode 100644
index 00000000..6d7b57cb
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuUtils.java
@@ -0,0 +1,102 @@
+package vg.civcraft.mc.civmodcore.inventory.gui.canvas;
+
+import org.ipvp.canvas.Menu;
+import org.ipvp.canvas.slot.SlotSettings;
+import org.ipvp.canvas.type.AbstractCivMenu;
+import org.ipvp.canvas.type.OpenHandler;
+import org.ipvp.canvas.type.UpdateHandler;
+
+public final class MenuUtils {
+
+ /**
+ * @return Returns an empty, unmodifiable slot.
+ */
+ public static SlotSettings createEmptySlot() {
+ return SlotSettings.builder().build();
+ }
+
+ /**
+ * Overrides a given menu's open event handler, in lieu of just replacing it, meaning that you can add handlers to
+ * a menu without fear of removing any previously added functionality.
+ *
+ * @param menu The menu to add the handler for.
+ * @param handler The handler to add.
+ * @param callSuperBefore Whether or not to call the existing handler before or after the given handler.
+ */
+ public static void overrideOpenHandler(final AbstractCivMenu menu,
+ final OpenHandler handler,
+ final boolean callSuperBefore) {
+ final var findExisting = menu.getOpenHandler();
+ if (findExisting.isEmpty()) {
+ menu.setOpenHandler(handler);
+ return;
+ }
+ final var existing = findExisting.get();
+ menu.setOpenHandler((viewer, openedMenu) -> {
+ if (callSuperBefore) {
+ existing.handle(viewer, openedMenu);
+ }
+ handler.handle(viewer, openedMenu);
+ if (!callSuperBefore) {
+ existing.handle(viewer, openedMenu);
+ }
+ });
+ }
+
+ /**
+ * Overrides a given menu's update event handler, in lieu of just replacing it, meaning that you can add handlers
+ * to a menu without fear of removing any previously added functionality.
+ *
+ * @param menu The menu to add the handler for.
+ * @param handler The handler to add.
+ * @param callSuperBefore Whether or not to call the existing handler before or after the given handler.
+ */
+ public static void overrideUpdateHandler(final AbstractCivMenu menu,
+ final UpdateHandler handler,
+ final boolean callSuperBefore) {
+ final var findExisting = menu.getUpdateHandler();
+ if (findExisting.isEmpty()) {
+ menu.setUpdateHandler(handler);
+ return;
+ }
+ final var existing = findExisting.get();
+ menu.setUpdateHandler((viewer, openedMenu) -> {
+ if (callSuperBefore) {
+ existing.handle(viewer, openedMenu);
+ }
+ handler.handle(viewer, openedMenu);
+ if (!callSuperBefore) {
+ existing.handle(viewer, openedMenu);
+ }
+ });
+ }
+
+ /**
+ * Overrides a given menu's close event handler, in lieu of just replacing it, meaning that you can add handlers to
+ * a menu without fear of removing any previously added functionality.
+ *
+ * @param menu The menu to add the handler for.
+ * @param handler The handler to add.
+ * @param callSuperBefore Whether or not to call the existing handler before or after the given handler.
+ */
+ public static void overrideCloseHandler(final AbstractCivMenu menu,
+ final Menu.CloseHandler handler,
+ final boolean callSuperBefore) {
+ final var findExisting = menu.getCloseHandler();
+ if (findExisting.isEmpty()) {
+ menu.setCloseHandler(handler);
+ return;
+ }
+ final var existing = findExisting.get();
+ menu.setCloseHandler((viewer, openedMenu) -> {
+ if (callSuperBefore) {
+ existing.close(viewer, openedMenu);
+ }
+ handler.close(viewer, openedMenu);
+ if (!callSuperBefore) {
+ existing.close(viewer, openedMenu);
+ }
+ });
+ }
+
+}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUI.java b/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUI.java
deleted file mode 100644
index a53d3f50..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUI.java
+++ /dev/null
@@ -1,356 +0,0 @@
-package vg.civcraft.mc.civmodcore.inventorygui.paged;
-
-import com.google.common.base.Preconditions;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Objects;
-import java.util.Set;
-import java.util.Stack;
-import java.util.UUID;
-import org.bukkit.Bukkit;
-import org.bukkit.entity.Player;
-import org.bukkit.event.inventory.ClickType;
-import org.bukkit.event.inventory.InventoryClickEvent;
-import org.bukkit.inventory.Inventory;
-import org.bukkit.inventory.InventoryView;
-import org.bukkit.inventory.ItemStack;
-import org.bukkit.scheduler.BukkitTask;
-import vg.civcraft.mc.civmodcore.CivModCorePlugin;
-import vg.civcraft.mc.civmodcore.inventory.InventoryUtils;
-import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils;
-import vg.civcraft.mc.civmodcore.inventorygui.ClickableInventory;
-import vg.civcraft.mc.civmodcore.inventorygui.IClickable;
-
-/**
- * Class that represents a proverbial slideshow of pages that can be switched to efficiently.
- *
- * You could also use {@link vg.civcraft.mc.civmodcore.inventorygui.MultiPageView}
- */
-public final class PagedGUI {
-
- private final int slots;
-
- private final UUID uuid;
-
- private final ClickableInventory inventory;
-
- private final Stack history;
-
- private Page currentPage;
-
- /**
- * Creates a paged GUI based on an amount of slots and a name.
- *
- * @param slots The amount of slots, which must pass a {@link InventoryUtils#isValidChestSize(int)} test.
- * @param name The name for the GUI, which should be relevant across each page as it cannot be changed.
- */
- public PagedGUI(int slots, String name) {
- Preconditions.checkArgument(InventoryUtils.isValidChestSize(slots));
- this.slots = slots;
- this.uuid = UUID.randomUUID();
- this.inventory = new LegacyInventory(slots, name);
- this.history = new Stack<>();
- this.currentPage = null;
- }
-
- /**
- * Resets the paged GUI if there's one or fewer viewers.
- *
- * @return Returns true if the paged GUI was reset.
- */
- public boolean reset() {
- if (InventoryUtils.hasOtherViewers(this.inventory.getInventory())) {
- return false;
- }
- InventoryUtils.clearInventory(this.inventory.getInventory());
- this.history.clear();
- this.currentPage = null;
- return true;
- }
-
- /**
- *
Creates a new page to be used for this paged GUI.
- *
- *
Note: The returned page will be forever bound to this paged GUI, do not try to use it for another.
- *
- * @return Returns a new page for this GUI.
- */
- public Page createPage() {
- return new Page();
- }
-
- /**
- * Presents this paged GUI to a player.
- *
- * @param player The player to present this paged GUI to.
- * @return Returns true if the player was successfully presented with this paged GUI.
- */
- public boolean showGUI(Player player) {
- Preconditions.checkArgument(player != null);
- InventoryView view = player.openInventory(getInventory());
- if (view == null) {
- return false;
- }
- PagedGUIManager.GUIs.put(getInventory(), this);
- return true;
- }
-
- /**
- *
Handler for when this paged GUI has been clicked.
- *
- *
Note: Only {@link PagedGUIManager#onInventoryClick(InventoryClickEvent)} should call this method.
- *
- * @param slot The slot of the button that has been clicked.
- * @param clicker The player who clicked the button.
- */
- void clicked(int slot, Player clicker, ClickType clickType) {
- if (this.currentPage == null) {
- return;
- }
- IClickable button = this.currentPage.getButton(slot);
- if (button == null) {
- return;
- }
- button.handleClick(clicker, clickType);
- }
-
- /**
- * @return Returns how many slots this GUI has.
- */
- public int getSlotCount() {
- return this.slots;
- }
-
- /**
- * @return Returns the underlying inventory storing the items representing buttons.
- */
- public Inventory getInventory() {
- return this.inventory.getInventory();
- }
-
- /**
- * Clears this GUI's page lineage, making the current page the root page.
- */
- public void clearPageLineage() {
- this.history.clear();
- }
-
- /**
- * Gets the current page.
- *
- * @return Returns the current page, which may be null.
- */
- public Page getCurrentPage() {
- return this.currentPage;
- }
-
- /**
- * Sets the current page. Will add the previous current page to the lineage.
- *
- * @param page The page to set, which cannot be null.
- */
- public void setCurrentPage(Page page) {
- setCurrentPage(page, true);
- }
-
- /**
- * Sets the current page.
- *
- * @param page The page to set, which cannot be null.
- * @param addPreviousToHistory If true will add the previous current page to the lineage.
- */
- public void setCurrentPage(Page page, boolean addPreviousToHistory) {
- Preconditions.checkArgument(page != null && page.getGUI() == this);
- Page previousPage = this.currentPage;
- if (previousPage == page) {
- return;
- }
- this.currentPage = page;
- if (previousPage != null) {
- if (addPreviousToHistory) {
- this.history.push(previousPage);
- }
- previousPage.hidden();
- }
- page.showGUI();
- updateGUI();
- }
-
- /**
- * Goes to the previous page within the lineage. If no lineage can be found then the GUI is emptied.
- */
- public void goToPreviousPage() {
- if (!this.history.isEmpty()) {
- Page page = this.history.pop();
- if (page != null) {
- setCurrentPage(page, false);
- return;
- }
- }
- this.currentPage = null;
- InventoryUtils.clearInventory(this.inventory.getInventory());
- updateGUI();
- }
-
- private void updateGUI() {
- Bukkit.getScheduler().scheduleSyncDelayedTask(CivModCorePlugin.getInstance(), this.inventory::updateInventory);
- }
-
- @Override
- public boolean equals(Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof PagedGUI)) {
- return false;
- }
- if (hashCode() != other.hashCode()) {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(this.uuid, this.inventory);
- }
-
- /**
- * Class that represents a page of a gui, a proverbial slide of a slideshow.
- */
- public final class Page {
-
- private final IClickable[] items;
-
- private final Set tasks;
-
- private Page() {
- this.items = new IClickable[slots];
- this.tasks = new HashSet<>();
- }
-
- private void showGUI() {
- for (int i = 0; i < slots; i++) {
- IClickable clickable = this.items[i];
- if (clickable == null) {
- inventory.setItem(null, i);
- continue;
- }
- ItemStack button = clickable.getItemStack();
- if (!ItemUtils.isValidItem(button)) {
- inventory.setItem(null, i);
- continue;
- }
- inventory.setItem(button, i);
- clickable.addedToInventory(inventory, i);
- }
- }
-
- private void hidden() {
- this.tasks.forEach(BukkitTask::cancel);
- this.tasks.clear();
- }
-
- /**
- * Resets this page to if it had just been created.
- */
- public void reset() {
- Arrays.fill(this.items, null);
- hidden();
- }
-
- /**
- * Gets the particular GUI this page is bound to. Do not attempt to use this page for another GUI, it will fail.
- *
- * @return Returns the GUI this page is bound to.
- */
- public PagedGUI getGUI() {
- return PagedGUI.this;
- }
-
- /**
- * Checks whether this page is currently being displayed.
- *
- * @return Returns true if this page is currently being displayed.
- */
- public boolean isCurrentPage() {
- return currentPage == this;
- }
-
- /**
- * Gets a button (a clickable) for a particular index.
- *
- * @param index The index to get the button for.
- * @return Returns the button at the given index, or null.
- */
- public IClickable getButton(int index) {
- return this.items[index];
- }
-
- /**
- * Sets a button (a clickable) to a particular index.
- *
- * @param index The index to save the button to.
- * @param button The button to save.
- */
- public void setButton(int index, IClickable button) {
- this.items[index] = button;
- }
-
- /**
- * Adds a task to this page. This feature pretty much exists to support
- * {@link vg.civcraft.mc.civmodcore.inventorygui.AnimatedClickable AnimatedClickable}.
- *
- * @param task The task to add.
- */
- public void addTask(BukkitTask task) {
- Preconditions.checkArgument(task != null);
- Preconditions.checkArgument(!task.isCancelled());
- Preconditions.checkArgument(task.isSync());
- this.tasks.add(task);
- }
-
- /**
- * Removes a task from the page and will be cancelled in the process.
- *
- * @param task The task to remove and cancel.
- */
- public void removeTask(BukkitTask task) {
- Preconditions.checkArgument(task != null);
- task.cancel();
- this.tasks.remove(task);
- }
-
- }
-
- /**
- * This class is just a ClickableInventory to
- */
- public class LegacyInventory extends ClickableInventory {
-
- public LegacyInventory(int size, String name) {
- super(size, name);
- }
-
- @Override
- public void registerTask(BukkitTask task) {
- Preconditions.checkArgument(currentPage != null);
- currentPage.addTask(task);
- }
-
- @Override
- @Deprecated
- public void showInventory(Player p) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void updateInventory() {
- for (Player viewer : InventoryUtils.getViewingPlayers(getInventory())) {
- viewer.updateInventory();
- }
- }
-
- }
-
-}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUIManager.java b/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUIManager.java
deleted file mode 100644
index 3d53d50d..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUIManager.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package vg.civcraft.mc.civmodcore.inventorygui.paged;
-
-import java.util.HashMap;
-import java.util.Map;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.inventory.InventoryClickEvent;
-import org.bukkit.event.inventory.InventoryCloseEvent;
-import org.bukkit.inventory.Inventory;
-import vg.civcraft.mc.civmodcore.entities.EntityUtils;
-import vg.civcraft.mc.civmodcore.inventory.InventoryUtils;
-
-public final class PagedGUIManager implements Listener {
-
- static final Map GUIs = new HashMap<>();
-
- public static void closeAllGUIs() {
- for (Map.Entry entry : GUIs.entrySet()) {
- for (Player player : InventoryUtils.getViewingPlayers(entry.getKey())) {
- player.closeInventory();
- }
- entry.getValue().reset();
- }
- GUIs.clear();
- }
-
- @EventHandler
- public void onInventoryClose(InventoryCloseEvent event) {
- GUIs.computeIfPresent(event.getInventory(), (k, gui) -> gui.reset() ? null : gui);
- }
-
- @EventHandler
- public void onInventoryClick(InventoryClickEvent event) {
- if (!EntityUtils.isPlayer(event.getWhoClicked())) {
- return;
- }
- Player viewer = (Player) event.getWhoClicked();
- PagedGUI gui = GUIs.get(event.getInventory());
- if (gui == null) {
- return;
- }
- switch (event.getAction()) {
- // Disable unknown actions
- default:
- case UNKNOWN:
- // These events are cursed. There's no way to know where the items are moving to or from, just cancel.
- case COLLECT_TO_CURSOR:
- case MOVE_TO_OTHER_INVENTORY:
- event.setCancelled(true);
- return;
- // Leave these be as they aren't dangerous. Cloning a stack is an OP feature and clones to your cursor
- case NOTHING:
- case CLONE_STACK:
- return;
- // Allow the following in context to the player's inventory, but not when interacting with the GUI
- case PICKUP_ONE:
- case PICKUP_SOME:
- case PICKUP_HALF:
- case PICKUP_ALL:
- case PLACE_ONE:
- case PLACE_SOME:
- case PLACE_ALL:
- case SWAP_WITH_CURSOR:
- case DROP_ONE_SLOT:
- case DROP_ALL_SLOT:
- case DROP_ONE_CURSOR:
- case DROP_ALL_CURSOR:
- case HOTBAR_MOVE_AND_READD:
- case HOTBAR_SWAP: {
- event.setCancelled(true);
- gui.clicked(event.getSlot(), viewer, event.getClick());
- }
- }
- }
-
-}
From e6ca8d4fc20faddcb364db9fc50b010f79a0f0ba Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 26 Apr 2021 21:28:18 +0100
Subject: [PATCH 053/143] Remove extraneous PagedGUI hooks
---
src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java | 2 --
1 file changed, 2 deletions(-)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
index d0807d1f..309cab56 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
@@ -16,7 +16,6 @@
import vg.civcraft.mc.civmodcore.inventory.items.SpawnEggUtils;
import vg.civcraft.mc.civmodcore.inventory.items.TreeTypeUtils;
import vg.civcraft.mc.civmodcore.inventorygui.ClickableInventoryListener;
-import vg.civcraft.mc.civmodcore.inventorygui.paged.PagedGUIManager;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.GlobalChunkMetaManager;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.api.ChunkMetaAPI;
import vg.civcraft.mc.civmodcore.locations.global.CMCWorldDAO;
@@ -80,7 +79,6 @@ public void onEnable() {
ScoreBoardAPI.setDefaultHeader(scoreboardHeader);
// Register listeners
registerListener(new ClickableInventoryListener());
- registerListener(new PagedGUIManager());
registerListener(DialogManager.INSTANCE);
registerListener(new ScoreBoardListener());
registerListener(new CustomEventMapper());
From 420cfabcc3013b9c161c763958d88ea2606367a1 Mon Sep 17 00:00:00 2001
From: Alexander
Date: Mon, 26 Apr 2021 21:29:04 +0100
Subject: [PATCH 054/143] Make certain dependencies pseudo-provided
---
pom.xml | 47 ++++++++++++++++++++++++++++++++---------------
1 file changed, 32 insertions(+), 15 deletions(-)
diff --git a/pom.xml b/pom.xml
index 37d4e139..306cd222 100644
--- a/pom.xml
+++ b/pom.xml
@@ -26,6 +26,28 @@
-proc:none
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+ 3.2.4
+
+
+ package
+
+ shade
+
+
+
+
+
+ it.unimi.dsi:fastutil
+ co.aikar:cleaner
+
+
+
+
+
+
@@ -46,6 +68,11 @@
adventure-text-minimessage4.1.0-SNAPSHOT
+
+ co.aikar
+ acf-bukkit
+ 0.5.0-SNAPSHOT
+ co.aikartaskchain-bukkit
@@ -66,20 +93,6 @@
commons-collections44.4
-
-
- org.slf4j
- slf4j-api
- 1.7.26
-
-
- co.aikar
- acf-bukkit
- 0.5.0-SNAPSHOT
- org.jetbrainsannotations
@@ -95,7 +108,11 @@
it.unimi.dsifastutil8.2.2
- provided
+
+
+ co.aikar
+ cleaner
+ 1.0-SNAPSHOT
From f1993e42678a48bdd7a1a185186f7c38627c4d0e Mon Sep 17 00:00:00 2001
From: wingzero54
Date: Thu, 29 Apr 2021 09:54:44 -0500
Subject: [PATCH 055/143] Revert "Chat / Item / Meta utilities update"
---
pom.xml | 80 +-
.../org/ipvp/canvas/type/AbstractCivMenu.java | 317 ------
.../org/ipvp/canvas/type/CivChestMenu.java | 91 --
.../org/ipvp/canvas/type/OpenHandler.java | 16 -
.../org/ipvp/canvas/type/UpdateHandler.java | 17 -
.../vg/civcraft/mc/civmodcore/ACivMod.java | 39 +-
.../mc/civmodcore/CivModCorePlugin.java | 37 +-
.../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 +
.../mc/civmodcore/chat/ChatUtils.java | 81 +-
.../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 +
.../command/AikarCommandManager.java | 53 +-
.../mc/civmodcore/command/MailBoxAPI.java | 56 ++
.../merchant/CustomBukkitMerchant.java | 61 --
.../entities/merchant/CustomNMSMerchant.java | 109 ---
.../civmodcore/inventory/ClonedInventory.java | 16 +-
.../civmodcore/inventory/InventoryUtils.java | 9 +-
.../inventory/gui/canvas/MenuPagination.java | 241 -----
.../inventory/gui/canvas/MenuUtils.java | 102 --
.../inventory/items/EnchantUtils.java | 20 +-
.../civmodcore/inventory/items/ItemUtils.java | 390 ++------
.../civmodcore/inventory/items/MetaUtils.java | 260 +----
.../civmodcore/inventory/items/MoreTags.java | 6 +-
.../inventory/items/PotionUtils.java | 7 +-
.../inventory/items/SpawnEggUtils.java | 136 ++-
.../inventory/items/TreeTypeUtils.java | 7 +-
.../inventorygui/paged/PagedGUI.java | 356 +++++++
.../inventorygui/paged/PagedGUIManager.java | 77 ++
.../mc/civmodcore/itemHandling/ItemMap.java | 3 +-
.../mc/civmodcore/maps/MapColours.java | 103 --
.../impl/collection/ListSetting.java | 2 +-
.../mc/civmodcore/serialization/NBTCache.java | 20 +
.../civmodcore/serialization/NBTCompound.java | 77 +-
.../serialization/NBTCompoundList.java | 79 ++
.../civmodcore/serialization/NBTHelper.java | 74 --
.../storage/nbt/BatchedNbtStorage.java | 124 ---
.../mc/civmodcore/util/CivLogger.java | 57 --
.../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 ++++
.../civmodcore/util/MoreCollectionUtils.java | 32 +-
.../mc/civmodcore/util/NullCoalescing.java | 185 ++++
.../mc/civmodcore/util/Resettable.java | 18 -
.../civcraft/mc/civmodcore/util/TextUtil.java | 170 +++-
.../mc/civmodcore/util/UuidUtils.java | 18 -
.../mc/civmodcore/world/WorldUtils.java | 2 +-
src/main/resources/materials.yml | 1 -
.../java/org/bukkit/pseudo/PseudoServer.java | 914 ------------------
.../civcraft/mc/civmodcore/enums/Tester.java | 25 +
.../mc/civmodcore/items/ItemMetaTests.java | 65 --
.../serialization/ExampleSerializable.java | 14 +-
.../{SerializationTests.java => Tester.java} | 60 +-
.../mc/civmodcore/text/TextTests.java | 40 -
.../uuid/{UuidTests.java => Tester.java} | 2 +-
76 files changed, 5476 insertions(+), 3338 deletions(-)
delete mode 100644 src/main/java/org/ipvp/canvas/type/AbstractCivMenu.java
delete mode 100644 src/main/java/org/ipvp/canvas/type/CivChestMenu.java
delete mode 100644 src/main/java/org/ipvp/canvas/type/OpenHandler.java
delete mode 100644 src/main/java/org/ipvp/canvas/type/UpdateHandler.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/BlockAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/ColourAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/EnchantAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/EnchantNames.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/EntityAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/InventoryAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/ItemAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/ItemNames.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/LocationAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/MaterialAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/NamespaceAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/PotionAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/PotionNames.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/RecipeAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/SpawnEggAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/ToolAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/TreeTypeAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/WorldAPI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/api/package-info.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/chatDialog/ChatListener.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/chatDialog/Dialog.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/chatDialog/DialogManager.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/chatDialog/LDialog.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/chatDialog/package-info.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/command/MailBoxAPI.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomBukkitMerchant.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuPagination.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuUtils.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUI.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUIManager.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/maps/MapColours.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCache.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompoundList.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/storage/nbt/BatchedNbtStorage.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/EnumUtils.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/Guard.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/Iteration.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/MapUtils.java
create mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/NullCoalescing.java
delete mode 100644 src/main/java/vg/civcraft/mc/civmodcore/util/Resettable.java
delete mode 100644 src/test/java/org/bukkit/pseudo/PseudoServer.java
create mode 100644 src/test/java/vg/civcraft/mc/civmodcore/enums/Tester.java
delete mode 100644 src/test/java/vg/civcraft/mc/civmodcore/items/ItemMetaTests.java
rename src/test/java/vg/civcraft/mc/civmodcore/serialization/{SerializationTests.java => Tester.java} (78%)
delete mode 100644 src/test/java/vg/civcraft/mc/civmodcore/text/TextTests.java
rename src/test/java/vg/civcraft/mc/civmodcore/uuid/{UuidTests.java => Tester.java} (94%)
diff --git a/pom.xml b/pom.xml
index 306cd222..addbae0d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -20,34 +20,11 @@
org.apache.maven.pluginsmaven-compiler-plugin
- 3.8.1-proc:none
-
- org.apache.maven.plugins
- maven-shade-plugin
- 3.2.4
-
-
- package
-
- shade
-
-
-
-
-
- it.unimi.dsi:fastutil
- co.aikar:cleaner
-
-
-
-
-
-
@@ -55,7 +32,7 @@
com.destroystokyo.paperpaper
- 1.16.5-R0.1-SNAPSHOT
+ 1.16.4-R0.1-SNAPSHOTprovided
@@ -63,26 +40,6 @@
HikariCP3.4.2
-
- net.kyori
- adventure-text-minimessage
- 4.1.0-SNAPSHOT
-
-
- co.aikar
- acf-bukkit
- 0.5.0-SNAPSHOT
-
-
- co.aikar
- taskchain-bukkit
- 3.7.2
-
-
- com.github.IPVP-MC
- canvas
- 91ec97f076
- org.apache.commonscommons-lang3
@@ -93,6 +50,20 @@
commons-collections44.4
+
+
+ org.slf4j
+ slf4j-api
+ 1.7.26
+
+
+ co.aikar
+ acf-bukkit
+ 0.5.0-SNAPSHOT
+ org.jetbrainsannotations
@@ -103,38 +74,23 @@
jsr3053.0.2
-
-
- it.unimi.dsi
- fastutil
- 8.2.2
-
-
- co.aikar
- cleaner
- 1.0-SNAPSHOT
- junitjunit
- 4.13.2
+ 4.13test
-
- civ-github-repo
- https://raw.githubusercontent.com/CivClassic/artifacts/master/
- aikarhttps://repo.aikar.co/content/groups/aikar/
- jitpack.io
- https://jitpack.io
+ civ-github-repo
+ https://raw.githubusercontent.com/CivClassic/artifacts/master/
diff --git a/src/main/java/org/ipvp/canvas/type/AbstractCivMenu.java b/src/main/java/org/ipvp/canvas/type/AbstractCivMenu.java
deleted file mode 100644
index 73e35e31..00000000
--- a/src/main/java/org/ipvp/canvas/type/AbstractCivMenu.java
+++ /dev/null
@@ -1,317 +0,0 @@
-package org.ipvp.canvas.type;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import net.kyori.adventure.text.Component;
-import org.apache.commons.lang3.reflect.FieldUtils;
-import org.apache.commons.lang3.reflect.MethodUtils;
-import org.bukkit.Bukkit;
-import org.bukkit.entity.Player;
-import org.bukkit.event.inventory.InventoryType;
-import org.bukkit.inventory.Inventory;
-import org.bukkit.inventory.InventoryHolder;
-import org.ipvp.canvas.Menu;
-import org.ipvp.canvas.slot.DefaultSlot;
-import org.ipvp.canvas.slot.Slot;
-import vg.civcraft.mc.civmodcore.chat.ChatUtils;
-import vg.civcraft.mc.civmodcore.inventory.InventoryUtils;
-import vg.civcraft.mc.civmodcore.inventory.gui.canvas.MenuUtils;
-import vg.civcraft.mc.civmodcore.util.NullUtils;
-
-public abstract class AbstractCivMenu extends AbstractMenu {
-
- private static final Field VIEWERS_FIELD;
- private static final Field SLOTS_FIELD;
- private static final Method UPDATE_INV_CONTENTS_METHOD;
-
- static {
- VIEWERS_FIELD = FieldUtils.getDeclaredField(AbstractMenu.class, "viewers", true);
- SLOTS_FIELD = FieldUtils.getDeclaredField(AbstractMenu.class, "slots", true);
- UPDATE_INV_CONTENTS_METHOD = MethodUtils.getMatchingMethod(AbstractMenu.class,
- "updateInventoryContents", Player.class, Inventory.class);
- UPDATE_INV_CONTENTS_METHOD.setAccessible(true);
- }
-
- private final Component title;
- private OpenHandler openHandler;
- private UpdateHandler updateHandler;
- protected boolean callCloseHandlerRegardless;
-
- protected AbstractCivMenu(final Component title,
- final int slots,
- final Menu parent,
- final boolean redraw) {
- super(null, slots, parent, redraw);
- if (!InventoryUtils.isValidChestSize(slots)) {
- throw new IllegalArgumentException("Not a valid chest size.");
- }
- this.title = ChatUtils.isNullOrEmpty(title) ? InventoryType.CHEST.defaultTitle() : title;
- }
-
- protected AbstractCivMenu(final Component title,
- final InventoryType type,
- final Menu parent,
- final boolean redraw) {
- super(null, type, parent, redraw);
- this.title = ChatUtils.isNullOrEmpty(title) ? type.defaultTitle() : title;
- this.inventorySlots = type.getDefaultSize();
- }
-
- /**
- * @return Returns a clone of this menu's title.
- */
- protected Component getTitle() {
- return ChatUtils.cloneComponent(this.title);
- }
-
- /**
- * @return Retrieves this menu's open event handler.
- */
- public Optional getOpenHandler() {
- return Optional.ofNullable(this.openHandler);
- }
-
- /**
- * Sets the open event handler for this menu. Use
- * {@link MenuUtils#overrideOpenHandler(AbstractCivMenu, OpenHandler, boolean)} instead if you'd prefer to
- * override the event handler rather than replace it.
- *
- * @param openHandler The open event handler to set for this menu.
- */
- public void setOpenHandler(final OpenHandler openHandler) {
- this.openHandler = openHandler;
- }
-
- /**
- * @return Retrieves this menu's update event handler.
- */
- public Optional getUpdateHandler() {
- return Optional.ofNullable(this.updateHandler);
- }
-
- /**
- * Sets the update event handler for this menu. Use
- * {@link MenuUtils#overrideUpdateHandler(AbstractCivMenu, UpdateHandler, boolean)} instead if you'd prefer to
- * override the event handler rather than replace it.
- *
- * @param updateHandler The update event handler to set for this menu.
- */
- public void setUpdateHandler(final UpdateHandler updateHandler) {
- this.updateHandler = updateHandler;
- }
-
- /**
- * Sets the close event handler for this menu. Use
- * {@link MenuUtils#overrideCloseHandler(AbstractCivMenu, CloseHandler, boolean)} instead if you'd prefer to
- * override the event handler rather than replace it.
- *
- * @param closeHandler The close event handler to set for this menu.
- */
- @Override
- public void setCloseHandler(final CloseHandler closeHandler) {
- super.setCloseHandler(closeHandler);
- }
-
- /**
- * @return Returns whether or not this menu will invoke its close event handler regardless of whether
- * {@link #closedByPlayer(Player, boolean)}'s second parameter, "triggerCloseHandler", is false.
- */
- public boolean isCallingCloseHandlerRegardless() {
- return this.callCloseHandlerRegardless;
- }
-
- /**
- * @param callCloseHandlerRegardless Set this to true if you want this menu to invoke its close event handler
- * regardless of whether {@link #closedByPlayer(Player, boolean)}'s second
- * parameter, "triggerCloseHandler", is false.
- */
- public void setCallCloseHandlerRegardless(final boolean callCloseHandlerRegardless) {
- this.callCloseHandlerRegardless = callCloseHandlerRegardless;
- }
-
- /**
- * @return Returns the total slot count for this menu.
- */
- protected int getSlotCount() {
- return this.inventorySlots;
- }
-
- /**
- * @return Returns the underlying viewers via reflection.
- */
- @SuppressWarnings("unchecked")
- protected final Set getRawViewers() {
- try {
- return (Set) FieldUtils.readField(VIEWERS_FIELD, this);
- }
- catch (final IllegalAccessException exception) {
- throw new RuntimeException(exception);
- }
- }
-
- /**
- * @return Returns the underlying slots via reflection.
- */
- protected final DefaultSlot[] getRawSlots() {
- try {
- return (DefaultSlot[]) FieldUtils.readField(SLOTS_FIELD, this);
- }
- catch (final IllegalAccessException exception) {
- throw new RuntimeException(exception);
- }
- }
-
- /**
- * Switches from this menu to a given menu.
- *
- * @param viewer The viewer to switch.
- * @param otherMenu The other menu to switch to.
- */
- public void openOtherMenu(final Player viewer, final AbstractCivMenu otherMenu) {
- if (otherMenu == null) {
- viewer.closeInventory();
- return;
- }
- otherMenu.open(viewer);
- }
-
- /**
- * Opens this menu's parent, or closes if it doesn't exist.
- *
- * @param viewer The viewer to navigate.
- */
- public void openParent(final Player viewer) {
- final var parent = getParent().orElse(null);
- if (parent == null) {
- viewer.closeInventory();
- return;
- }
- if (parent instanceof AbstractCivMenu) {
- ((AbstractCivMenu) parent).openOtherMenu(viewer, this);
- return;
- }
- parent.open(viewer);
- }
-
- /**
- * Basically a carbon copy of {@link AbstractMenu#closedByPlayer(Player, boolean)}, except
- * for the additional logic of {@link #callCloseHandlerRegardless} to force the menu to call
- * the close handler even if {@code triggerCloseHandler} is false.
- *
- * @param viewer The closing viewer.
- * @param triggerCloseHandler Whether to call the close handler, which defers to
- * {@link #callCloseHandlerRegardless}.
- */
- @Override
- public void closedByPlayer(final Player viewer, final boolean triggerCloseHandler) {
- final var currentInventory = viewer.getOpenInventory().getTopInventory().getHolder();
- final var viewers = getRawViewers();
- if (!(currentInventory instanceof MenuHolder)
- || !viewers.contains(currentInventory)) {
- return;
- }
- if (triggerCloseHandler || this.callCloseHandlerRegardless) {
- getCloseHandler().ifPresent(handler -> handler.close(viewer, this));
- }
- viewers.remove((MenuHolder) currentInventory);
- }
-
- /**
- * @param viewer The viewer to update this menu for.
- */
- @Override
- public void update(final Player viewer) throws IllegalStateException {
- if (!isOpen(viewer)) {
- return;
- }
-
- final var currentHolder = viewer.getOpenInventory().getTopInventory().getHolder();
- final var currentInventory = NullUtils.isNotNull(currentHolder).getInventory();
-
- for (final Slot slot : getRawSlots()) {
- currentInventory.setItem(slot.getIndex(), slot.getItem(viewer));
- }
-
- getUpdateHandler().ifPresent(handler -> handler.handle(viewer, this));
- viewer.updateInventory();
- }
-
- /**
- * Basically a carbon copy of {@link AbstractMenu#open(Player)}, which is needed to override the
- * {@code createInventory()} method, but it's private so the entire function needs to be copied,
- * alongside its other dependent private methods.
- */
- @Override
- public void open(final Player viewer) {
- final var currentHolder = viewer.getOpenInventory().getTopInventory().getHolder();
- final MenuHolder holder;
- if (currentHolder instanceof MenuHolder) {
- holder = (MenuHolder) currentHolder;
- final var currentMenu = holder.getMenu();
-
- if (currentMenu == this) {
- return;
- }
-
- Inventory inventory;
- if (isRedraw() && Objects.equals(getDimensions(), currentMenu.getDimensions())) {
- inventory = holder.getInventory();
- if (currentMenu instanceof AbstractMenu) {
- ((AbstractMenu) currentMenu).closedByPlayer(viewer, false);
- }
- }
- else {
- currentMenu.close(viewer);
- inventory = createInventory(holder);
- holder.setInventory(inventory);
- viewer.openInventory(inventory);
- }
-
- updateInventoryContents(viewer, inventory);
- holder.setMenu(this);
- }
- else {
- // Create new MenuHolder for the player
- holder = new MenuHolder(viewer, this);
- final var inventory = createInventory(holder);
- updateInventoryContents(viewer, inventory);
- holder.setInventory(inventory);
- viewer.openInventory(inventory);
- }
- getRawViewers().add(holder);
- getOpenHandler().ifPresent(handler -> handler.handle(viewer, this));
- }
-
- /**
- * Basically a carbon copy of {@link AbstractMenu}'s version, but uses a component title instead.
- *
- * @param holder The menu's inventory holder.
- * @return Returns the new inventory.
- */
- protected Inventory createInventory(final InventoryHolder holder) {
- if (this.inventoryType == null) {
- return Bukkit.createInventory(holder, this.inventorySlots, this.title);
- }
- return Bukkit.createInventory(holder, this.inventoryType, this.title);
- }
-
- /**
- * Invokes {@link AbstractMenu}'s version via reflection.
- *
- * @param viewer The viewer to update.
- * @param inventory The inventory to update.
- */
- protected void updateInventoryContents(final Player viewer, final Inventory inventory) {
- try {
- UPDATE_INV_CONTENTS_METHOD.invoke(this, viewer, inventory);
- }
- catch (final InvocationTargetException | IllegalAccessException exception) {
- throw new RuntimeException(exception);
- }
- }
-
-}
diff --git a/src/main/java/org/ipvp/canvas/type/CivChestMenu.java b/src/main/java/org/ipvp/canvas/type/CivChestMenu.java
deleted file mode 100644
index 95252097..00000000
--- a/src/main/java/org/ipvp/canvas/type/CivChestMenu.java
+++ /dev/null
@@ -1,91 +0,0 @@
-package org.ipvp.canvas.type;
-
-import net.kyori.adventure.text.Component;
-import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
-import org.apache.commons.lang3.StringUtils;
-import org.ipvp.canvas.Menu;
-import vg.civcraft.mc.civmodcore.chat.ChatUtils;
-
-public class CivChestMenu extends AbstractCivMenu {
-
- private Dimension dimension;
-
- public CivChestMenu(final Component title, final int rows) {
- this(title, rows, true);
- }
-
- public CivChestMenu(final Component title, final int rows, final boolean redraw) {
- this(title, rows, null, redraw);
- }
-
- public CivChestMenu(final Component title, final int rows, final Menu parent, final boolean redraw) {
- super(title, rows * 9, parent, redraw);
- }
-
- /**
- * @return Return this chest menu's row and column counts.
- */
- @Override
- public Dimension getDimensions() {
- if (this.dimension == null) {
- this.dimension = new Dimension(getSlotCount() / 9, 9);
- }
- return this.dimension;
- }
-
- /**
- * Returns a new builder.
- *
- * @param rows The amount of rows for the inventory to contain
- * @throws IllegalArgumentException if rows is not between 1 and 6 inclusive
- */
- public static Builder builder(final int rows) {
- if (rows < 1 || rows > 6) {
- throw new IllegalArgumentException("rows must be a value from 1 to 6");
- }
- return new Builder(rows);
- }
-
- /**
- * A builder for creating a CustomChestMenu instance.
- */
- public static class Builder extends AbstractMenu.Builder {
-
- private Component title;
-
- Builder(final int rows) {
- super(new Dimension(rows, 9));
- }
-
- @Deprecated
- @Override
- public Builder title(final String title) {
- if (StringUtils.isBlank(title)) {
- this.title = null;
- return this;
- }
- this.title = LegacyComponentSerializer.legacyAmpersand().deserialize(title);
- if (ChatUtils.isNullOrEmpty(this.title)) {
- this.title = null;
- }
- return this;
- }
-
- public Builder title(final Component title) {
- this.title = title;
- return this;
- }
-
- public Component getComponentTitle() {
- return this.title;
- }
-
- @Override
- public CivChestMenu build() {
- return new CivChestMenu(getComponentTitle(),
- getDimensions().getArea(), getParent(), isRedraw());
- }
-
- }
-
-}
diff --git a/src/main/java/org/ipvp/canvas/type/OpenHandler.java b/src/main/java/org/ipvp/canvas/type/OpenHandler.java
deleted file mode 100644
index a845cb52..00000000
--- a/src/main/java/org/ipvp/canvas/type/OpenHandler.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package org.ipvp.canvas.type;
-
-import org.bukkit.entity.Player;
-
-@FunctionalInterface
-public interface OpenHandler {
-
- /**
- * Is called by {@link AbstractCivMenu} when one of its menus are opened by a viewer.
- *
- * @param viewer The viewer of the opened menu.
- * @param menu The menu being opened.
- */
- void handle(Player viewer, AbstractCivMenu menu);
-
-}
diff --git a/src/main/java/org/ipvp/canvas/type/UpdateHandler.java b/src/main/java/org/ipvp/canvas/type/UpdateHandler.java
deleted file mode 100644
index e145b975..00000000
--- a/src/main/java/org/ipvp/canvas/type/UpdateHandler.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package org.ipvp.canvas.type;
-
-import org.bukkit.entity.Player;
-
-@FunctionalInterface
-public interface UpdateHandler {
-
- /**
- * Is called by {@link AbstractCivMenu} when one of its menus are updated. This is called after the menu has been
- * updated but before the update packets have been sent to the player.
- *
- * @param viewer The viewer of the updating menu.
- * @param menu The menu being updated.
- */
- void handle(Player viewer, AbstractCivMenu menu);
-
-}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/ACivMod.java b/src/main/java/vg/civcraft/mc/civmodcore/ACivMod.java
index d6cd8ac3..d1410f56 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/ACivMod.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/ACivMod.java
@@ -8,7 +8,6 @@
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;
@@ -36,7 +35,9 @@ public abstract class ACivMod extends JavaPlugin {
@Deprecated
protected CommandHandler handle = null;
+
protected StandaloneCommandHandler newCommandHandler;
+
protected boolean useNewCommandHandler = true;
@Override
@@ -337,36 +338,28 @@ 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.equals(plugin.getClass())) {
+ if (clazz.isAssignableFrom(plugin.getClass())) {
return (T) plugin;
}
}
- 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);
- }
+ 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);
}
- catch (final Exception ignored) { }
}
- 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) { }
+ try {
+ final Field field = clazz.getField("instance");
+ 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;
}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
index 309cab56..8321dc59 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/CivModCorePlugin.java
@@ -5,7 +5,9 @@
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;
@@ -16,11 +18,11 @@
import vg.civcraft.mc.civmodcore.inventory.items.SpawnEggUtils;
import vg.civcraft.mc.civmodcore.inventory.items.TreeTypeUtils;
import vg.civcraft.mc.civmodcore.inventorygui.ClickableInventoryListener;
+import vg.civcraft.mc.civmodcore.inventorygui.paged.PagedGUIManager;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.GlobalChunkMetaManager;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.api.ChunkMetaAPI;
import vg.civcraft.mc.civmodcore.locations.global.CMCWorldDAO;
import vg.civcraft.mc.civmodcore.locations.global.WorldIDManager;
-import vg.civcraft.mc.civmodcore.maps.MapColours;
import vg.civcraft.mc.civmodcore.playersettings.PlayerSettingAPI;
import vg.civcraft.mc.civmodcore.playersettings.gui.ConfigCommand;
import vg.civcraft.mc.civmodcore.playersettings.gui.ConfigGetAnyCommand;
@@ -32,18 +34,18 @@
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 final AikarCommandManager commands;
- public CivModCorePlugin() {
- this.commands = new AikarCommandManager(this, false);
- }
+ private AikarCommandManager manager;
@Override
public void onEnable() {
@@ -79,15 +81,21 @@ public void onEnable() {
ScoreBoardAPI.setDefaultHeader(scoreboardHeader);
// Register listeners
registerListener(new ClickableInventoryListener());
+ registerListener(new PagedGUIManager());
registerListener(DialogManager.INSTANCE);
+ registerListener(new ChatListener());
registerListener(new ScoreBoardListener());
registerListener(new CustomEventMapper());
registerListener(new WorldTracker());
registerListener(ChunkOperationManager.INSTANCE);
// Register commands
- this.commands.init();
- this.commands.registerCommand(new ConfigCommand());
- this.commands.registerCommand(ChunkOperationManager.INSTANCE);
+ this.manager = new AikarCommandManager(this) {
+ @Override
+ public void registerCommands() {
+ registerCommand(new ConfigCommand());
+ registerCommand(ChunkOperationManager.INSTANCE);
+ }
+ };
// Load APIs
EnchantUtils.loadEnchantAbbreviations(this);
ItemUtils.loadItemNames(this);
@@ -96,14 +104,16 @@ public void onEnable() {
SpawnEggUtils.init();
TreeTypeUtils.init();
BottomLineAPI.init();
- MapColours.init();
- this.newCommandHandler.registerCommand(new ConfigSetAnyCommand());
- this.newCommandHandler.registerCommand(new ConfigGetAnyCommand());
+ newCommandHandler.registerCommand(new ConfigSetAnyCommand());
+ newCommandHandler.registerCommand(new ConfigGetAnyCommand());
+ // Deprecated
+ PotionNames.loadPotionNames();
}
@Override
public void onDisable() {
Bukkit.getOnlinePlayers().forEach(HumanEntity::closeInventory);
+ PotionNames.resetPotionNames();
ChunkMetaAPI.saveAll();
this.chunkMetaManager = null;
// Disconnect database
@@ -121,7 +131,10 @@ public void onDisable() {
PlayerSettingAPI.saveAll();
ConfigurationSerialization.unregisterClass(ManagedDatasource.class);
NBTSerialization.clearAllRegistrations();
- this.commands.reset();
+ if (this.manager != null) {
+ this.manager.reset();
+ this.manager = null;
+ }
super.onDisable();
}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/api/BlockAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/api/BlockAPI.java
new file mode 100644
index 00000000..1655203e
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/BlockAPI.java
@@ -0,0 +1,390 @@
+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
new file mode 100644
index 00000000..4b810645
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/ColourAPI.java
@@ -0,0 +1,84 @@
+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
new file mode 100644
index 00000000..b458bb80
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/EnchantAPI.java
@@ -0,0 +1,155 @@
+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
new file mode 100644
index 00000000..56bff356
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/EnchantNames.java
@@ -0,0 +1,94 @@
+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
new file mode 100644
index 00000000..82d16df1
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/EntityAPI.java
@@ -0,0 +1,66 @@
+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
new file mode 100644
index 00000000..c1ad9007
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/InventoryAPI.java
@@ -0,0 +1,279 @@
+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
new file mode 100644
index 00000000..96215223
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/ItemAPI.java
@@ -0,0 +1,420 @@
+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
new file mode 100644
index 00000000..460d4c0e
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/ItemNames.java
@@ -0,0 +1,37 @@
+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
new file mode 100644
index 00000000..16b3d11f
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/LocationAPI.java
@@ -0,0 +1,156 @@
+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
new file mode 100644
index 00000000..3dae6419
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/MaterialAPI.java
@@ -0,0 +1,793 @@
+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;
+
+/**
+ *
+ *
+ * @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
new file mode 100644
index 00000000..3439f47b
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/NamespaceAPI.java
@@ -0,0 +1,91 @@
+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
new file mode 100644
index 00000000..797f8feb
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/PotionAPI.java
@@ -0,0 +1,65 @@
+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
new file mode 100644
index 00000000..629ec333
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/PotionNames.java
@@ -0,0 +1,203 @@
+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
new file mode 100644
index 00000000..2ef837a7
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/RecipeAPI.java
@@ -0,0 +1,93 @@
+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
new file mode 100644
index 00000000..d4a5f88d
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/SpawnEggAPI.java
@@ -0,0 +1,136 @@
+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
new file mode 100644
index 00000000..077e4a75
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/ToolAPI.java
@@ -0,0 +1,48 @@
+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
new file mode 100644
index 00000000..4a5cde30
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/TreeTypeAPI.java
@@ -0,0 +1,121 @@
+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
new file mode 100644
index 00000000..3cac1652
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/WorldAPI.java
@@ -0,0 +1,90 @@
+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
new file mode 100644
index 00000000..41b27c19
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/api/package-info.java
@@ -0,0 +1,7 @@
+/**
+ * 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/chat/ChatUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java
index e6162799..f87f8585 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/chat/ChatUtils.java
@@ -3,18 +3,10 @@
import com.google.common.base.Strings;
import java.awt.Color;
import java.util.List;
-import java.util.Objects;
-import net.kyori.adventure.text.Component;
-import net.kyori.adventure.text.format.TextDecoration;
-import net.kyori.adventure.text.minimessage.MiniMessage;
-import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
-import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
-import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
import net.md_5.bungee.api.ChatColor;
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;
public final class ChatUtils {
@@ -159,64 +151,28 @@ public static String parseColorTags(String string) {
*
* @param component The component to test if null or empty.
* @return Returns true if the component is null or has no visible content.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
*/
- @Deprecated
public static boolean isNullOrEmpty(final BaseComponent component) {
if (component == null) {
return true;
}
- return Strings.isNullOrEmpty(component.toPlainText());
+ final TextComponent text = fromLegacyText(component.toPlainText());
+ return Strings.isNullOrEmpty(text.toPlainText());
}
/**
- *
Determines whether a given base component is null or empty.
+ *
Converts a string containing Minecraft's legacy colour codes into a text component.
*
- *
This is determined by converting the component into plain text, so a non-null component filled with
- * nothing but colour codes and hover text will likely return true.
+ *
Note: This does not work on Civ's colour code equivalents, make sure to parse those before using this.
*
- * @param component The component to test if null or empty.
- * @return Returns true if the component is null or has no visible content.
+ * @param text The legacy text to parse.
+ * @return Returns a text component of the legacy text.
*/
- public static boolean isNullOrEmpty(final Component component) {
- if (component == null) {
- return true;
+ public static TextComponent fromLegacyText(final String text) {
+ if (Strings.isNullOrEmpty(text)) {
+ return new TextComponent(text);
}
- return StringUtils.isBlank(PlainComponentSerializer.plain().serialize(component));
- }
-
- /**
- * @return Generates a new text component that's specifically NOT italicised. Use this for item names and
- * lore.
- */
- public static net.kyori.adventure.text.TextComponent newComponent() {
- return newComponent("");
- }
-
- /**
- * Generates a new text component that's specifically NOT italicised. Use this for item names and lore.
- *
- * @param content The text content for the component.
- * @return Returns the generated text component.
- */
- public static net.kyori.adventure.text.TextComponent newComponent(final String content) {
- return Component.text(Objects.requireNonNull(content))
- .decoration(TextDecoration.ITALIC, TextDecoration.State.FALSE);
- }
-
- /**
- * Clones a component.
- *
- * @param component The component to clone.
- * @return Returns a clone of the given component.
- */
- public static Component cloneComponent(final Component component) {
- if (component == null) {
- return null;
- }
- final var raw = GsonComponentSerializer.gson().serialize(component);
- return GsonComponentSerializer.gson().deserialize(raw);
+ return new TextComponent(TextComponent.fromLegacyText(text, ChatColor.RESET));
}
/**
@@ -225,10 +181,7 @@ public static Component cloneComponent(final Component component) {
* @param value The value of the text. (Objects will be stringified)
* @param formats The colour formats.
* @return Returns the created component, so you can do more stuff to it.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure. Use {@link Component#text()} instead.
*/
- @Deprecated
public static TextComponent textComponent(final Object value, final ChatColor... formats) {
final TextComponent component = new TextComponent(value == null ? "" : value.toString());
if (!ArrayUtils.isEmpty(formats)) {
@@ -267,18 +220,4 @@ else if (format == ChatColor.MAGIC) {
return component;
}
- public static boolean areComponentsEqual(final Component former, final Component latter) {
- if (StringUtils.equals(
- MiniMessage.get().serialize(former),
- MiniMessage.get().serialize(latter))) {
- return true;
- }
- if (StringUtils.equals(
- LegacyComponentSerializer.legacyAmpersand().serialize(former),
- LegacyComponentSerializer.legacyAmpersand().serialize(latter))) {
- return true;
- }
- return false;
- }
-
}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/ChatListener.java b/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/ChatListener.java
new file mode 100644
index 00000000..596783bd
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/ChatListener.java
@@ -0,0 +1,36 @@
+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
new file mode 100644
index 00000000..9aa61ed7
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/Dialog.java
@@ -0,0 +1,67 @@
+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
new file mode 100644
index 00000000..9cbcc598
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/DialogManager.java
@@ -0,0 +1,45 @@
+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
new file mode 100644
index 00000000..8dd875dd
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/LDialog.java
@@ -0,0 +1,36 @@
+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
new file mode 100644
index 00000000..2ee0705f
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/chatDialog/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * 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/AikarCommandManager.java b/src/main/java/vg/civcraft/mc/civmodcore/command/AikarCommandManager.java
index f5fb95af..27890ad4 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/command/AikarCommandManager.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/command/AikarCommandManager.java
@@ -35,6 +35,7 @@
public class AikarCommandManager {
private final ACivMod plugin;
+
private CustomBukkitManager manager;
/**
@@ -42,7 +43,7 @@ public class AikarCommandManager {
*
* @param plugin The plugin to bind this manager to.
*/
- public AikarCommandManager(final ACivMod plugin) {
+ public AikarCommandManager(ACivMod plugin) {
this(plugin, true);
}
@@ -54,17 +55,25 @@ public AikarCommandManager(final ACivMod plugin) {
* {@link AikarCommandManager#registerCommands()} and
* {@link AikarCommandManager#registerCompletions(CommandCompletions)}.
*/
- public AikarCommandManager(final ACivMod plugin, final boolean autoInit) {
+ public AikarCommandManager(ACivMod plugin, boolean autoInit) {
this.plugin = plugin;
if (autoInit) {
init();
}
}
+ /**
+ * @deprecated Use {@link #init()} instead as it's more indicative of what's happening.
+ */
+ @Deprecated
+ public final void register() {
+ init();
+ }
+
/**
* Will initialise the manager and register both commands and completions. You should only really use this if
- * you've used {@link AikarCommandManager#reset()} or both {@link AikarCommandManager#resetCommands()} and
- * {@link AikarCommandManager#resetCompletions()}, otherwise there may be issues.
+ * you've used {@link AikarCommandManager#reset()} or both {@link AikarCommandManager#deregisterCommands()} and
+ * {@link AikarCommandManager#deregisterCompletions()}, otherwise there may be issues.
*/
public final void init() {
this.manager = new CustomBukkitManager(plugin);
@@ -74,19 +83,19 @@ public final void init() {
}
/**
- * This is called as part of {@link AikarCommandManager#init()} and should be overridden by an extending class to
- * register all (or as many) commands at once.
+ * This is called as part of {@link AikarCommandManager#register()} and should be overridden by an extending class
+ * to register all (or as many) commands at once.
*/
public void registerCommands() { }
/**
- * This is called as part of {@link AikarCommandManager#init()} and should be overridden by an extending class to
- * register all (or as many) completions at once, though make sure to call super.
+ * This is called as part of {@link AikarCommandManager#register()} and should be overridden by an extending class
+ * to register all (or as many) completions at once, though make sure to call super.
*
* @param completions The completion manager is given. It is the same manager that can be reached via
* {@link CustomBukkitManager#getCommandCompletions()}.
*/
- public void registerCompletions(final CommandCompletions completions) {
+ public void registerCompletions(CommandCompletions completions) {
completions.registerAsyncCompletion("allplayers", context ->
Arrays.stream(Bukkit.getOfflinePlayers())
.map(OfflinePlayer::getName)
@@ -106,24 +115,24 @@ public void registerCompletions(final CommandCompletions contexts) { }
+ public void registerContexts(CommandContexts contexts) { }
/**
* Registers a new command and any attached tab completions.
*
* @param command The command instance to register.
*/
- public final void registerCommand(final AikarCommand command) {
+ public final void registerCommand(AikarCommand command) {
Preconditions.checkArgument(command != null, "Could not register that command: the command was null.");
this.manager.registerCommand(command);
this.plugin.info("Command [" + command.getClass().getSimpleName() + "] registered.");
- for (final var entry : getTabCompletions(command.getClass()).entrySet()) {
+ for (Map.Entry entry : getTabCompletions(command.getClass()).entrySet()) {
if (entry.getValue().async()) {
this.manager.getCommandCompletions().registerAsyncCompletion(entry.getValue().value(), (context) ->
runCommandCompletion(context, command, entry.getValue().value(), entry.getKey()));
@@ -142,7 +151,7 @@ public final void registerCommand(final AikarCommand command) {
* @param command The command instance to register.
*/
@SuppressWarnings("unchecked")
- public final void deregisterCommand(final AikarCommand command) {
+ public final void deregisterCommand(AikarCommand command) {
Preconditions.checkArgument(command != null, "Could not deregister that command: the command was null.");
this.manager.unregisterCommand(command);
this.plugin.info("Command [" + command.getClass().getSimpleName() + "] deregistered.");
@@ -161,16 +170,16 @@ public final void deregisterCommand(final AikarCommand command) {
}
/**
- * Resets all commands.
+ * Deregisters all commands.
*/
- public final void resetCommands() {
+ public final void deregisterCommands() {
this.manager.unregisterCommands();
}
/**
- * Resets all command completions.
+ * Deregisters all command completions.
*/
- public final void resetCompletions() {
+ public final void deregisterCompletions() {
this.manager.unregisterCompletions();
}
@@ -178,8 +187,8 @@ public final void resetCompletions() {
* Resets the manager, resetting all commands and completions.
*/
public final void reset() {
- resetCommands();
- resetCompletions();
+ this.manager.unregisterCommands();
+ this.manager.unregisterCompletions();
this.manager = null;
}
@@ -192,10 +201,6 @@ public final CustomBukkitManager getInternalManager() {
return this.manager;
}
- public ACivMod getPlugin() {
- return this.plugin;
- }
-
// ------------------------------------------------------------
// Utilities
// ------------------------------------------------------------
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/command/MailBoxAPI.java b/src/main/java/vg/civcraft/mc/civmodcore/command/MailBoxAPI.java
new file mode 100644
index 00000000..41c86cb9
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/command/MailBoxAPI.java
@@ -0,0 +1,56 @@
+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/entities/merchant/CustomBukkitMerchant.java b/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomBukkitMerchant.java
deleted file mode 100644
index de4f8617..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomBukkitMerchant.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package vg.civcraft.mc.civmodcore.entities.merchant;
-
-import io.papermc.paper.event.player.PlayerTradeEvent;
-import java.lang.reflect.Field;
-import java.util.logging.Level;
-import net.kyori.adventure.text.Component;
-import org.apache.commons.lang3.reflect.FieldUtils;
-import org.bukkit.Bukkit;
-import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftMerchant;
-import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftMerchantCustom;
-import vg.civcraft.mc.civmodcore.util.CivLogger;
-
-/**
- * This is an alternative to {@link Bukkit#createMerchant(Component)} that re-adds
- * {@link PlayerTradeEvent} emissions. Just do: {@code new CustomBukkitMerchant(Component)}
- */
-public class CustomBukkitMerchant extends CraftMerchantCustom {
-
- private static final CivLogger LOGGER;
- private static final Field MERCHANT_FIELD;
-
- static {
- LOGGER = CivLogger.getLogger(CustomBukkitMerchant.class);
- MERCHANT_FIELD = FieldUtils.getField(CraftMerchant.class, "merchant", true);
- FieldUtils.removeFinalModifier(MERCHANT_FIELD);
- }
-
- public CustomBukkitMerchant(final Component title) {
- super(title);
- final var nmsMerchant = new CustomNMSMerchant(this, title);
- try {
- FieldUtils.writeField(MERCHANT_FIELD, this, nmsMerchant, true);
- }
- catch (final IllegalAccessException exception) {
- LOGGER.log(Level.SEVERE,
- "Could not re-set merchant to [" + nmsMerchant + "]",
- exception);
- }
- }
-
- public CustomNMSMerchant getNMSMerchant() {
- return (CustomNMSMerchant) super.getMerchant();
- }
-
- /**
- * Use {@link #getNMSMerchant()} instead. The only reason why this is being kept is because
- * the super constructor calls this function and expects this type, not {@link CustomNMSMerchant}.
- */
- @Deprecated
- @Override
- public CraftMerchantCustom.MinecraftMerchant getMerchant() {
- return super.getMerchant();
- }
-
- @Override
- public String toString() {
- /** Stolen from {@link Object#toString()} because the super version is garbage */
- return getClass().getName() + "@" + Integer.toHexString(hashCode());
- }
-
-}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java b/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java
deleted file mode 100644
index ff3780e0..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/entities/merchant/CustomNMSMerchant.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package vg.civcraft.mc.civmodcore.entities.merchant;
-
-import io.papermc.paper.event.player.PlayerTradeEvent;
-import java.lang.reflect.Field;
-import java.util.Collections;
-import java.util.Objects;
-import net.kyori.adventure.text.Component;
-import net.minecraft.server.v1_16_R3.Entity;
-import net.minecraft.server.v1_16_R3.EntityExperienceOrb;
-import net.minecraft.server.v1_16_R3.EntityPlayer;
-import net.minecraft.server.v1_16_R3.EntityTypes;
-import net.minecraft.server.v1_16_R3.EntityVillager;
-import net.minecraft.server.v1_16_R3.EntityVillagerAbstract;
-import net.minecraft.server.v1_16_R3.EntityVillagerTrader;
-import net.minecraft.server.v1_16_R3.MerchantRecipe;
-import net.minecraft.server.v1_16_R3.MerchantRecipeList;
-import net.minecraft.server.v1_16_R3.World;
-import org.apache.commons.lang3.reflect.FieldUtils;
-import org.bukkit.craftbukkit.v1_16_R3.entity.CraftVillager;
-import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftMerchantCustom;
-import org.bukkit.entity.ExperienceOrb;
-
-public class CustomNMSMerchant extends CraftMerchantCustom.MinecraftMerchant {
-
- private static final Field TRADES_FIELD;
-
- static {
- TRADES_FIELD = FieldUtils.getField(CraftMerchantCustom.MinecraftMerchant.class, "trades", true);
- FieldUtils.removeFinalModifier(TRADES_FIELD);
- }
-
- CustomNMSMerchant(final CustomBukkitMerchant merchant, final Component title) {
- super(title);
- this.craftMerchant = Objects.requireNonNull(merchant);
- }
-
- /**
- * @return Returns the raw offers object (which is mutable) via reflection.
- */
- public MerchantRecipeList getRawOffers() {
- try {
- return (MerchantRecipeList) FieldUtils.readField(TRADES_FIELD, this, true);
- }
- catch (final IllegalAccessException exception) {
- throw new RuntimeException(exception);
- }
- }
-
- /**
- * This is based heavily on {@link EntityVillagerAbstract#a(MerchantRecipe)}. This method is called
- * by NMS when a trade is being purchased.
- */
- @Override
- public void a(final MerchantRecipe trade) {
- if (getTrader() instanceof EntityPlayer) {
- final var trader = (EntityPlayer) getTrader();
- final var villager = createDisposableVillager(trader.getWorld());
- final var event = new PlayerTradeEvent(
- trader.getBukkitEntity(),
- villager, // Have to spawn a useless villager because this is @Nonnull
- trade.asBukkit(),
- true, // reward xp?
- true); // should increase uses?
- event.callEvent();
- killDisposableVillager(villager);
- if (event.isCancelled()) {
- return;
- }
- final var eventTrade = event.getTrade();
- if (event.willIncreaseTradeUses()) {
- eventTrade.setUses(eventTrade.getUses() + 1);
- }
- if (event.isRewardingExp() && eventTrade.hasExperienceReward()) {
- /** Based on {@link EntityVillagerTrader#b(MerchantRecipe)} */
- final int xp = 3 + Entity.SHARED_RANDOM.nextInt(4);
- final var world = trader.getWorld();
- world.addEntity(new EntityExperienceOrb(
- world, trader.locX(), trader.locY() + 0.5d, trader.locZ(),
- xp, ExperienceOrb.SpawnReason.VILLAGER_TRADE, trader, null));
- }
- return;
- }
- super.a(trade);
- }
-
- // ------------------------------------------------------------
- // Unfortunate but necessary villager management
- // ------------------------------------------------------------
-
- private static CraftVillager createDisposableVillager(final World world) {
- final var villager = new CraftVillager(world.getServer(),
- new EntityVillager(EntityTypes.VILLAGER, world));
- villager.setAI(false);
- villager.setGravity(false);
- villager.setCanPickupItems(false);
- villager.setSilent(true);
- villager.setVillagerExperience(0);
- villager.setInvisible(true);
- villager.setRecipes(Collections.emptyList());
- return villager;
- }
-
- private static void killDisposableVillager(final CraftVillager villager) {
- villager.getHandle().dead = true;
- villager.getHandle().setHealth(0);
- villager.getHandle().shouldBeRemoved = true;
- }
-
-}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/ClonedInventory.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/ClonedInventory.java
index b9738bc4..8354095f 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/ClonedInventory.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/ClonedInventory.java
@@ -231,24 +231,10 @@ public Inventory getInventory() {
* @return Returns a clone of the given inventory.
*/
public static ClonedInventory cloneInventory(final Inventory inventory) {
- return cloneInventory(inventory, false);
- }
-
- /**
- *
Clones the given inventory for the purpose of test manipulating its contents.
- *
- *
Note: Do not type check the inventory, it's JUST a contents copy within an inventory wrapper to provide the
- * relevant and useful methods.
- *
- * @param inventory The inventory to clone.
- * @param forceClone Determines whether the inventory should be cloned even if it's an already cloned inventory.
- * @return Returns a clone of the given inventory.
- */
- public static ClonedInventory cloneInventory(final Inventory inventory, final boolean forceClone) {
if (inventory == null) {
return null;
}
- if (!forceClone && inventory instanceof ClonedInventory) {
+ if (inventory instanceof ClonedInventory) {
return (ClonedInventory) inventory;
}
Inventory clone;
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java
index 8d83053f..094adfe7 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/inventory/InventoryUtils.java
@@ -14,13 +14,6 @@
public final class InventoryUtils {
- public static final int CHEST_1_ROW = 9;
- public static final int CHEST_2_ROWS = 9 * 2;
- public static final int CHEST_3_ROWS = 9 * 3;
- public static final int CHEST_4_ROWS = 9 * 4;
- public static final int CHEST_5_ROWS = 9 * 5;
- public static final int CHEST_6_ROWS = 9 * 6;
-
/**
* Tests an inventory to see if it's valid.
*
@@ -45,7 +38,7 @@ public static boolean isValidInventory(final Inventory inventory) {
*/
public static List getViewingPlayers(final Inventory inventory) {
if (!isValidInventory(inventory)) {
- return new ArrayList<>(0);
+ return new ArrayList<>();
}
return inventory.getViewers().stream()
.filter(entity -> entity instanceof Player)
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuPagination.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuPagination.java
deleted file mode 100644
index 78e04292..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuPagination.java
+++ /dev/null
@@ -1,241 +0,0 @@
-package vg.civcraft.mc.civmodcore.inventory.gui.canvas;
-
-import it.unimi.dsi.fastutil.objects.Object2ObjectAVLTreeMap;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.UUID;
-import org.apache.commons.collections4.CollectionUtils;
-import org.bukkit.entity.Player;
-import org.ipvp.canvas.slot.SlotSettings;
-import org.ipvp.canvas.type.AbstractCivMenu;
-
-/**
- * Better version of {@link org.ipvp.canvas.paginate.PaginatedMenuBuilder} as it allows you to apply pagination to an
- * already existing menu, rather than using a builder to spawn a bunch of new menu instances that'll just be used by a
- * single player before promptly discarded.
- */
-public final class MenuPagination {
-
- private final AbstractCivMenu menu;
- private final Map playerPages;
- private final List menuBar;
- private final ElementSupplier supplier;
- private final int buttonSlots;
-
- private MenuPagination(final AbstractCivMenu menu,
- final ElementSupplier supplier,
- final List menuBar) {
- this.menu = Objects.requireNonNull(menu, "Menu cannot be null");
- final int rows = menu.getDimensions().getRows();
- if (rows < 2 || rows > 5) {
- throw new IllegalArgumentException("Row count must be between 2 and 5 inclusively");
- }
- this.playerPages = new Object2ObjectAVLTreeMap<>();
- this.menuBar = List.copyOf(menuBar);
- if (menuBar.size() > 9) {
- throw new IllegalArgumentException("Bar cannot contain more than 9 buttons");
- }
- this.supplier = Objects.requireNonNull(supplier, "Element supplier cannot be null");
- this.buttonSlots = (rows * 9) - 9;
-
- MenuUtils.overrideOpenHandler(menu, (viewer, opened) -> {
- final var pager = INTERNAL_getPlayerPager(viewer);
- pager.pageNumber = 0;
- pager.elements = this.supplier.generate(viewer, opened);
- INTERNAL_applyPlayerPage(viewer, opened, INTERNAL_getPlayerPager(viewer));
- }, true);
-
- MenuUtils.overrideUpdateHandler(menu, (viewer, updated) -> {
- INTERNAL_applyPlayerPage(viewer, updated, INTERNAL_getPlayerPager(viewer));
- }, true);
-
- menu.setCallCloseHandlerRegardless(true);
- MenuUtils.overrideCloseHandler(menu, (viewer, ignored) -> {
- this.playerPages.remove(viewer.getUniqueId());
- }, true);
-
- for (int i = 0; i < this.buttonSlots; i++) {
- menu.getSlot(i).setClickHandler((viewer, click) -> {
- final var pager = INTERNAL_getPlayerPager(viewer);
- final int buttonIndex = INTERNAL_calculateElementIndex(pager, click.getClickedSlot().getIndex());
- if (buttonIndex >= pager.elements.size()) {
- return;
- }
- final var handler = pager.elements.get(buttonIndex).getClickHandler();
- if (handler == null) {
- return;
- }
- handler.click(viewer, click);
- });
- }
-
- for (int i = 0; i < 9; i++) {
- final var slotIndex = INTERNAL_calculateBarIndex(i);
- if (i >= this.menuBar.size()) {
- menu.getSlot(slotIndex).setSettings(MenuUtils.createEmptySlot());
- break;
- }
- final var barElement = this.menuBar.get(i);
- if (barElement == null) {
- menu.getSlot(slotIndex).setSettings(MenuUtils.createEmptySlot());
- continue;
- }
- menu.getSlot(slotIndex).setSettings(barElement);
- }
- }
-
- /**
- * @param viewer The viewer to send to the next page.
- */
- public void nextPage(final Player viewer) {
- final var pager = INTERNAL_getPlayerPager(viewer);
- pager.pageNumber++;
- this.menu.update(viewer);
- }
-
- /**
- * @param viewer The viewer to send to the previous page.
- */
- public void previousPage(final Player viewer) {
- final var pager = INTERNAL_getPlayerPager(viewer);
- pager.pageNumber--;
- this.menu.update(viewer);
- }
-
- /**
- * @param viewer The viewer to check if they have a next page.
- * @return Returns whether the viewer has a next page.
- */
- public boolean hasNextPage(final Player viewer) {
- final var pager = INTERNAL_getPlayerPager(viewer);
- final int elementsSize = CollectionUtils.size(pager.elements);
- final int totalPages = elementsSize / this.buttonSlots;
- if (totalPages == 0) {
- return false;
- }
- return pager.pageNumber >= totalPages;
- }
-
- /**
- * @param viewer The viewer to check if they have a previous page.
- * @return Returns whether the viewer has a previous page.
- */
- public boolean hasPreviousPage(final Player viewer) {
- final var pager = INTERNAL_getPlayerPager(viewer);
- final int elementsSize = CollectionUtils.size(pager.elements);
- final int totalPages = elementsSize / this.buttonSlots;
- if (totalPages == 0) {
- return false;
- }
- return pager.pageNumber < totalPages;
- }
-
- protected void INTERNAL_applyPlayerPage(final Player viewer,
- final AbstractCivMenu menu,
- final INTERNAL_PlayerPager pager) {
- pager.pageNumber = Math.max(pager.pageNumber, 0);
- pager.pageNumber = Math.min(pager.pageNumber, pager.elements.size() / this.buttonSlots);
- for (int i = 0; i < this.buttonSlots; i++) {
- final int buttonIndex = INTERNAL_calculateElementIndex(pager, i);
- if (buttonIndex >= pager.elements.size()) {
- menu.getSlot(i).setRawItem(viewer, null);
- continue;
- }
- final var template = pager.elements.get(buttonIndex).getItemTemplate();
- if (template == null) {
- menu.getSlot(i).setRawItem(viewer, null);
- continue;
- }
- menu.getSlot(i).setRawItem(viewer, template.getItem(viewer));
- }
- }
-
- protected INTERNAL_PlayerPager INTERNAL_getPlayerPager(final Player viewer) {
- return this.playerPages.computeIfAbsent(viewer.getUniqueId(), (uuid) -> new INTERNAL_PlayerPager());
- }
-
- protected int INTERNAL_calculateElementIndex(final INTERNAL_PlayerPager pager, final int slot) {
- return (pager.pageNumber * this.buttonSlots) + slot;
- }
-
- protected int INTERNAL_calculateBarIndex(final int slot) {
- return this.buttonSlots + slot;
- }
-
- protected static class INTERNAL_PlayerPager {
- private int pageNumber;
- private List elements;
- }
-
- @FunctionalInterface
- public interface ElementSupplier {
- List generate(Player viewer, AbstractCivMenu menu);
- }
-
- /**
- * @return Returns a new pagination builder.
- */
- public static Builder builder() {
- return new Builder();
- }
-
- public static class Builder {
-
- private AbstractCivMenu menu;
- private ElementSupplier supplier;
- private final SlotSettings[] menuBar;
-
- Builder() {
- this.menuBar = new SlotSettings[] {
- MenuUtils.createEmptySlot(),
- MenuUtils.createEmptySlot(),
- MenuUtils.createEmptySlot(),
- MenuUtils.createEmptySlot(),
- MenuUtils.createEmptySlot(),
- MenuUtils.createEmptySlot(),
- MenuUtils.createEmptySlot(),
- MenuUtils.createEmptySlot(),
- MenuUtils.createEmptySlot()
- };
- }
-
- /**
- * @param menu The menu to paginate.
- * @return Returns this builder.
- */
- public Builder setMenu(final AbstractCivMenu menu) {
- this.menu = menu;
- return this;
- }
-
- /**
- * @param supplier Supplier method to return all the elements to be paginated.
- * @return Returns this builder.
- */
- public Builder setElementSupplier(final ElementSupplier supplier) {
- this.supplier = supplier;
- return this;
- }
-
- /**
- * @param index The index of the menu bar element from 0-8 inclusively.
- * @param element The menu bar element to add.
- * @return Returns this builder.
- */
- public Builder setMenuBarElement(final int index, final SlotSettings element) {
- this.menuBar[index] = element == null ? MenuUtils.createEmptySlot() : element;
- return this;
- }
-
- /**
- * @return Returns a constructed menu pagination based on this builder.
- */
- public MenuPagination build() {
- return new MenuPagination(this.menu, this.supplier, Arrays.asList(this.menuBar));
- }
-
- }
-
-}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuUtils.java
deleted file mode 100644
index 6d7b57cb..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/inventory/gui/canvas/MenuUtils.java
+++ /dev/null
@@ -1,102 +0,0 @@
-package vg.civcraft.mc.civmodcore.inventory.gui.canvas;
-
-import org.ipvp.canvas.Menu;
-import org.ipvp.canvas.slot.SlotSettings;
-import org.ipvp.canvas.type.AbstractCivMenu;
-import org.ipvp.canvas.type.OpenHandler;
-import org.ipvp.canvas.type.UpdateHandler;
-
-public final class MenuUtils {
-
- /**
- * @return Returns an empty, unmodifiable slot.
- */
- public static SlotSettings createEmptySlot() {
- return SlotSettings.builder().build();
- }
-
- /**
- * Overrides a given menu's open event handler, in lieu of just replacing it, meaning that you can add handlers to
- * a menu without fear of removing any previously added functionality.
- *
- * @param menu The menu to add the handler for.
- * @param handler The handler to add.
- * @param callSuperBefore Whether or not to call the existing handler before or after the given handler.
- */
- public static void overrideOpenHandler(final AbstractCivMenu menu,
- final OpenHandler handler,
- final boolean callSuperBefore) {
- final var findExisting = menu.getOpenHandler();
- if (findExisting.isEmpty()) {
- menu.setOpenHandler(handler);
- return;
- }
- final var existing = findExisting.get();
- menu.setOpenHandler((viewer, openedMenu) -> {
- if (callSuperBefore) {
- existing.handle(viewer, openedMenu);
- }
- handler.handle(viewer, openedMenu);
- if (!callSuperBefore) {
- existing.handle(viewer, openedMenu);
- }
- });
- }
-
- /**
- * Overrides a given menu's update event handler, in lieu of just replacing it, meaning that you can add handlers
- * to a menu without fear of removing any previously added functionality.
- *
- * @param menu The menu to add the handler for.
- * @param handler The handler to add.
- * @param callSuperBefore Whether or not to call the existing handler before or after the given handler.
- */
- public static void overrideUpdateHandler(final AbstractCivMenu menu,
- final UpdateHandler handler,
- final boolean callSuperBefore) {
- final var findExisting = menu.getUpdateHandler();
- if (findExisting.isEmpty()) {
- menu.setUpdateHandler(handler);
- return;
- }
- final var existing = findExisting.get();
- menu.setUpdateHandler((viewer, openedMenu) -> {
- if (callSuperBefore) {
- existing.handle(viewer, openedMenu);
- }
- handler.handle(viewer, openedMenu);
- if (!callSuperBefore) {
- existing.handle(viewer, openedMenu);
- }
- });
- }
-
- /**
- * Overrides a given menu's close event handler, in lieu of just replacing it, meaning that you can add handlers to
- * a menu without fear of removing any previously added functionality.
- *
- * @param menu The menu to add the handler for.
- * @param handler The handler to add.
- * @param callSuperBefore Whether or not to call the existing handler before or after the given handler.
- */
- public static void overrideCloseHandler(final AbstractCivMenu menu,
- final Menu.CloseHandler handler,
- final boolean callSuperBefore) {
- final var findExisting = menu.getCloseHandler();
- if (findExisting.isEmpty()) {
- menu.setCloseHandler(handler);
- return;
- }
- final var existing = findExisting.get();
- menu.setCloseHandler((viewer, openedMenu) -> {
- if (callSuperBefore) {
- existing.close(viewer, openedMenu);
- }
- handler.close(viewer, openedMenu);
- if (!callSuperBefore) {
- existing.close(viewer, openedMenu);
- }
- });
- }
-
-}
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 1260dea9..1f82abab 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,7 @@
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import vg.civcraft.mc.civmodcore.CivModCorePlugin;
-import vg.civcraft.mc.civmodcore.util.CivLogger;
+import vg.civcraft.mc.civmodcore.util.Chainer;
import vg.civcraft.mc.civmodcore.util.KeyedUtils;
/**
@@ -96,35 +96,34 @@ 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)) {
- logger.warning("Enchantment key was empty.");
+ plugin.warning("[EnchantUtils] Enchantment key was empty.");
continue;
}
final Enchantment enchant = EnchantUtils.getEnchantment(key);
if (enchant == null) {
- logger.warning("Could not find enchantment: " + key);
+ plugin.warning("[EnchantUtils] Could not find enchantment: " + key);
return;
}
final String abbreviation = enchantsConfig.getString(key);
if (Strings.isNullOrEmpty(abbreviation)) {
- logger.warning("Abbreviation for [" + key + "] was empty.");
+ plugin.warning("[EnchantUtils] Abbreviation for [" + key + "] was empty.");
continue;
}
ENCHANT_ABBR.put(enchant, abbreviation);
}
- logger.info("Loaded a total of " + ENCHANT_ABBR.size() + " abbreviations from enchants.yml");
+ plugin.info("[EnchantUtils] 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
- logger.warning("The following enchants are missing from enchants.yml: " +
+ plugin.warning("[EnchantUtils] The following enchants are missing from enchants.yml: " +
missing.stream().map(Enchantment::getName).collect(Collectors.joining(",")) + ".");
}
}
@@ -188,10 +187,7 @@ 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) {
- if (item == null) {
- return ImmutableMap.of();
- }
- return item.getEnchantments();
+ return Chainer.from(item).then(ItemStack::getEnchantments).getOrGenerate(HashMap::new);
}
/**
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 e4628c11..744acf48 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,8 +9,6 @@
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
-import javax.annotation.Nonnull;
-import net.kyori.adventure.text.Component;
import org.apache.commons.collections4.CollectionUtils;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
@@ -19,7 +17,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;
+import vg.civcraft.mc.civmodcore.util.Chainer;
/**
* Class of static APIs for Items. Replaces ISUtils.
@@ -34,34 +32,33 @@ 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)) {
- logger.warning("Material key was empty.");
+ plugin.warning("[ItemUtils] Material key was empty.");
continue;
}
final Material material = Material.getMaterial(key);
if (material == null) {
- logger.warning("Could not find material: " + key);
+ plugin.warning("[ItemUtils] Could not find material: " + key);
return;
}
final String name = materialsConfig.getString(key);
if (Strings.isNullOrEmpty(name)) {
- logger.warning("Name for [" + key + "] was empty.");
+ plugin.warning("[ItemUtils] Name for [" + key + "] was empty.");
continue;
}
MATERIAL_NAMES.put(material, ChatUtils.parseColor(name));
}
- logger.info("Loaded a total of " + MATERIAL_NAMES.size() + " item names from materials.yml");
+ plugin.info("[ItemUtils] 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()) {
- logger.warning("The following materials are missing from materials.yml: " +
+ plugin.warning("[ItemUtils] The following materials are missing from materials.yml: " +
missing.stream().map(Enum::name).collect(Collectors.joining(",")) + ".");
}
}
@@ -76,7 +73,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, (ignored) -> material.name());
+ return MATERIAL_NAMES.computeIfAbsent(material, (_material) -> material.name());
}
/**
@@ -86,10 +83,7 @@ public static String getItemName(final Material material) {
* @return Returns the item's name.
*/
public static String getItemName(final ItemStack item) {
- if (item == null) {
- return null;
- }
- return getItemName(item.getType());
+ return getItemName(Chainer.from(item).then(ItemStack::getType).get());
}
/**
@@ -101,9 +95,16 @@ public static String getItemName(final ItemStack item) {
* @return Returns true if the item is valid.
*/
public static boolean isValidItem(final ItemStack item) {
- return item != null
- && isValidItemMaterial(item.getType())
- && isValidItemAmount(item);
+ if (item == null) {
+ return false;
+ }
+ if (!isValidItemMaterial(item.getType())) {
+ return false;
+ }
+ if (!isValidItemAmount(item)) {
+ return false;
+ }
+ return true;
}
/**
@@ -113,9 +114,16 @@ && isValidItemMaterial(item.getType())
* @return Returns true if the item has a valid amount.
*/
public static boolean isValidItemAmount(ItemStack item) {
- return item != null
- && item.getAmount() > 0
- && item.getAmount() <= item.getMaxStackSize();
+ if (item == null) {
+ return false;
+ }
+ if (item.getAmount() <= 0) {
+ return false;
+ }
+ if (item.getAmount() > item.getMaxStackSize()) {
+ return false;
+ }
+ return true;
}
/**
@@ -125,50 +133,35 @@ 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) {
- return material != null
- && !material.isAir()
- && material.isItem();
- }
-
- /**
- * 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 functionally identical.
- *
- * @see ItemStack#isSimilar(ItemStack)
- */
- public static boolean areItemsEqual(final ItemStack former, final ItemStack latter) {
- if (former == latter) {
- return true;
+ if (material == null) {
+ return false;
}
- return (former != null && latter != null)
- && former.getAmount() == latter.getAmount()
- && areItemsSimilar(former, latter);
+ if (material.isAir()) {
+ return false;
+ }
+ if (!material.isItem()) {
+ return false;
+ }
+ return true;
}
/**
- * Determines whether two item stacks are similar.
+ * 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.
+ * @return Returns true if both items are similar and not null.
*
* @see ItemStack#isSimilar(ItemStack)
*/
public static boolean areItemsSimilar(final ItemStack former, final ItemStack latter) {
- if (former == latter) {
+ if (former != null && former.isSimilar(latter)) {
return true;
}
- 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;
+ if (latter != null && latter.isSimilar(former)) {
+ return true;
}
- return MetaUtils.areMetasEqual(former.getItemMeta(), latter.getItemMeta());
+ return false;
}
/**
@@ -207,10 +200,7 @@ public static ItemStack normalizeItem(ItemStack item) {
* @return Returns the item meta.
*/
public static ItemMeta getItemMeta(final ItemStack item) {
- if (item == null) {
- return null;
- }
- return item.getItemMeta();
+ return Chainer.from(item).then(ItemStack::getItemMeta).get();
}
/**
@@ -220,8 +210,7 @@ public static ItemMeta getItemMeta(final ItemStack item) {
* @return Returns true if the item has a display name.
*/
public static boolean hasDisplayName(final ItemStack item) {
- final var meta = getItemMeta(item);
- return meta != null && meta.hasDisplayName();
+ return Strings.isNullOrEmpty(getDisplayName(item));
}
/**
@@ -230,12 +219,8 @@ public static boolean hasDisplayName(final ItemStack item) {
* @param item The item to retrieve the display name from.
* @return Returns the display name of an item.
*/
- public static Component getComponentDisplayName(final ItemStack item) {
- final var meta = getItemMeta(item);
- if (meta == null) {
- return null;
- }
- return meta.displayName();
+ public static String getDisplayName(final ItemStack item) {
+ return Chainer.from(getItemMeta(item)).then(ItemMeta::getDisplayName).get();
}
/**
@@ -246,12 +231,17 @@ public static Component getComponentDisplayName(final ItemStack item) {
*
* @throws IllegalArgumentException Throws when the given item has no meta.
*/
- public static void setComponentDisplayName(final ItemStack item, final Component name) {
- final var meta = getItemMeta(item);
+ public static void setDisplayName(final ItemStack item, final String name) {
+ final ItemMeta meta = getItemMeta(item);
if (meta == null) {
throw new IllegalArgumentException("Cannot set that display name: item has no meta.");
}
- meta.displayName(name);
+ if (Strings.isNullOrEmpty(name)) {
+ meta.setDisplayName(null);
+ }
+ else {
+ meta.setDisplayName(name);
+ }
item.setItemMeta(meta);
}
@@ -261,13 +251,8 @@ public static void setComponentDisplayName(final ItemStack item, final Component
* @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<>(0);
- }
- return MetaUtils.getComponentLore(meta);
+ public static List getLore(final ItemStack item) {
+ return MetaUtils.getLore(getItemMeta(item));
}
/**
@@ -280,13 +265,10 @@ public static List getComponentLore(final ItemStack item) {
*
* @throws IllegalArgumentException Throws when the given item has no meta.
*/
- public static void setComponentLore(final ItemStack item, final Component... 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);
+ public static void setLore(final ItemStack item, final String... lines) {
+ final List lore = new ArrayList<>();
+ CollectionUtils.addAll(lore, lines);
+ setLore(item, lore);
}
/**
@@ -299,24 +281,25 @@ public static void setComponentLore(final ItemStack item, final Component... lin
*
* @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);
+ public static void setLore(final ItemStack item, final List lines) {
+ final ItemMeta meta = getItemMeta(item);
if (meta == null) {
throw new IllegalArgumentException("Cannot set that lore: item has no meta.");
}
- MetaUtils.setComponentLore(meta, lines);
+ meta.setLore(lines);
item.setItemMeta(meta);
}
/**
- * Clears the lore from an item.
+ * Appends lore to an item.
*
- * @param item The item to clear lore of.
+ * @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 clearLore(final ItemStack item) {
- setLore(item, (List) null);
+ public static void addLore(final ItemStack item, final String... lines) {
+ addLore(item, false, lines);
}
/**
@@ -327,20 +310,24 @@ public static void clearLore(final ItemStack item) {
*
* @throws IllegalArgumentException Throws when the given item has no meta.
*/
- public static void addComponentLore(final ItemStack item, final Component... lines) {
- addComponentLore(item, false, lines);
+ public static void addLore(final ItemStack item, final List lines) {
+ addLore(item, false, lines);
}
/**
- * Appends lore to an item.
+ * 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 List lines) {
- addComponentLore(item, false, lines);
+ public static void addLore(final ItemStack item, final boolean prepend, final String... lines) {
+ handleItemMeta(item, (ItemMeta meta) -> {
+ MetaUtils.addLore(meta, prepend, lines);
+ return true;
+ });
}
/**
@@ -352,35 +339,22 @@ public static void addComponentLore(final ItemStack item, final List
*
* @throws IllegalArgumentException Throws when the given item has no meta.
*/
- public static void addComponentLore(final ItemStack item,
- final boolean prepend,
- final Component... 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);
+ public static void addLore(final ItemStack item, final boolean prepend, final List lines) {
+ handleItemMeta(item, (ItemMeta meta) -> {
+ MetaUtils.addLore(meta, prepend, lines);
+ return true;
+ });
}
/**
- * Adds lore to an item, either by appending or prepending.
+ * Clears the lore from an item.
*
- * @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.
+ * @param item The item to clear lore of.
*
* @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);
+ public static void clearLore(final ItemStack item) {
+ setLore(item, (List) null);
}
/**
@@ -396,11 +370,13 @@ public static Damageable getDamageable(final ItemStack item) {
return null;
}
final Material material = item.getType();
- if (!isValidItemMaterial(material)
- || material.getMaxDurability() <= 0) {
+ if (!isValidItemMaterial(material)) {
return null;
}
- final var meta = getItemMeta(item);
+ if (material.getMaxDurability() <= 0) {
+ return null;
+ }
+ final ItemMeta meta = item.getItemMeta();
if (!(meta instanceof Damageable)) {
return null;
}
@@ -447,188 +423,8 @@ public static boolean handleItemMeta(final ItemStack item, final Predicate getLore(final ItemStack item) {
- final var meta = getItemMeta(item);
- if (meta == null) {
- return new ArrayList<>(0);
- }
- return MetaUtils.getLore(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.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
- * Use {@link #setComponentLore(ItemStack, Component...)} instead.
- */
- @Deprecated
- public static void setLore(final ItemStack item, final String... lines) {
- final List lore = new ArrayList<>();
- CollectionUtils.addAll(lore, lines);
- setLore(item, 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 ItemUtils#clearLore(ItemStack)
- *
- * @throws IllegalArgumentException Throws when the given item has no meta.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
- * Use {@link #setComponentLore(ItemStack, List)} instead.
- */
- @Deprecated
- public static void setLore(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.");
- }
- 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.
- *
- * @throws IllegalArgumentException Throws when the given item has no meta.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
- * Use {@link #addComponentLore(ItemStack, Component...)} instead.
- */
- @Deprecated
- public static void addLore(final ItemStack item, final String... lines) {
- addLore(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.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
- * Use {@link #addComponentLore(ItemStack, List)} instead.
- */
- @Deprecated
- public static void addLore(final ItemStack item, final 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.
- *
- * @throws IllegalArgumentException Throws when the given item has no meta.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
- * Use {@link #addComponentLore(ItemStack, boolean, Component...)} instead.
- */
- @Deprecated
- public static void addLore(final ItemStack item, final boolean prepend, final String... lines) {
- 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);
- }
-
- /**
- * 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.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
- * Use {@link #addComponentLore(ItemStack, boolean, List)} instead.
- */
- @Deprecated
- public static void addLore(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.addLore(meta, prepend, lines);
- item.setItemMeta(meta);
- }
-
}
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 c1a64f84..0533bfc6 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,21 +1,16 @@
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.Objects;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
-import net.kyori.adventure.text.Component;
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.chat.ChatUtils;
/**
* Class of static utilities for when you already have an instance of {@link ItemMeta}, such as
@@ -24,54 +19,6 @@
*/
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.displayName(null);
- fakeFormer.lore(null);
- fakeLatter.displayName(null);
- fakeLatter.lore(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()) {
- if (!ChatUtils.areComponentsEqual(
- former.displayName(),
- latter.displayName())) {
- return false;
- }
- }
- if (former.hasLore() != latter.hasLore()) {
- return false;
- }
- if (former.hasLore()) {
- if (!Objects.equals(
- getComponentLore(former),
- getComponentLore(latter))) {
- return false;
- }
- }
- return true;
- }
-
/**
* Retrieves the lore from a given item meta.
*
@@ -79,197 +26,41 @@ public static boolean areMetasEqual(final ItemMeta former, final ItemMeta latter
* @return Returns the lore, which is never null.
*/
@Nonnull
- public static List getComponentLore(@Nonnull final ItemMeta meta) {
- final List lore = meta.lore();
- if (CollectionUtils.isEmpty(lore)) {
- return new ArrayList<>(0);
- }
- return lore;
- }
-
- /**
- * 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 Component... lines) {
- if (ArrayUtils.isEmpty(lines)) {
- meta.lore(null);
- return;
- }
- meta.lore(Arrays.asList(lines));
- }
-
- /**
- * 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.lore(null);
- return;
- }
- meta.lore(lines);
- }
-
- /**
- * Clears the lore from an item meta.
- *
- * @param meta The item meta to clear the lore of.
- */
- public static void clearLore(@Nonnull final ItemMeta meta) {
- meta.lore(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 Component... 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 Component... lines) {
- if (ArrayUtils.isEmpty(lines)) {
- return;
- }
- final List lore = getComponentLore(meta);
- if (prepend) {
- ArrayUtils.reverse(lines);
- for (final Component 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 Component 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
- * does actually apply an enchantment to an item.
- *
- * @param meta Item meta to apply glow to.
- */
- public static void addGlow(@Nonnull final ItemMeta meta) {
- meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
- meta.addEnchant(Enchantment.DURABILITY, 1, true); // true = ignoreLevelRestriction
- }
-
- // ------------------------------------------------------------
- // Deprecated Functions
- // ------------------------------------------------------------
-
- /**
- * 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.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
- * Use {@link #getComponentLore(ItemMeta)} instead.
- */
- @Deprecated
- @Nonnull
public static List getLore(@Nonnull final ItemMeta meta) {
final List lore = meta.getLore();
if (lore == null) {
- return new ArrayList<>(0);
+ return new ArrayList<>();
}
return lore;
}
/**
- * 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.
+ * Appends lore to an item.
*
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
- * Use {@link #addComponentLore(ItemMeta, Component...)} instead.
+ * @param meta The item to append the lore to.
+ * @param lines The lore to append to the item.
*/
- @Deprecated
public static void addLore(@Nonnull final ItemMeta meta, final String... lines) {
addLore(meta, false, lines);
}
/**
- * Appends lore to an item meta.
+ * Appends lore to an item.
*
- * @param meta The item meta to append the lore to.
- * @param lines The lore to append to the item meta.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
- * Use {@link #addComponentLore(ItemMeta, List)} instead.
+ * @param meta The item to append the lore to.
+ * @param lines The lore to append to the item.
*/
- @Deprecated
public static void addLore(@Nonnull final ItemMeta meta, final List lines) {
addLore(meta, false, lines);
}
/**
- * Adds lore to an item meta, either by appending or prepending.
+ * Adds lore to an item, either by appending or prepending.
*
- * @param meta The item meta to append the lore to.
+ * @param meta 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 meta.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
- * Use {@link #addComponentLore(ItemMeta, boolean, Component...)} instead.
+ * @param lines The lore to append to the item.
*/
- @Deprecated
public static void addLore(@Nonnull final ItemMeta meta, final boolean prepend, final String... lines) {
if (ArrayUtils.isEmpty(lines)) {
return;
@@ -288,16 +79,12 @@ public static void addLore(@Nonnull final ItemMeta meta, final boolean prepend,
}
/**
- * Adds lore to an item meta, either by appending or prepending.
+ * Adds lore to an item, either by appending or prepending.
*
- * @param meta The item meta to append the lore to.
+ * @param meta 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 meta.
- *
- * @deprecated Has been deprecated due to Paper's move to Kyori's Adventure.
- * Use {@link #addComponentLore(ItemMeta, boolean, List)} instead.
+ * @param lines The lore to append to the item.
*/
- @Deprecated
public static void addLore(@Nonnull final ItemMeta meta, final boolean prepend, final List lines) {
if (CollectionUtils.isEmpty(lines)) {
return;
@@ -315,4 +102,25 @@ public static void addLore(@Nonnull final ItemMeta meta, final boolean prepend,
meta.setLore(lore);
}
+ /**
+ * Clears the lore from an item.
+ *
+ * @param meta The item meta to clear the lore of.
+ */
+ public static void clearLore(@Nonnull final ItemMeta meta) {
+ meta.setLore(null);
+ }
+
+ /**
+ * 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 meta Item meta to apply glow to.
+ */
+ public static void addGlow(@Nonnull final ItemMeta meta) {
+ meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
+ meta.addEnchant(Enchantment.DURABILITY, 1, true); // true = ignoreLevelRestriction
+ }
+
}
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 5fd29988..dd427662 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,7 +14,6 @@
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;
/**
@@ -109,8 +108,6 @@ 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());
@@ -217,7 +214,6 @@ 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<>();
@@ -228,7 +224,7 @@ public static void init() {
missing.removeIf(Tag.FIRE::isTagged);
missing.removeIf(CROPS::isTagged);
if (!missing.isEmpty()) {
- logger.warning("The following crops are missing: " +
+ Bukkit.getLogger().warning("[MoreTags] 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 73173449..3791f3bc 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,14 +83,13 @@ 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()) {
- logger.warning("The following potion types are missing: " +
+ Bukkit.getLogger().warning("[PotionUtils] The following potion types are missing: " +
missing.stream().map(Enum::name).collect(Collectors.joining(",")) + ".");
}
}
@@ -100,7 +99,7 @@ public static void init() {
CollectionUtils.addAll(missing, PotionEffectType.values());
missing.removeIf(EFFECTS::containsKey);
if (!missing.isEmpty()) {
- logger.warning("The following potion effects are missing: " +
+ Bukkit.getLogger().warning("[PotionUtils] 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 2d36ac45..54b00fac 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,90 +7,88 @@
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.
*/
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_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();
+ 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();
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()) {
- logger.warning("The following spawn eggs are missing: " +
+ Bukkit.getLogger().warning("[SpawnEggUtils] 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 ee93c0e3..2b6d1bab 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,7 +109,6 @@ 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<>();
@@ -119,7 +118,7 @@ public static void init() {
CollectionUtils.addAll(missing, TreeType.values());
missing.removeIf(type -> exclude.contains(type) || TREE_MATERIALS.containsValue(type));
if (!missing.isEmpty()) {
- logger.warning("The following tree types are missing: " +
+ Bukkit.getLogger().warning("[TreeTypeUtils] The following tree types are missing: " +
missing.stream().map(Enum::name).collect(Collectors.joining(",")) + ".");
}
}
@@ -129,7 +128,7 @@ public static void init() {
CollectionUtils.addAll(missing, TreeType.values());
missing.removeIf(SAPLING_MATERIALS::containsKey);
if (!missing.isEmpty()) {
- logger.warning("The following sapling types are missing: " +
+ Bukkit.getLogger().warning("[TreeTypeUtils] The following sapling types are missing: " +
missing.stream().map(Enum::name).collect(Collectors.joining(",")) + ".");
}
}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUI.java b/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUI.java
new file mode 100644
index 00000000..a53d3f50
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUI.java
@@ -0,0 +1,356 @@
+package vg.civcraft.mc.civmodcore.inventorygui.paged;
+
+import com.google.common.base.Preconditions;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Objects;
+import java.util.Set;
+import java.util.Stack;
+import java.util.UUID;
+import org.bukkit.Bukkit;
+import org.bukkit.entity.Player;
+import org.bukkit.event.inventory.ClickType;
+import org.bukkit.event.inventory.InventoryClickEvent;
+import org.bukkit.inventory.Inventory;
+import org.bukkit.inventory.InventoryView;
+import org.bukkit.inventory.ItemStack;
+import org.bukkit.scheduler.BukkitTask;
+import vg.civcraft.mc.civmodcore.CivModCorePlugin;
+import vg.civcraft.mc.civmodcore.inventory.InventoryUtils;
+import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils;
+import vg.civcraft.mc.civmodcore.inventorygui.ClickableInventory;
+import vg.civcraft.mc.civmodcore.inventorygui.IClickable;
+
+/**
+ * Class that represents a proverbial slideshow of pages that can be switched to efficiently.
+ *
+ * You could also use {@link vg.civcraft.mc.civmodcore.inventorygui.MultiPageView}
+ */
+public final class PagedGUI {
+
+ private final int slots;
+
+ private final UUID uuid;
+
+ private final ClickableInventory inventory;
+
+ private final Stack history;
+
+ private Page currentPage;
+
+ /**
+ * Creates a paged GUI based on an amount of slots and a name.
+ *
+ * @param slots The amount of slots, which must pass a {@link InventoryUtils#isValidChestSize(int)} test.
+ * @param name The name for the GUI, which should be relevant across each page as it cannot be changed.
+ */
+ public PagedGUI(int slots, String name) {
+ Preconditions.checkArgument(InventoryUtils.isValidChestSize(slots));
+ this.slots = slots;
+ this.uuid = UUID.randomUUID();
+ this.inventory = new LegacyInventory(slots, name);
+ this.history = new Stack<>();
+ this.currentPage = null;
+ }
+
+ /**
+ * Resets the paged GUI if there's one or fewer viewers.
+ *
+ * @return Returns true if the paged GUI was reset.
+ */
+ public boolean reset() {
+ if (InventoryUtils.hasOtherViewers(this.inventory.getInventory())) {
+ return false;
+ }
+ InventoryUtils.clearInventory(this.inventory.getInventory());
+ this.history.clear();
+ this.currentPage = null;
+ return true;
+ }
+
+ /**
+ *
Creates a new page to be used for this paged GUI.
+ *
+ *
Note: The returned page will be forever bound to this paged GUI, do not try to use it for another.
+ *
+ * @return Returns a new page for this GUI.
+ */
+ public Page createPage() {
+ return new Page();
+ }
+
+ /**
+ * Presents this paged GUI to a player.
+ *
+ * @param player The player to present this paged GUI to.
+ * @return Returns true if the player was successfully presented with this paged GUI.
+ */
+ public boolean showGUI(Player player) {
+ Preconditions.checkArgument(player != null);
+ InventoryView view = player.openInventory(getInventory());
+ if (view == null) {
+ return false;
+ }
+ PagedGUIManager.GUIs.put(getInventory(), this);
+ return true;
+ }
+
+ /**
+ *
Handler for when this paged GUI has been clicked.
+ *
+ *
Note: Only {@link PagedGUIManager#onInventoryClick(InventoryClickEvent)} should call this method.
+ *
+ * @param slot The slot of the button that has been clicked.
+ * @param clicker The player who clicked the button.
+ */
+ void clicked(int slot, Player clicker, ClickType clickType) {
+ if (this.currentPage == null) {
+ return;
+ }
+ IClickable button = this.currentPage.getButton(slot);
+ if (button == null) {
+ return;
+ }
+ button.handleClick(clicker, clickType);
+ }
+
+ /**
+ * @return Returns how many slots this GUI has.
+ */
+ public int getSlotCount() {
+ return this.slots;
+ }
+
+ /**
+ * @return Returns the underlying inventory storing the items representing buttons.
+ */
+ public Inventory getInventory() {
+ return this.inventory.getInventory();
+ }
+
+ /**
+ * Clears this GUI's page lineage, making the current page the root page.
+ */
+ public void clearPageLineage() {
+ this.history.clear();
+ }
+
+ /**
+ * Gets the current page.
+ *
+ * @return Returns the current page, which may be null.
+ */
+ public Page getCurrentPage() {
+ return this.currentPage;
+ }
+
+ /**
+ * Sets the current page. Will add the previous current page to the lineage.
+ *
+ * @param page The page to set, which cannot be null.
+ */
+ public void setCurrentPage(Page page) {
+ setCurrentPage(page, true);
+ }
+
+ /**
+ * Sets the current page.
+ *
+ * @param page The page to set, which cannot be null.
+ * @param addPreviousToHistory If true will add the previous current page to the lineage.
+ */
+ public void setCurrentPage(Page page, boolean addPreviousToHistory) {
+ Preconditions.checkArgument(page != null && page.getGUI() == this);
+ Page previousPage = this.currentPage;
+ if (previousPage == page) {
+ return;
+ }
+ this.currentPage = page;
+ if (previousPage != null) {
+ if (addPreviousToHistory) {
+ this.history.push(previousPage);
+ }
+ previousPage.hidden();
+ }
+ page.showGUI();
+ updateGUI();
+ }
+
+ /**
+ * Goes to the previous page within the lineage. If no lineage can be found then the GUI is emptied.
+ */
+ public void goToPreviousPage() {
+ if (!this.history.isEmpty()) {
+ Page page = this.history.pop();
+ if (page != null) {
+ setCurrentPage(page, false);
+ return;
+ }
+ }
+ this.currentPage = null;
+ InventoryUtils.clearInventory(this.inventory.getInventory());
+ updateGUI();
+ }
+
+ private void updateGUI() {
+ Bukkit.getScheduler().scheduleSyncDelayedTask(CivModCorePlugin.getInstance(), this.inventory::updateInventory);
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof PagedGUI)) {
+ return false;
+ }
+ if (hashCode() != other.hashCode()) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(this.uuid, this.inventory);
+ }
+
+ /**
+ * Class that represents a page of a gui, a proverbial slide of a slideshow.
+ */
+ public final class Page {
+
+ private final IClickable[] items;
+
+ private final Set tasks;
+
+ private Page() {
+ this.items = new IClickable[slots];
+ this.tasks = new HashSet<>();
+ }
+
+ private void showGUI() {
+ for (int i = 0; i < slots; i++) {
+ IClickable clickable = this.items[i];
+ if (clickable == null) {
+ inventory.setItem(null, i);
+ continue;
+ }
+ ItemStack button = clickable.getItemStack();
+ if (!ItemUtils.isValidItem(button)) {
+ inventory.setItem(null, i);
+ continue;
+ }
+ inventory.setItem(button, i);
+ clickable.addedToInventory(inventory, i);
+ }
+ }
+
+ private void hidden() {
+ this.tasks.forEach(BukkitTask::cancel);
+ this.tasks.clear();
+ }
+
+ /**
+ * Resets this page to if it had just been created.
+ */
+ public void reset() {
+ Arrays.fill(this.items, null);
+ hidden();
+ }
+
+ /**
+ * Gets the particular GUI this page is bound to. Do not attempt to use this page for another GUI, it will fail.
+ *
+ * @return Returns the GUI this page is bound to.
+ */
+ public PagedGUI getGUI() {
+ return PagedGUI.this;
+ }
+
+ /**
+ * Checks whether this page is currently being displayed.
+ *
+ * @return Returns true if this page is currently being displayed.
+ */
+ public boolean isCurrentPage() {
+ return currentPage == this;
+ }
+
+ /**
+ * Gets a button (a clickable) for a particular index.
+ *
+ * @param index The index to get the button for.
+ * @return Returns the button at the given index, or null.
+ */
+ public IClickable getButton(int index) {
+ return this.items[index];
+ }
+
+ /**
+ * Sets a button (a clickable) to a particular index.
+ *
+ * @param index The index to save the button to.
+ * @param button The button to save.
+ */
+ public void setButton(int index, IClickable button) {
+ this.items[index] = button;
+ }
+
+ /**
+ * Adds a task to this page. This feature pretty much exists to support
+ * {@link vg.civcraft.mc.civmodcore.inventorygui.AnimatedClickable AnimatedClickable}.
+ *
+ * @param task The task to add.
+ */
+ public void addTask(BukkitTask task) {
+ Preconditions.checkArgument(task != null);
+ Preconditions.checkArgument(!task.isCancelled());
+ Preconditions.checkArgument(task.isSync());
+ this.tasks.add(task);
+ }
+
+ /**
+ * Removes a task from the page and will be cancelled in the process.
+ *
+ * @param task The task to remove and cancel.
+ */
+ public void removeTask(BukkitTask task) {
+ Preconditions.checkArgument(task != null);
+ task.cancel();
+ this.tasks.remove(task);
+ }
+
+ }
+
+ /**
+ * This class is just a ClickableInventory to
+ */
+ public class LegacyInventory extends ClickableInventory {
+
+ public LegacyInventory(int size, String name) {
+ super(size, name);
+ }
+
+ @Override
+ public void registerTask(BukkitTask task) {
+ Preconditions.checkArgument(currentPage != null);
+ currentPage.addTask(task);
+ }
+
+ @Override
+ @Deprecated
+ public void showInventory(Player p) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void updateInventory() {
+ for (Player viewer : InventoryUtils.getViewingPlayers(getInventory())) {
+ viewer.updateInventory();
+ }
+ }
+
+ }
+
+}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUIManager.java b/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUIManager.java
new file mode 100644
index 00000000..3d53d50d
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/inventorygui/paged/PagedGUIManager.java
@@ -0,0 +1,77 @@
+package vg.civcraft.mc.civmodcore.inventorygui.paged;
+
+import java.util.HashMap;
+import java.util.Map;
+import org.bukkit.entity.Player;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.Listener;
+import org.bukkit.event.inventory.InventoryClickEvent;
+import org.bukkit.event.inventory.InventoryCloseEvent;
+import org.bukkit.inventory.Inventory;
+import vg.civcraft.mc.civmodcore.entities.EntityUtils;
+import vg.civcraft.mc.civmodcore.inventory.InventoryUtils;
+
+public final class PagedGUIManager implements Listener {
+
+ static final Map GUIs = new HashMap<>();
+
+ public static void closeAllGUIs() {
+ for (Map.Entry entry : GUIs.entrySet()) {
+ for (Player player : InventoryUtils.getViewingPlayers(entry.getKey())) {
+ player.closeInventory();
+ }
+ entry.getValue().reset();
+ }
+ GUIs.clear();
+ }
+
+ @EventHandler
+ public void onInventoryClose(InventoryCloseEvent event) {
+ GUIs.computeIfPresent(event.getInventory(), (k, gui) -> gui.reset() ? null : gui);
+ }
+
+ @EventHandler
+ public void onInventoryClick(InventoryClickEvent event) {
+ if (!EntityUtils.isPlayer(event.getWhoClicked())) {
+ return;
+ }
+ Player viewer = (Player) event.getWhoClicked();
+ PagedGUI gui = GUIs.get(event.getInventory());
+ if (gui == null) {
+ return;
+ }
+ switch (event.getAction()) {
+ // Disable unknown actions
+ default:
+ case UNKNOWN:
+ // These events are cursed. There's no way to know where the items are moving to or from, just cancel.
+ case COLLECT_TO_CURSOR:
+ case MOVE_TO_OTHER_INVENTORY:
+ event.setCancelled(true);
+ return;
+ // Leave these be as they aren't dangerous. Cloning a stack is an OP feature and clones to your cursor
+ case NOTHING:
+ case CLONE_STACK:
+ return;
+ // Allow the following in context to the player's inventory, but not when interacting with the GUI
+ case PICKUP_ONE:
+ case PICKUP_SOME:
+ case PICKUP_HALF:
+ case PICKUP_ALL:
+ case PLACE_ONE:
+ case PLACE_SOME:
+ case PLACE_ALL:
+ case SWAP_WITH_CURSOR:
+ case DROP_ONE_SLOT:
+ case DROP_ALL_SLOT:
+ case DROP_ONE_CURSOR:
+ case DROP_ALL_CURSOR:
+ case HOTBAR_MOVE_AND_READD:
+ case HOTBAR_SWAP: {
+ event.setCancelled(true);
+ gui.clicked(event.getSlot(), viewer, event.getClick());
+ }
+ }
+ }
+
+}
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 79ed44e1..fb6be0b6 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/itemHandling/ItemMap.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/itemHandling/ItemMap.java
@@ -19,7 +19,6 @@
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
@@ -303,7 +302,7 @@ public int getAmount(ItemStack is) {
int amount = 0;
for (Entry entry : matSubMap.getEntrySet()) {
ItemStack current = entry.getKey();
- if (MetaUtils.areMetasEqual(is.getItemMeta(), current.getItemMeta())) {
+ if (is.getItemMeta().equals(current.getItemMeta())) {
amount += entry.getValue();
}
}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/maps/MapColours.java b/src/main/java/vg/civcraft/mc/civmodcore/maps/MapColours.java
deleted file mode 100644
index 184e3853..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/maps/MapColours.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package vg.civcraft.mc.civmodcore.maps;
-
-import java.util.Collection;
-import java.util.Objects;
-import java.util.Set;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-import javax.annotation.Nonnull;
-import net.minecraft.server.v1_16_R3.MaterialMapColor;
-import org.apache.commons.collections4.CollectionUtils;
-import vg.civcraft.mc.civmodcore.util.CivLogger;
-
-/**
- * Reference
- */
-public enum MapColours {
-
- NONE(MaterialMapColor.b),
- GRASS(MaterialMapColor.c),
- SAND(MaterialMapColor.d),
- WOOL(MaterialMapColor.e), // White wool
- FIRE(MaterialMapColor.f),
- ICE(MaterialMapColor.g),
- METAL(MaterialMapColor.h),
- PLANT(MaterialMapColor.i),
- SNOW(MaterialMapColor.j),
- CLAY(MaterialMapColor.k),
- DIRT(MaterialMapColor.l),
- STONE(MaterialMapColor.m),
- WATER(MaterialMapColor.n),
- WOOD(MaterialMapColor.o),
- QUARTZ(MaterialMapColor.p),
- COLOR_ORANGE(MaterialMapColor.q),
- COLOR_MAGENTA(MaterialMapColor.r),
- COLOR_LIGHT_BLUE(MaterialMapColor.s),
- COLOR_YELLOW(MaterialMapColor.t),
- COLOR_LIGHT_GREEN(MaterialMapColor.u),
- COLOR_PINK(MaterialMapColor.v),
- COLOR_GRAY(MaterialMapColor.w),
- COLOR_LIGHT_GRAY(MaterialMapColor.x),
- COLOR_CYAN(MaterialMapColor.y),
- COLOR_PURPLE(MaterialMapColor.z),
- COLOR_BLUE(MaterialMapColor.A),
- COLOR_BROWN(MaterialMapColor.B),
- COLOR_GREEN(MaterialMapColor.C),
- COLOR_RED(MaterialMapColor.D),
- COLOR_BLACK(MaterialMapColor.E),
- GOLD(MaterialMapColor.F),
- DIAMOND(MaterialMapColor.G),
- LAPIS(MaterialMapColor.H),
- EMERALD(MaterialMapColor.I),
- PODZOL(MaterialMapColor.J),
- NETHER(MaterialMapColor.K),
- TERRACOTTA_WHITE(MaterialMapColor.L),
- TERRACOTTA_ORANGE(MaterialMapColor.M),
- TERRACOTTA_MAGENTA(MaterialMapColor.N),
- TERRACOTTA_LIGHT_BLUE(MaterialMapColor.O),
- TERRACOTTA_YELLOW(MaterialMapColor.P),
- TERRACOTTA_LIGHT_GREEN(MaterialMapColor.Q),
- TERRACOTTA_PINK(MaterialMapColor.R),
- TERRACOTTA_GRAY(MaterialMapColor.S),
- TERRACOTTA_LIGHT_GRAY(MaterialMapColor.T),
- TERRACOTTA_CYAN(MaterialMapColor.U),
- TERRACOTTA_PURPLE(MaterialMapColor.V),
- TERRACOTTA_BLUE(MaterialMapColor.W),
- TERRACOTTA_BROWN(MaterialMapColor.X),
- TERRACOTTA_GREEN(MaterialMapColor.Y),
- TERRACOTTA_RED(MaterialMapColor.Z),
- TERRACOTTA_BLACK(MaterialMapColor.aa),
- CRIMSON_NYLIUM(MaterialMapColor.ab),
- CRIMSON_STEM(MaterialMapColor.ac),
- CRIMSON_HYPHAE(MaterialMapColor.ad),
- WARPED_NYLIUM(MaterialMapColor.ae),
- WARPED_STEM(MaterialMapColor.af),
- WARPED_HYPHAE(MaterialMapColor.ag),
- WARPED_WART_BLOCK(MaterialMapColor.ah);
-
- private final MaterialMapColor nms;
-
- MapColours(@Nonnull final MaterialMapColor nms) {
- this.nms = Objects.requireNonNull(nms);
- }
-
- public MaterialMapColor asNMS() {
- return this.nms;
- }
-
- public static void init() {
- final Set coreMapColours = Set.of(Stream.of(values())
- .map(MapColours::asNMS)
- .toArray(MaterialMapColor[]::new));
- final Set baseMapColours = Set.of(MaterialMapColor.a);
- final Collection missing = CollectionUtils.disjunction(coreMapColours, baseMapColours);
- missing.removeIf(Objects::isNull); // Remove all empty colors from baseMapColors
- if (!missing.isEmpty()) {
- final CivLogger logger = CivLogger.getLogger(MapColours.class);
- logger.warning("The following map colours are missing: " + missing.stream()
- .map(e -> Integer.toString(e.aj))
- .collect(Collectors.joining(",")));
- }
- }
-
-}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/collection/ListSetting.java b/src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/collection/ListSetting.java
index 9eb201c1..7730c0fd 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/collection/ListSetting.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/playersettings/impl/collection/ListSetting.java
@@ -11,7 +11,7 @@ public ListSetting(JavaPlugin owningPlugin, List defaultValue, String name, S
String description, Class elementClass) {
super(owningPlugin, defaultValue, name, identifier, gui, description, elementClass, (c) -> {
if (c == null) {
- return new ArrayList<>(0);
+ return new ArrayList<>();
}
return new ArrayList<>(c);
});
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCache.java b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCache.java
new file mode 100644
index 00000000..1949b3fd
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCache.java
@@ -0,0 +1,20 @@
+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 396a23fa..5015d8ec 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompound.java
@@ -23,9 +23,7 @@
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftItemStack;
-import org.bukkit.craftbukkit.v1_16_R3.persistence.CraftPersistentDataContainer;
import org.bukkit.inventory.ItemStack;
-import org.bukkit.persistence.PersistentDataContainer;
import vg.civcraft.mc.civmodcore.inventory.items.ItemUtils;
import vg.civcraft.mc.civmodcore.util.NullUtils;
import vg.civcraft.mc.civmodcore.util.Validation;
@@ -40,8 +38,11 @@ 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;
@@ -62,15 +63,6 @@ public NBTCompound(NBTTagCompound tag) {
this.tag = tag == null ? new NBTTagCompound() : tag;
}
- /**
- * Creates a new NBTCompound by wrapping an existing PersistentDataContainer.
- *
- * @param container The PersistentDataContainer to wrap.
- */
- public NBTCompound(final PersistentDataContainer container) {
- this(container == null ? null : new NBTTagCompound(((CraftPersistentDataContainer) container).getRaw()) {});
- }
-
/**
* Creates a new NBTCompound by wrapping and serialising an NBTSerializable object.
*
@@ -357,29 +349,12 @@ 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 {
- if (useMojangFormat) {
- this.tag.setLong(key + "Most", value.getMostSignificantBits());
- this.tag.setLong(key + "Least", value.getLeastSignificantBits());
- }
- else {
- this.tag.a(key, value);
- }
+ this.tag.a(key, value);
}
}
@@ -437,22 +412,8 @@ public void setString(String key, String value) {
* @return The value of the key, default: NULL
*/
public NBTCompound getCompound(String key) {
- return getCompound(key, false);
- }
-
- /**
- * Gets a tag compound value from a key.
- *
- * @param key The key to get the value of.
- * @param forceNonNull Whether to force the returned value to be non-null.
- * @return The value of the key, which is never null.
- */
- public NBTCompound getCompound(final String key, final boolean forceNonNull) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(key));
if (!this.tag.hasKeyOfType(key, 10)) {
- if (forceNonNull) {
- return new NBTCompound();
- }
return null;
}
return new NBTCompound(this.tag.getCompound(key));
@@ -864,6 +825,36 @@ 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
new file mode 100644
index 00000000..83fcdee8
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTCompoundList.java
@@ -0,0 +1,79 @@
+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.
+ */
+@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/serialization/NBTHelper.java b/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java
deleted file mode 100644
index ea854a9e..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/serialization/NBTHelper.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package vg.civcraft.mc.civmodcore.serialization;
-
-import java.util.UUID;
-import org.bukkit.Bukkit;
-import org.bukkit.Location;
-import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftItemStack;
-import org.bukkit.inventory.ItemStack;
-
-public final class NBTHelper {
-
- // ------------------------------------------------------------
- // Location
- // ------------------------------------------------------------
-
- private static final String LOCATION_WORLD_KEY = "world";
- private static final String LOCATION_X_KEY = "x";
- private static final String LOCATION_Y_KEY = "y";
- private static final String LOCATION_Z_KEY = "z";
- private static final String LOCATION_YAW_KEY = "yaw";
- private static final String LOCATION_PITCH_KEY = "pitch";
-
- public static Location locationFromNBT(final NBTCompound nbt) {
- if (nbt == null) {
- return null;
- }
- final UUID worldUUID = nbt.getUUID(LOCATION_WORLD_KEY);
- return new Location(
- worldUUID == null ? null : Bukkit.getWorld(worldUUID),
- nbt.getDouble(LOCATION_X_KEY),
- nbt.getDouble(LOCATION_Y_KEY),
- nbt.getDouble(LOCATION_Z_KEY),
- nbt.getFloat(LOCATION_YAW_KEY),
- nbt.getFloat(LOCATION_PITCH_KEY));
- }
-
- public static NBTCompound locationToNBT(final Location location) {
- if (location == null) {
- return null;
- }
- final var nbt = new NBTCompound();
- nbt.setUUID(LOCATION_WORLD_KEY, location.isWorldLoaded() ? location.getWorld().getUID() : null);
- nbt.setDouble(LOCATION_X_KEY, location.getX());
- nbt.setDouble(LOCATION_Y_KEY, location.getY());
- nbt.setDouble(LOCATION_Z_KEY, location.getZ());
- if (location.getYaw() != 0) {
- nbt.setFloat(LOCATION_YAW_KEY, location.getYaw());
- }
- if (location.getPitch() != 0) {
- nbt.setFloat(LOCATION_PITCH_KEY, location.getPitch());
- }
- return nbt;
- }
-
- // ------------------------------------------------------------
- // ItemStack
- // ------------------------------------------------------------
-
- public static ItemStack itemStackFromNBT(final NBTCompound nbt) {
- if (nbt == null) {
- return null;
- }
- return net.minecraft.server.v1_16_R3.ItemStack.fromCompound(nbt.getRAW()).getBukkitStack();
- }
-
- public static NBTCompound itemStackToNBT(final ItemStack item) {
- if (item == null) {
- return null;
- }
- final var nbt = new NBTCompound();
- CraftItemStack.asNMSCopy(item).save(nbt.getRAW());
- return nbt;
- }
-
-}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/storage/nbt/BatchedNbtStorage.java b/src/main/java/vg/civcraft/mc/civmodcore/storage/nbt/BatchedNbtStorage.java
deleted file mode 100644
index 5df82f57..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/storage/nbt/BatchedNbtStorage.java
+++ /dev/null
@@ -1,124 +0,0 @@
-package vg.civcraft.mc.civmodcore.storage.nbt;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import java.io.File;
-import java.util.Objects;
-import java.util.stream.Stream;
-import org.apache.commons.lang3.ArrayUtils;
-import org.bukkit.craftbukkit.libs.org.apache.commons.io.FileUtils;
-import org.bukkit.craftbukkit.libs.org.apache.commons.io.FilenameUtils;
-import vg.civcraft.mc.civmodcore.ACivMod;
-import vg.civcraft.mc.civmodcore.serialization.NBTCompound;
-import vg.civcraft.mc.civmodcore.util.CivLogger;
-
-public abstract class BatchedNbtStorage {
-
- protected static final String EXTENSION = "nbt";
-
- protected final CivLogger logger;
- protected final File storageFolder;
-
- public BatchedNbtStorage(final ACivMod plugin, final String folder) {
- Preconditions.checkArgument(!Strings.isNullOrEmpty(folder));
- this.logger = CivLogger.getLogger(getClass());
- this.storageFolder = new File(plugin.getDataFolder(), folder);
- }
-
- /**
- * Loads all the ".nbt" files from the storage folder.
- *
- * @return Returns a stream of all the correct parsed nbt files into their appropriate container.
- */
- public Stream loadAll() {
- if (!this.storageFolder.isDirectory()) {
- return Stream.empty().parallel();
- }
- final var files = this.storageFolder.listFiles();
- if (ArrayUtils.isEmpty(files)) {
- return Stream.empty().parallel();
- }
- assert files != null;
- return Stream.of(files)
- .parallel()
- .filter(file -> FilenameUtils.isExtension(file.getName(), EXTENSION))
- .map(this::loadFile)
- .filter(Objects::nonNull);
- }
-
- /**
- * Saves a given stream of elements to their respective files.
- *
- * @param elements The elements to save.
- * @return Returns a stream of all elements that were successfully saved.
- */
- public Stream saveSelected(final Stream elements) {
- if (elements == null) {
- return Stream.empty().parallel();
- }
- return elements.parallel()
- .filter(Objects::nonNull)
- .map(this::saveElement)
- .filter(Objects::nonNull); // Remove unsuccessful saves
- }
-
- /**
- * Removes all given elements' respective files.
- *
- * @param elements The elements to remove the files of.
- * @return Returns a stream of elements whose files could not be removed.
- */
- public Stream removeSelected(final Stream elements) {
- if (elements == null) {
- return Stream.empty().parallel();
- }
- return elements.parallel()
- .map(this::removeElement)
- .filter(Objects::nonNull); // Remove successful deletions
- }
-
- /**
- * This method is called during {@link #loadAll()} and is used to read and parse the data within the given file. You
- * should also check the file's name using maybe {@link FilenameUtils#getBaseName(String)} to ensure it's correctly
- * formatted. I'd recommend using {@link FileUtils#readFileToByteArray(File)} to read the file, then using
- * {@link NBTCompound#fromBytes(byte[])} to convert that into a usable NBT instance. If for whatever reason the file
- * cannot be correctly parsed, the correct course of action is to log the error using {@link this#logger} and
- * returning null.
- *
- * @param file The file to read and parse.
- * @return Returns a valid instance of the resulting container, or null if something went wrong.
- */
- protected abstract T loadFile(final File file);
-
- /**
- * This method is called during {@link #saveSelected(Stream)} and is used to save particular elements to their
- * respective files. You can use {@link #generateFileName(Object)} to determine what that filename should be. I'd
- * recommend you use {@link FileUtils#writeByteArrayToFile(File, byte[])} via
- * {@link NBTCompound#toBytes(NBTCompound)}. If the element was successfully saved, return the element or otherwise
- * return null.
- *
- * @param element The element to save to its respective file.
- * @return Returns the element if successfully saved, otherwise null.
- */
- protected abstract T saveElement(final T element);
-
- /**
- * This method is called during {@link #removeSelected(Stream)} and is used to delete particular elements' files.
- * You can use {@link #generateFileName(Object)} to determine what the file's name should be.
- *
- * @param element The element to delete the file of.
- * @return Returns null if the file was successfully deleted, otherwise return the given element.
- */
- protected abstract T removeElement(final T element);
-
- /**
- * Generates a filename based on the given object.
- *
- * @param object The object to base the filename off.
- * @return Returns a file name with the appropriate extension.
- */
- protected String generateFileName(final Object object) {
- return object + "." + EXTENSION;
- }
-
-}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java b/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
deleted file mode 100644
index ef3ddb94..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/util/CivLogger.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package vg.civcraft.mc.civmodcore.util;
-
-import com.destroystokyo.paper.utils.PaperPluginLogger;
-import com.google.common.base.Strings;
-import java.util.logging.LogRecord;
-import java.util.logging.Logger;
-import javax.annotation.Nonnull;
-import org.apache.commons.lang3.reflect.FieldUtils;
-import org.bukkit.Bukkit;
-import org.bukkit.plugin.PluginDescriptionFile;
-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(@Nonnull final Class> clazz) {
- final ClassLoader classLoader = clazz.getClassLoader();
- if (classLoader instanceof PluginClassLoader) {
- final var plugin = ((PluginClassLoader) classLoader).getPlugin();
- if (plugin != null) {
- return new CivLogger(plugin.getLogger(), clazz.getSimpleName());
- }
- // Plugin has been constructed but not initialised yet
- final var descriptionField = FieldUtils.getDeclaredField(PluginClassLoader.class, "description", true);
- try {
- final var description = (PluginDescriptionFile) descriptionField.get(classLoader);
- final var logger = PaperPluginLogger.getLogger(description);
- return new CivLogger(logger, clazz.getSimpleName());
- }
- catch (final IllegalAccessException ignored) {}
- }
- return new CivLogger(Bukkit.getLogger(), clazz.getSimpleName());
- }
-
-}
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/EnumUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/util/EnumUtils.java
new file mode 100644
index 00000000..14ba1f6e
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/EnumUtils.java
@@ -0,0 +1,72 @@
+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
new file mode 100644
index 00000000..da9b0cd0
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/Guard.java
@@ -0,0 +1,43 @@
+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
new file mode 100644
index 00000000..fa1c5ee2
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/Iteration.java
@@ -0,0 +1,350 @@
+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.
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.
+ *
+ * @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.
+ *
+ * @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
new file mode 100644
index 00000000..1f3fc284
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/MapUtils.java
@@ -0,0 +1,164 @@
+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/MoreCollectionUtils.java b/src/main/java/vg/civcraft/mc/civmodcore/util/MoreCollectionUtils.java
index 6bd86e83..093065f5 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/util/MoreCollectionUtils.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/MoreCollectionUtils.java
@@ -1,8 +1,6 @@
package vg.civcraft.mc.civmodcore.util;
-import it.unimi.dsi.fastutil.ints.Int2ObjectFunction;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
@@ -28,10 +26,7 @@ public final class MoreCollectionUtils {
*/
@SafeVarargs
public static > K collect(final Supplier constructor, final T... elements) {
- if (constructor == null) {
- return null;
- }
- final K collection = constructor.get();
+ final K collection = Chainer.from(constructor).then(Supplier::get).get();
if (collection == null) {
return null;
}
@@ -39,31 +34,6 @@ public static > K collect(final Supplier construct
return collection;
}
- /**
- * Creates a new collection with the exact size of 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.
- */
- @SafeVarargs
- public static > K collectExact(final Int2ObjectFunction constructor,
- final T... elements) {
- if (constructor == null) {
- return null;
- }
- if (elements == null) {
- return constructor.get(0);
- }
- final K collection = constructor.get(elements.length);
- if (collection != null) {
- Collections.addAll(collection, elements);
- }
- return collection;
- }
-
/**
*
Tests whether there is at least one element in the given collection that passes the criteria of the given
* predicate.
diff --git a/src/main/java/vg/civcraft/mc/civmodcore/util/NullCoalescing.java b/src/main/java/vg/civcraft/mc/civmodcore/util/NullCoalescing.java
new file mode 100644
index 00000000..e6093d9f
--- /dev/null
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/NullCoalescing.java
@@ -0,0 +1,185 @@
+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.
+ *
+ * @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/main/java/vg/civcraft/mc/civmodcore/util/Resettable.java b/src/main/java/vg/civcraft/mc/civmodcore/util/Resettable.java
deleted file mode 100644
index 85fddcf4..00000000
--- a/src/main/java/vg/civcraft/mc/civmodcore/util/Resettable.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package vg.civcraft.mc.civmodcore.util;
-
-/**
- * This exists to try and standardise initialising and resetting objects.
- */
-public interface Resettable {
-
- /**
- * Initialises this object, which is irrelevant to construction.
- */
- void init();
-
- /**
- * Resets this object, which is irrelevant to finalisation / closure.
- */
- void reset();
-
-}
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 e4af566a..714ab4d8 100644
--- a/src/main/java/vg/civcraft/mc/civmodcore/util/TextUtil.java
+++ b/src/main/java/vg/civcraft/mc/civmodcore/util/TextUtil.java
@@ -1,11 +1,13 @@
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;
@@ -60,7 +62,10 @@ public static String parse(String str) {
*/
@Deprecated
public static String parseColor(String string) {
- return ChatUtils.parseColor(string);
+ string = parseColorAmp(string);
+ string = parseColorAcc(string);
+ string = parseColorTags(string);
+ return string;
}
/**
@@ -68,7 +73,9 @@ public static String parseColor(String string) {
*/
@Deprecated
public static String parseColorAmp(String string) {
- return ChatUtils.parseColorAmp(string);
+ string = string.replace("&&", "&");
+ string = string.replaceAll("&([a-zA-Z0-9])", "§$1");
+ return string;
}
/**
@@ -76,7 +83,39 @@ public static String parseColorAmp(String string) {
*/
@Deprecated
public static String parseColorAcc(String string) {
- return ChatUtils.parseColorAcc(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());
}
/**
@@ -84,7 +123,52 @@ public static String parseColorAcc(String string) {
*/
@Deprecated
public static String parseColorTags(String string) {
- return ChatUtils.parseColorTags(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("