From 4483ce0d79adb64c01e5721e987e1f1b06ebbbc8 Mon Sep 17 00:00:00 2001 From: Dan Mulloy Date: Sun, 13 Aug 2017 23:00:51 -0400 Subject: [PATCH] Add NbtFactory#fromItemOptional This new method won't create tags if they don't already exists Fixes #376 --- .../protocol/wrappers/nbt/NbtFactory.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/modules/API/src/main/java/com/comphenix/protocol/wrappers/nbt/NbtFactory.java b/modules/API/src/main/java/com/comphenix/protocol/wrappers/nbt/NbtFactory.java index 834e1ded..42dbc611 100644 --- a/modules/API/src/main/java/com/comphenix/protocol/wrappers/nbt/NbtFactory.java +++ b/modules/API/src/main/java/com/comphenix/protocol/wrappers/nbt/NbtFactory.java @@ -26,6 +26,7 @@ import java.lang.reflect.Method; import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; @@ -168,6 +169,31 @@ public class NbtFactory { } return fromBase(result); } + + /** + * Constructs a wrapper for a NBT tag in an ItemStack. This is where auxillary + * data such as enchantments, name, and lore is stored. It doesn't include the material, + * damage value, or stack size. + *

+ * This differs from {@link #fromItemTag(ItemStack)} in that the tag is not created if it + * doesn't already exist. + * + * @param stack the ItemStack. Must be a CraftItemStack. Use {@link MinecraftReflection#getBukkitItemStack(Object)} + * @return A wrapper for the NBT tag if it exists, an empty Optional if not + */ + public static Optional> fromItemOptional(ItemStack stack) { + checkItemStack(stack); + + StructureModifier> modifier = getStackModifier(stack); + NbtBase result = modifier.read(0); + + // Create the tag if it doesn't exist + if (result == null) { + return Optional.empty(); + } + + return Optional.of(fromBase(result)); + } /** * Load a NBT compound from a GZIP compressed file.