Version 1.5.2:

* Added support for 1.18.2 by updating NBT-API internal dependency
This commit is contained in:
PretzelJohn 2022-03-05 09:01:42 -05:00
parent f4a8ecd21c
commit ea98a911d3
16 changed files with 794 additions and 197 deletions

View File

@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.pretzel.dev</groupId>
<artifactId>VillagerTradeLimiter</artifactId>
<version>1.5.1</version>
<version>1.5.2</version>
<properties>
<java.version>1.8</java.version>
@ -40,7 +40,7 @@
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.18.1-R0.1-SNAPSHOT</version>
<version>1.18.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>

View File

@ -3,22 +3,20 @@ package com.pretzel.dev.villagertradelimiter.nms;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.bukkit.inventory.ItemStack;
import com.pretzel.dev.villagertradelimiter.nms.utils.MinecraftVersion;
import com.pretzel.dev.villagertradelimiter.nms.utils.nmsmappings.ReflectionMethod;
import org.bukkit.inventory.ItemStack;
/**
* Base class representing NMS Compounds. For a standalone implementation check
* {@link NBTContainer}
*
*
* @author tr7zw
*
*/
@ -77,7 +75,7 @@ public class NBTCompound {
/**
* Merges all data from comp into this compound. This is done in one action, so
* it also works with Tiles/Entities
*
*
* @param comp
*/
public void mergeCompound(NBTCompound comp) {
@ -92,7 +90,7 @@ public class NBTCompound {
/**
* Setter
*
*
* @param key
* @param value
*/
@ -108,7 +106,7 @@ public class NBTCompound {
/**
* Getter
*
*
* @param key
* @return The stored value or NMS fallback
*/
@ -127,7 +125,7 @@ public class NBTCompound {
/**
* Setter
*
*
* @param key
* @param value
*/
@ -143,7 +141,7 @@ public class NBTCompound {
/**
* Getter
*
*
* @param key
* @return The stored value or NMS fallback
*/
@ -158,7 +156,7 @@ public class NBTCompound {
/**
* Setter
*
*
* @param key
* @param value
*/
@ -174,7 +172,7 @@ public class NBTCompound {
/**
* Getter
*
*
* @param key
* @return The stored value or NMS fallback
*/
@ -189,7 +187,7 @@ public class NBTCompound {
/**
* Setter
*
*
* @param key
* @param value
*/
@ -205,7 +203,7 @@ public class NBTCompound {
/**
* Getter
*
*
* @param key
* @return The stored value or NMS fallback
*/
@ -220,7 +218,7 @@ public class NBTCompound {
/**
* Setter
*
*
* @param key
* @param value
*/
@ -236,7 +234,7 @@ public class NBTCompound {
/**
* Getter
*
*
* @param key
* @return The stored value or NMS fallback
*/
@ -251,7 +249,7 @@ public class NBTCompound {
/**
* Setter
*
*
* @param key
* @param value
*/
@ -267,7 +265,7 @@ public class NBTCompound {
/**
* Getter
*
*
* @param key
* @return The stored value or NMS fallback
*/
@ -282,7 +280,7 @@ public class NBTCompound {
/**
* Setter
*
*
* @param key
* @param value
*/
@ -298,7 +296,7 @@ public class NBTCompound {
/**
* Getter
*
*
* @param key
* @return The stored value or NMS fallback
*/
@ -313,7 +311,7 @@ public class NBTCompound {
/**
* Setter
*
*
* @param key
* @param value
*/
@ -329,7 +327,7 @@ public class NBTCompound {
/**
* Getter
*
*
* @param key
* @return The stored value or NMS fallback
*/
@ -344,7 +342,7 @@ public class NBTCompound {
/**
* Setter
*
*
* @param key
* @param value
*/
@ -360,7 +358,7 @@ public class NBTCompound {
/**
* Getter
*
*
* @param key
* @return The stored value or NMS fallback
*/
@ -375,7 +373,7 @@ public class NBTCompound {
/**
* Setter
*
*
* @param key
* @param value
*/
@ -396,7 +394,7 @@ public class NBTCompound {
/**
* Getter
*
*
* @param key
* @return The stored value or NMS fallback
*/
@ -411,7 +409,7 @@ public class NBTCompound {
/**
* Uses Gson to store an {@link Serializable} Object
*
*
* @param key
* @param value
*/
@ -427,7 +425,7 @@ public class NBTCompound {
/**
* Uses Gson to retrieve a stored Object
*
*
* @param key
* @param type Class of the Object
* @return The created Object or null if empty
@ -443,7 +441,7 @@ public class NBTCompound {
/**
* Save an ItemStack as a compound under a given key
*
*
* @param key
* @param item
*/
@ -459,7 +457,7 @@ public class NBTCompound {
/**
* Get an ItemStack that was saved at the given key
*
*
* @param key
* @return
*/
@ -472,8 +470,8 @@ public class NBTCompound {
readLock.unlock();
}
}
/**
/**
* Setter
*
* @param key
@ -547,7 +545,7 @@ public class NBTCompound {
/**
* Creates a subCompound, or returns it if already provided
*
*
* @param name Key to use
* @return The subCompound Object
*/
@ -584,10 +582,10 @@ public class NBTCompound {
readLock.unlock();
}
}
/**
* The same as addCompound, just with a name that better reflects what it does
*
*
* @param name
* @return
*/
@ -625,6 +623,36 @@ public class NBTCompound {
}
}
/**
* @param name
* @return The retrieved Integer List
*/
public NBTList<int[]> getIntArrayList(String name) {
try {
writeLock.lock();
NBTList<int[]> list = NBTReflectionUtil.getList(this, name, NBTType.NBTTagIntArray, int[].class);
saveCompound();
return list;
} finally {
writeLock.unlock();
}
}
/**
* @param name
* @return The retrieved Integer List
*/
public NBTList<UUID> getUUIDList(String name) {
try {
writeLock.lock();
NBTList<UUID> list = NBTReflectionUtil.getList(this, name, NBTType.NBTTagIntArray, UUID.class);
saveCompound();
return list;
} finally {
writeLock.unlock();
}
}
/**
* @param name
* @return The retrieved Float List
@ -669,10 +697,10 @@ public class NBTCompound {
writeLock.unlock();
}
}
/**
* Returns the type of the list, null if not a list
*
*
* @param name
* @return
*/
@ -804,34 +832,34 @@ public class NBTCompound {
}
return false;
}
protected static boolean isEqual(NBTCompound compA, NBTCompound compB, String key) {
if(compA.getType(key) != compB.getType(key))return false;
switch(compA.getType(key)) {
case NBTTagByte:
return compA.getByte(key).equals(compB.getByte(key));
case NBTTagByteArray:
return Arrays.equals(compA.getByteArray(key), compB.getByteArray(key));
case NBTTagCompound:
return compA.getCompound(key).equals(compB.getCompound(key));
case NBTTagDouble:
return compA.getDouble(key).equals(compB.getDouble(key));
case NBTTagEnd:
return true; //??
case NBTTagFloat:
return compA.getFloat(key).equals(compB.getFloat(key));
case NBTTagInt:
return compA.getInteger(key).equals(compB.getInteger(key));
case NBTTagIntArray:
return Arrays.equals(compA.getIntArray(key), compB.getIntArray(key));
case NBTTagList:
return NBTReflectionUtil.getEntry(compA, key).toString().equals(NBTReflectionUtil.getEntry(compB, key).toString()); // Just string compare the 2 lists
case NBTTagLong:
return compA.getLong(key).equals(compB.getLong(key));
case NBTTagShort:
return compA.getShort(key).equals(compB.getShort(key));
case NBTTagString:
return compA.getString(key).equals(compB.getString(key));
case NBTTagByte:
return compA.getByte(key).equals(compB.getByte(key));
case NBTTagByteArray:
return Arrays.equals(compA.getByteArray(key), compB.getByteArray(key));
case NBTTagCompound:
return compA.getCompound(key).equals(compB.getCompound(key));
case NBTTagDouble:
return compA.getDouble(key).equals(compB.getDouble(key));
case NBTTagEnd:
return true; //??
case NBTTagFloat:
return compA.getFloat(key).equals(compB.getFloat(key));
case NBTTagInt:
return compA.getInteger(key).equals(compB.getInteger(key));
case NBTTagIntArray:
return Arrays.equals(compA.getIntArray(key), compB.getIntArray(key));
case NBTTagList:
return NBTReflectionUtil.getEntry(compA, key).toString().equals(NBTReflectionUtil.getEntry(compB, key).toString()); // Just string compare the 2 lists
case NBTTagLong:
return compA.getLong(key).equals(compB.getLong(key));
case NBTTagShort:
return compA.getShort(key).equals(compB.getShort(key));
case NBTTagString:
return compA.getString(key).equals(compB.getString(key));
}
return false;
}

View File

@ -0,0 +1,51 @@
package com.pretzel.dev.villagertradelimiter.nms;
import com.pretzel.dev.villagertradelimiter.nms.utils.nmsmappings.ClassWrapper;
import com.pretzel.dev.villagertradelimiter.nms.utils.nmsmappings.ReflectionMethod;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Integer implementation for NBTLists
*
* @author tr7zw
*
*/
public class NBTIntArrayList extends NBTList<int[]> {
private final NBTContainer tmpContainer;
protected NBTIntArrayList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
this.tmpContainer = new NBTContainer();
}
@Override
protected Object asTag(int[] object) {
try {
Constructor<?> con = ClassWrapper.NMS_NBTTAGINTARRAY.getClazz().getDeclaredConstructor(int[].class);
con.setAccessible(true);
return con.newInstance(object);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new NbtApiException("Error while wrapping the Object " + object + " to it's NMS object!", e);
}
}
@Override
public int[] get(int index) {
try {
Object obj = ReflectionMethod.LIST_GET.run(listObject, index);
ReflectionMethod.COMPOUND_SET.run(tmpContainer.getCompound(), "tmp", obj);
int[] val = tmpContainer.getIntArray("tmp");
tmpContainer.removeKey("tmp");
return val;
} catch (NumberFormatException nf) {
return null;
} catch (Exception ex) {
throw new NbtApiException(ex);
}
}
}

View File

@ -9,7 +9,7 @@ import com.pretzel.dev.villagertradelimiter.nms.utils.nmsmappings.ReflectionMeth
/**
* NBT class to access vanilla/custom tags on ItemStacks. This class doesn't
* autosave to the Itemstack, use getItem to get the changed ItemStack
*
*
* @author tr7zw
*
*/
@ -21,25 +21,25 @@ public class NBTItem extends NBTCompound {
/**
* Constructor for NBTItems. The ItemStack will be cloned!
*
*
* @param item
*/
public NBTItem(ItemStack item) {
this(item, false);
}
/**
* Constructor for NBTItems. The ItemStack will be cloned! If directApply is true,
* all changed will be mapped to the original item. Changes to the NBTItem will overwrite changes done
* to the original item in that case.
*
*
* @param item
* @param directApply
*/
public NBTItem(ItemStack item, boolean directApply) {
super(null, null);
if (item == null || item.getType() == Material.AIR) {
throw new NullPointerException("ItemStack can't be null/Air!");
throw new NullPointerException("ItemStack can't be null/Air! This is not a NBTAPI bug!");
}
this.directApply = directApply;
bukkitItem = item.clone();
@ -71,7 +71,7 @@ public class NBTItem extends NBTCompound {
*/
public void applyNBT(ItemStack item) {
if (item == null || item.getType() == Material.AIR) {
throw new NullPointerException("ItemStack can't be null/Air!");
throw new NullPointerException("ItemStack can't be null/Air! This is not a NBTAPI bug!");
}
NBTItem nbti = new NBTItem(new ItemStack(item.getType()));
nbti.mergeCompound(this);
@ -103,17 +103,17 @@ public class NBTItem extends NBTCompound {
item.setItemMeta(meta);
}
/**
* True, if the item has any tags now known for this item type.
*
*
* @return true when custom tags are present
*/
public boolean hasCustomNbtData() {
ItemMeta meta = bukkitItem.getItemMeta();
return !NBTReflectionUtil.getUnhandledNBTTags(meta).isEmpty();
ItemMeta meta = bukkitItem.getItemMeta();
return !NBTReflectionUtil.getUnhandledNBTTags(meta).isEmpty();
}
/**
* Remove all custom (non-vanilla) NBT tags from the NBTItem.
*/
@ -136,7 +136,7 @@ public class NBTItem extends NBTCompound {
/**
* This may return true even when the NBT is empty.
*
*
* @return Does the ItemStack have a NBTCompound.
*/
public boolean hasNBTData() {
@ -146,7 +146,7 @@ public class NBTItem extends NBTCompound {
/**
* Helper method that converts {@link ItemStack} to {@link NBTContainer} with
* all it's data like Material, Damage, Amount and Tags.
*
*
* @param item
* @return Standalone {@link NBTContainer} with the Item's data
*/
@ -157,7 +157,7 @@ public class NBTItem extends NBTCompound {
/**
* Helper method to do the inverse to "convertItemtoNBT". Creates an
* {@link ItemStack} using the {@link NBTCompound}
*
*
* @param comp
* @return ItemStack using the {@link NBTCompound}'s data
*/

View File

@ -9,8 +9,8 @@ import com.pretzel.dev.villagertradelimiter.nms.utils.nmsmappings.ReflectionMeth
public class NBTPersistentDataContainer extends NBTCompound {
private final PersistentDataContainer container;
protected NBTPersistentDataContainer(PersistentDataContainer container) {
public NBTPersistentDataContainer(PersistentDataContainer container) {
super(null, null);
this.container = container;
}
@ -27,5 +27,5 @@ public class NBTPersistentDataContainer extends NBTCompound {
map.clear();
ReflectionMethod.CRAFT_PERSISTENT_DATA_CONTAINER_PUT_ALL.run(container, compound);
}
}

View File

@ -1,13 +1,11 @@
package com.pretzel.dev.villagertradelimiter.nms;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
import java.util.Set;
import java.util.*;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
@ -22,7 +20,7 @@ import com.pretzel.dev.villagertradelimiter.nms.utils.nmsmappings.ReflectionMeth
/**
* Utility class for translating NBTApi calls to reflections into NMS code All
* methods are allowed to throw {@link NbtApiException}
*
*
* @author tr7zw
*
*/
@ -35,7 +33,7 @@ public class NBTReflectionUtil {
field_unhandledTags = ClassWrapper.CRAFT_METAITEM.getClazz().getDeclaredField("unhandledTags");
field_unhandledTags.setAccessible(true);
} catch (NoSuchFieldException e) {
}
}
@ -48,7 +46,7 @@ public class NBTReflectionUtil {
/**
* Gets the NMS Entity for a given Bukkit Entity
*
*
* @param entity Bukkit Entity
* @return NMS Entity
*/
@ -62,7 +60,7 @@ public class NBTReflectionUtil {
/**
* Reads in a InputStream as NMS Compound
*
*
* @param stream InputStream of any NBT file
* @return NMS Compound
*/
@ -70,13 +68,16 @@ public class NBTReflectionUtil {
try {
return ReflectionMethod.NBTFILE_READ.run(null, stream);
} catch (Exception e) {
try {
stream.close();
}catch(IOException ignore) {}
throw new NbtApiException("Exception while reading a NBT File!", e);
}
}
/**
* Writes a NMS Compound to an OutputStream
*
*
* @param nbt NMS Compound
* @param stream Stream to write to
* @return ???
@ -88,10 +89,10 @@ public class NBTReflectionUtil {
throw new NbtApiException("Exception while writing NBT!", e);
}
}
/**
* Writes a Compound to an OutputStream
*
*
* @param comp Compound
* @param stream Stream to write to
*/
@ -113,7 +114,7 @@ public class NBTReflectionUtil {
/**
* Simulates getOrCreateTag. If an Item doesn't yet have a Tag, it will return a
* new empty tag.
*
*
* @param nmsitem
* @return NMS Compound
*/
@ -128,7 +129,7 @@ public class NBTReflectionUtil {
/**
* Converts {@link NBTCompound} to NMS ItemStacks
*
*
* @param nbtcompound Any valid {@link NBTCompound}
* @return NMS ItemStack
*/
@ -147,7 +148,7 @@ public class NBTReflectionUtil {
/**
* Converts NMS ItemStacks to {@link NBTContainer}
*
*
* @param nmsitem NMS ItemStack
* @return {@link NBTContainer} with all the data
*/
@ -177,7 +178,7 @@ public class NBTReflectionUtil {
/**
* Gets the Vanilla NBT Compound from a given NMS Entity
*
*
* @param nmsEntity
* @return NMS NBT Compound
*/
@ -195,7 +196,7 @@ public class NBTReflectionUtil {
/**
* Loads all Vanilla tags from a NMS Compound into a NMS Entity
*
*
* @param nbtTag
* @param nmsEntity
* @return The NMS Entity
@ -211,7 +212,7 @@ public class NBTReflectionUtil {
/**
* Gets the NMS Compound from a given TileEntity
*
*
* @param tile
* @return NMS Compound with the Vanilla data
*/
@ -226,16 +227,16 @@ public class NBTReflectionUtil {
Object pos = ObjectCreator.NMS_BLOCKPOSITION.getInstance(tile.getX(), tile.getY(), tile.getZ());
o = ReflectionMethod.NMS_WORLD_GET_TILEENTITY.run(nmsworld, pos);
}
Object answer = null;
if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_18_R1)) {
answer = ReflectionMethod.TILEENTITY_GET_NBT_1181.run(o);
answer = ReflectionMethod.TILEENTITY_GET_NBT_1181.run(o);
} else {
answer = ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().newInstance();
ReflectionMethod.TILEENTITY_GET_NBT.run(o, answer);
answer = ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().newInstance();
ReflectionMethod.TILEENTITY_GET_NBT.run(o, answer);
}
if (answer == null) {
throw new NbtApiException("Unable to get NBTCompound from TileEntity! " + tile + " " + o);
throw new NbtApiException("Unable to get NBTCompound from TileEntity! " + tile + " " + o);
}
return answer;
} catch (Exception e) {
@ -245,7 +246,7 @@ public class NBTReflectionUtil {
/**
* Sets Vanilla tags from a NMS Compound to a TileEntity
*
*
* @param tile
* @param comp
*/
@ -261,7 +262,7 @@ public class NBTReflectionUtil {
o = ReflectionMethod.NMS_WORLD_GET_TILEENTITY.run(nmsworld, pos);
}
if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_17_R1)) {
ReflectionMethod.TILEENTITY_SET_NBT.run(o, comp);
ReflectionMethod.TILEENTITY_SET_NBT.run(o, comp);
}else if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_16_R1)) {
Object blockData = ReflectionMethod.TILEENTITY_GET_BLOCKDATA.run(o);
ReflectionMethod.TILEENTITY_SET_NBT_LEGACY1161.run(o, blockData, comp);
@ -275,7 +276,7 @@ public class NBTReflectionUtil {
/**
* Gets the subCompound with a given name from a NMS Compound
*
*
* @param compound
* @param name
* @return NMS Compound or null
@ -294,7 +295,7 @@ public class NBTReflectionUtil {
/**
* Creates a subCompound with a given name in the given NMS Compound
*
*
* @param comp
* @param name
*/
@ -322,7 +323,7 @@ public class NBTReflectionUtil {
/**
* Checks if the Compound is correctly linked to it's roots
*
*
* @param comp
* @return true if this is a valide Compound, else false
*/
@ -352,7 +353,7 @@ public class NBTReflectionUtil {
/**
* Merges the second {@link NBTCompound} into the first one
*
*
* @param comp Target for the merge
* @param nbtcompoundSrc Data to merge
*/
@ -381,7 +382,7 @@ public class NBTReflectionUtil {
/**
* Returns the content for a given key inside a Compound
*
*
* @param comp
* @param key
* @return Content saved under this key
@ -403,7 +404,7 @@ public class NBTReflectionUtil {
/**
* Sets a key in a {@link NBTCompound} to a given value
*
*
* @param comp
* @param key
* @param val
@ -431,7 +432,7 @@ public class NBTReflectionUtil {
/**
* Returns the List saved with a given key.
*
*
* @param comp
* @param key
* @param type
@ -461,6 +462,10 @@ public class NBTReflectionUtil {
return (NBTList<T>) new NBTDoubleList(comp, key, type, nbt);
} else if (clazz == Long.class) {
return (NBTList<T>) new NBTLongList(comp, key, type, nbt);
} else if (clazz == int[].class) {
return (NBTList<T>) new NBTIntArrayList(comp, key, type, nbt);
} else if (clazz == UUID.class) {
return (NBTList<T>) new NBTUUIDList(comp, key, type, nbt);
} else {
return null;
}
@ -468,7 +473,7 @@ public class NBTReflectionUtil {
throw new NbtApiException("Exception while getting a list with the type '" + type + "'!", ex);
}
}
public static NBTType getListType(NBTCompound comp, String key) {
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
@ -481,7 +486,7 @@ public class NBTReflectionUtil {
Object nbt = ReflectionMethod.COMPOUND_GET.run(workingtag, key);
String fieldname = "type";
if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_17_R1)) {
fieldname = "w";
fieldname = "w";
}
Field f = nbt.getClass().getDeclaredField(fieldname);
f.setAccessible(true);
@ -490,7 +495,7 @@ public class NBTReflectionUtil {
throw new NbtApiException("Exception while getting the list type!", ex);
}
}
public static Object getEntry(NBTCompound comp, String key) {
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
@ -509,7 +514,7 @@ public class NBTReflectionUtil {
/**
* Uses Gson to set a {@link Serializable} value in a Compound
*
*
* @param comp
* @param key
* @param value
@ -527,7 +532,7 @@ public class NBTReflectionUtil {
/**
* Uses Gson to load back a {@link Serializable} object from the Compound
*
*
* @param comp
* @param key
* @param type
@ -545,7 +550,7 @@ public class NBTReflectionUtil {
/**
* Deletes the given key
*
*
* @param comp
* @param key
*/
@ -563,7 +568,7 @@ public class NBTReflectionUtil {
/**
* Gets the Keyset inside this Compound
*
*
* @param comp
* @return Set of all keys
*/
@ -581,7 +586,7 @@ public class NBTReflectionUtil {
/**
* Sets data inside the Compound
*
*
* @param comp
* @param type
* @param key
@ -605,7 +610,7 @@ public class NBTReflectionUtil {
/**
* Gets data from the Compound
*
*
* @param comp
* @param type
* @param key

View File

@ -0,0 +1,53 @@
package com.pretzel.dev.villagertradelimiter.nms;
import com.pretzel.dev.villagertradelimiter.nms.utils.UUIDUtil;
import com.pretzel.dev.villagertradelimiter.nms.utils.nmsmappings.ClassWrapper;
import com.pretzel.dev.villagertradelimiter.nms.utils.nmsmappings.ReflectionMethod;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;
/**
* Integer implementation for NBTLists
*
* @author tr7zw
*
*/
public class NBTUUIDList extends NBTList<UUID> {
private final NBTContainer tmpContainer;
protected NBTUUIDList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
this.tmpContainer = new NBTContainer();
}
@Override
protected Object asTag(UUID object) {
try {
Constructor<?> con = ClassWrapper.NMS_NBTTAGINTARRAY.getClazz().getDeclaredConstructor(int[].class);
con.setAccessible(true);
return con.newInstance(UUIDUtil.uuidToIntArray(object));
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new NbtApiException("Error while wrapping the Object " + object + " to it's NMS object!", e);
}
}
@Override
public UUID get(int index) {
try {
Object obj = ReflectionMethod.LIST_GET.run(listObject, index);
ReflectionMethod.COMPOUND_SET.run(tmpContainer.getCompound(), "tmp", obj);
int[] val = tmpContainer.getIntArray("tmp");
tmpContainer.removeKey("tmp");
return UUIDUtil.uuidFromIntArray(val);
} catch (NumberFormatException nf) {
return null;
} catch (Exception ex) {
throw new NbtApiException(ex);
}
}
}

View File

@ -1,21 +1,30 @@
package com.pretzel.dev.villagertradelimiter.nms;
import com.pretzel.dev.villagertradelimiter.nms.utils.MinecraftVersion;
/**
* A generic {@link RuntimeException} that can be thrown by most methods in the
* NBTAPI.
*
*
* @author tr7zw
*
*/
public class NbtApiException extends RuntimeException {
/**
*
*
*/
private static final long serialVersionUID = -993309714559452334L;
/**
* Keep track of the plugin selfcheck.
* Null = not checked(silentquickstart/shaded)
* true = selfcheck failed
* false = everything should be fine, but apparently wasn't?
*/
public static Boolean confirmedBroken = null;
/**
*
*
*/
public NbtApiException() {
super();
@ -28,7 +37,7 @@ public class NbtApiException extends RuntimeException {
* @param writableStackTrace
*/
public NbtApiException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
super(generateMessage(message), cause, enableSuppression, writableStackTrace);
}
/**
@ -36,21 +45,32 @@ public class NbtApiException extends RuntimeException {
* @param cause
*/
public NbtApiException(String message, Throwable cause) {
super(message, cause);
super(generateMessage(message), cause);
}
/**
* @param message
*/
public NbtApiException(String message) {
super(message);
super(generateMessage(message));
}
/**
* @param cause
*/
public NbtApiException(Throwable cause) {
super(cause);
super(generateMessage(cause==null ? null : cause.toString()), cause);
}
private static String generateMessage(String message) {
if(message == null)return null;
if(confirmedBroken == null) {
return "[?]"+message;
}else if(confirmedBroken == false) {
return "[Selfchecked]"+message;
}
return "[" + MinecraftVersion.getVersion() + "]There were errors detected during the server self-check! Please, make sure that NBT-API is up to date. Error message: " + message;
}
}

View File

@ -0,0 +1,388 @@
package com.pretzel.dev.villagertradelimiter.nms.utils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
import static com.pretzel.dev.villagertradelimiter.nms.utils.MinecraftVersion.getLogger;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*
* This class is modified by tr7zw to work when the api is shaded into other peoples plugins.
*/
public class ApiMetricsLite {
private static final String PLUGINNAME = "ItemNBTAPI"; // DO NOT CHANGE THE NAME! else it won't link the data on bStats
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The version of the NBT-Api bStats
public static final int NBT_BSTATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Is bStats enabled on this server?
private boolean enabled;
// Should failed requests be logged?
private static boolean logFailedRequests;
// Should the sent data be logged?
private static boolean logSentData;
// Should the response text be logged?
private static boolean logResponseStatusText;
// The uuid of the server
private static String serverUUID;
// The plugin
private Plugin plugin;
/**
* Class constructor.
*
*/
public ApiMetricsLite() {
// The register method just uses any enabled plugin it can find to register. This *shouldn't* cause any problems, since the plugin isn't used any other way.
// Register our service
for(Plugin plug : Bukkit.getPluginManager().getPlugins()) {
plugin = plug;
if(plugin != null)
break;
}
if(plugin == null) {
return;// Didn't find any plugin that could work
}
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Should the sent data be logged?
config.addDefault("logSentData", false);
// Should the response text be logged?
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
}
// Load the data
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
enabled = config.getBoolean("enabled", true);
logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
if (enabled) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("NBT_BSTATS_VERSION"); // Create only one instance of the nbt-api bstats.
return;
} catch (NoSuchFieldException ignored) { }
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) { }
}
boolean fFound = found;
// Register our service
if(Bukkit.isPrimaryThread()){
Bukkit.getServicesManager().register(ApiMetricsLite.class, this, plugin, ServicePriority.Normal);
if (!fFound) {
getLogger().info("[NBTAPI] Using the plugin '" + plugin.getName() + "' to create a bStats instance!");
// We are the first!
startSubmitting();
}
}else{
Bukkit.getScheduler().runTask(plugin, () -> {
Bukkit.getServicesManager().register(ApiMetricsLite.class, this, plugin, ServicePriority.Normal);
if (!fFound) {
getLogger().info("[NBTAPI] Using the plugin '" + plugin.getName() + "' to create a bStats instance!");
// We are the first!
startSubmitting();
}
});
}
}
}
/**
* Checks if bStats is enabled.
*
* @return Whether bStats is enabled or not.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000l * 60l * 5l, 1000l * 60l * 30l);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JsonObject getPluginData() {
JsonObject data = new JsonObject();
data.addProperty("pluginName", PLUGINNAME); // Append the name of the plugin
data.addProperty("pluginVersion", MinecraftVersion.VERSION); // Append the version of the plugin
data.add("customCharts", new JsonArray());
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JsonObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
String bukkitName = Bukkit.getName();
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JsonObject data = new JsonObject();
data.addProperty("serverUUID", serverUUID);
data.addProperty("playerAmount", playerAmount);
data.addProperty("onlineMode", onlineMode);
data.addProperty("bukkitVersion", bukkitVersion);
data.addProperty("bukkitName", bukkitName);
data.addProperty("javaVersion", javaVersion);
data.addProperty("osName", osName);
data.addProperty("osArch", osArch);
data.addProperty("osVersion", osVersion);
data.addProperty("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JsonObject data = getServerData();
JsonArray pluginData = new JsonArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin);
} else { // old bstats version compatibility
try {
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
jsonStringGetter.setAccessible(true);
String jsonString = (String) jsonStringGetter.invoke(plugin);
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
pluginData.add(object);
}
} catch (ClassNotFoundException e) {
// minecraft version 1.14+
if (logFailedRequests) {
getLogger().log(Level.WARNING, "[NBTAPI][BSTATS] Encountered exception while posting request!", e);
// Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time
//this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception ", e);
}
continue; // continue looping since we cannot do any other thing.
}
}
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
}
}
} catch (NoSuchFieldException ignored) { }
}
data.add("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
getLogger().log(Level.WARNING, "[NBTAPI][BSTATS] Could not submit plugin stats of " + plugin.getName(), e);
// Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time
//plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}
}).start();
}
/**
* Sends the data to the bStats server.
*
* @param plugin Any plugin. It's just used to get a logger instance.
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
if (logSentData) {
getLogger().info("[NBTAPI][BSTATS] Sending data to bStats: " + data.toString());
// Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time
//plugin.getLogger().info("Sending data to bStats: " + data.toString());
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
if (logResponseStatusText) {
getLogger().info("[NBTAPI][BSTATS] Sent data to bStats and received response: " + builder.toString());
// Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time
//plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
}
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return new byte[0];
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes(StandardCharsets.UTF_8));
gzip.close();
return outputStream.toByteArray();
}
}

View File

@ -9,7 +9,7 @@ import org.bukkit.Bukkit;
* This class acts as the "Brain" of the NBTApi. It contains the main logger for
* other classes,registers bStats and checks rather Maven shading was done
* correctly.
*
*
* @author tr7zw
*
*/
@ -17,7 +17,7 @@ import org.bukkit.Bukkit;
public enum MinecraftVersion {
UNKNOWN(Integer.MAX_VALUE), // Use the newest known mappings
MC1_7_R4(174), MC1_8_R3(183), MC1_9_R1(191), MC1_9_R2(192), MC1_10_R1(1101), MC1_11_R1(1111), MC1_12_R1(1121),
MC1_13_R1(1131), MC1_13_R2(1132), MC1_14_R1(1141), MC1_15_R1(1151), MC1_16_R1(1161), MC1_16_R2(1162), MC1_16_R3(1163), MC1_17_R1(1171), MC1_18_R1(1181, true);
MC1_13_R1(1131), MC1_13_R2(1132), MC1_14_R1(1141), MC1_15_R1(1151), MC1_16_R1(1161), MC1_16_R2(1162), MC1_16_R3(1163), MC1_17_R1(1171), MC1_18_R1(1181, true), MC1_18_R2(1182, true);
private static MinecraftVersion version;
private static Boolean hasGsonSupport;
@ -30,15 +30,15 @@ public enum MinecraftVersion {
private static Logger logger = Logger.getLogger("NBTAPI");
// NBT-API Version
protected static final String VERSION = "2.9.0-SNAPSHOT";
protected static final String VERSION = "2.9.2";
private final int versionId;
private final boolean mojangMapping;
MinecraftVersion(int versionId) {
this(versionId, false);
}
MinecraftVersion(int versionId) {
this(versionId, false);
}
MinecraftVersion(int versionId, boolean mojangMapping) {
this.versionId = versionId;
this.mojangMapping = mojangMapping;
@ -55,29 +55,34 @@ public enum MinecraftVersion {
* @return True if method names are in Mojang format and need to be remapped internally
*/
public boolean isMojangMapping() {
return mojangMapping;
}
public String getPackageName() {
if(this == UNKNOWN) {
return values()[values().length-1].name().replace("MC", "v");
}
return this.name().replace("MC", "v");
return mojangMapping;
}
/**
/**
* This method is required to hot-wire the plugin during mappings generation for newer mc versions thanks to md_5 not used mojmap.
*
* @return
*/
public String getPackageName() {
if(this == UNKNOWN) {
return Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
}
return this.name().replace("MC", "v");
}
/**
* Returns true if the current versions is at least the given Version
*
*
* @param version The minimum version
* @return
*/
public static boolean isAtLeastVersion(MinecraftVersion version) {
return getVersion().getVersionId() >= version.getVersionId();
}
/**
* Returns true if the current versions newer (not equal) than the given version
*
*
* @param version The minimum version
* @return
*/
@ -88,7 +93,7 @@ public enum MinecraftVersion {
/**
* Getter for this servers MinecraftVersion. Also init's bStats and checks the
* shading.
*
*
* @return The enum for the MinecraftVersion this server is running
*/
public static MinecraftVersion getVersion() {
@ -105,19 +110,26 @@ public enum MinecraftVersion {
if (version != UNKNOWN) {
logger.info("[NBTAPI] NMS support '" + version.name() + "' loaded!");
} else {
logger.warning("[NBTAPI] Wasn't able to find NMS Support! Some functions may not work!");
logger.warning("[NBTAPI] This Server-Version(" + ver + ") is not supported by this NBT-API Version(" + VERSION + ") located at " + MinecraftVersion.class.getName() + ". The NBT-API will try to work as good as it can! Some functions may not work!");
}
init();
return version;
}
private static void init() {
try {
if (hasGsonSupport() && !bStatsDisabled)
new ApiMetricsLite();
} catch (Exception ex) {
logger.log(Level.WARNING, "[NBTAPI] Error enabling Metrics!", ex);
}
if (hasGsonSupport() && !updateCheckDisabled)
new Thread(() -> {
try {
VersionChecker.checkForUpdates();
} catch (Exception ex) {
logger.log(Level.WARNING, "[NBTAPI] Error while checking for updates!", ex);
logger.log(Level.WARNING, "[NBTAPI] Error while checking for updates! Error: " + ex.getMessage());
}
}).start();
// Maven's Relocate is clever and changes strings, too. So we have to use this
@ -182,17 +194,17 @@ public enum MinecraftVersion {
public static void disablePackageWarning() {
disablePackageWarning = true;
}
/**
* @return Logger used by the NBT-API
*/
public static Logger getLogger() {
return logger;
}
/**
* Replaces the NBT-API logger with a custom implementation.
*
*
* @param logger The new logger(can not be null!)
*/
public static void replaceLogger(Logger logger) {
@ -200,4 +212,4 @@ public enum MinecraftVersion {
MinecraftVersion.logger = logger;
}
}
}

View File

@ -0,0 +1,22 @@
package com.pretzel.dev.villagertradelimiter.nms.utils;
import java.util.UUID;
public class UUIDUtil {
public static UUID uuidFromIntArray(int[] is) {
return new UUID((long) is[0] << 32 | (long) is[1] & 4294967295L,
(long) is[2] << 32 | (long) is[3] & 4294967295L);
}
public static int[] uuidToIntArray(UUID uUID) {
long l = uUID.getMostSignificantBits();
long m = uUID.getLeastSignificantBits();
return leastMostToIntArray(l, m);
}
private static int[] leastMostToIntArray(long l, long m) {
return new int[]{(int) (l >> 32), (int) l, (int) (m >> 32), (int) m};
}
}

View File

@ -10,7 +10,6 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.pretzel.dev.villagertradelimiter.nms.NBTItem;
/**
@ -21,12 +20,13 @@ public class VersionChecker {
private static final String USER_AGENT = "nbt-api Version check";
private static final String REQUEST_URL = "https://api.spiget.org/v2/resources/7939/versions?size=100";
public static boolean hideOk = false;
protected static void checkForUpdates() throws Exception {
URL url = new URL(REQUEST_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("User-Agent", USER_AGENT);// Set
// User-Agent
// User-Agent
// If you're not sure if the request will be successful,
// you need to check the response code and use #getErrorStream if it
@ -43,18 +43,19 @@ public class VersionChecker {
int versionDifference = getVersionDifference(latest.get("name").getAsString());
if (versionDifference == -1) { // Outdated
MinecraftVersion.getLogger().log(Level.WARNING,
"[NBTAPI] The NBT-API at '" + NBTItem.class.getPackage() + "' seems to be outdated!");
"[NBTAPI] The NBT-API located at '" + NBTItem.class.getPackage() + "' seems to be outdated!");
MinecraftVersion.getLogger().log(Level.WARNING, "[NBTAPI] Current Version: '" + MinecraftVersion.VERSION
+ "' Newest Version: " + latest.get("name").getAsString() + "'");
MinecraftVersion.getLogger().log(Level.WARNING,
"[NBTAPI] Please update the nbt-api or the plugin that contains the api!");
"[NBTAPI] Please update the NBTAPI or the plugin that contains the api(nag the mod author when the newest release has an old version, not the NBTAPI dev)!");
} else if (versionDifference == 0) {
MinecraftVersion.getLogger().log(Level.INFO, "[NBTAPI] The NBT-API seems to be up-to-date!");
if(!hideOk)
MinecraftVersion.getLogger().log(Level.INFO, "[NBTAPI] The NBT-API seems to be up-to-date!");
} else if (versionDifference == 1) {
MinecraftVersion.getLogger().log(Level.WARNING, "[NBTAPI] The NBT-API at '" + NBTItem.class.getPackage()
+ "' seems to be a future Version, not yet released on Spigot/CurseForge!");
MinecraftVersion.getLogger().log(Level.WARNING, "[NBTAPI] Current Version: '" + MinecraftVersion.VERSION
MinecraftVersion.getLogger().log(Level.INFO, "[NBTAPI] The NBT-API at '" + NBTItem.class.getPackage()
+ "' seems to be a future Version, not yet released on Spigot/CurseForge! This is not an error!");
MinecraftVersion.getLogger().log(Level.INFO, "[NBTAPI] Current Version: '" + MinecraftVersion.VERSION
+ "' Newest Version: " + latest.get("name").getAsString() + "'");
}
} else {
@ -97,7 +98,7 @@ public class VersionChecker {
return 1;
if (!relPatch.contains("-") && curPatch.contains("-"))
return -1; // Release has no - but we do = We use a Snapshot of the
// release
// release
if (relPatch.contains("-") && curPatch.contains("-"))
return 0; // Release and cur are Snapshots/alpha/beta
return 1;

View File

@ -8,7 +8,7 @@ import com.pretzel.dev.villagertradelimiter.nms.utils.MinecraftVersion;
/**
* Wraps NMS and CRAFT classes
*
*
* @author tr7zw
*
*/
@ -23,6 +23,7 @@ public enum ClassWrapper {
NMS_NBTBASE(PackageWrapper.NMS, "NBTBase", null, null, "net.minecraft.nbt", "net.minecraft.nbt.Tag"),
NMS_NBTTAGSTRING(PackageWrapper.NMS, "NBTTagString", null, null, "net.minecraft.nbt", "net.minecraft.nbt.StringTag"),
NMS_NBTTAGINT(PackageWrapper.NMS, "NBTTagInt", null, null, "net.minecraft.nbt", "net.minecraft.nbt.IntTag"),
NMS_NBTTAGINTARRAY(PackageWrapper.NMS, "NBTTagIntArray", null, null, "net.minecraft.nbt", "net.minecraft.nbt.IntArrayTag"),
NMS_NBTTAGFLOAT(PackageWrapper.NMS, "NBTTagFloat", null, null, "net.minecraft.nbt", "net.minecraft.nbt.FloatTag"),
NMS_NBTTAGDOUBLE(PackageWrapper.NMS, "NBTTagDouble", null, null, "net.minecraft.nbt", "net.minecraft.nbt.DoubleTag"),
NMS_NBTTAGLONG(PackageWrapper.NMS, "NBTTagLong", null, null, "net.minecraft.nbt", "net.minecraft.nbt.LongTag"),
@ -56,7 +57,7 @@ public enum ClassWrapper {
}
ClassWrapper(PackageWrapper packageId, String clazzName, MinecraftVersion from, MinecraftVersion to,
String mojangMap, String mojangName) {
String mojangMap, String mojangName) {
this.mojangName = mojangName;
if (from != null && MinecraftVersion.getVersion().getVersionId() < from.getVersionId()) {
return;

View File

@ -3,9 +3,12 @@ package com.pretzel.dev.villagertradelimiter.nms.utils.nmsmappings;
import java.util.HashMap;
import java.util.Map;
import com.pretzel.dev.villagertradelimiter.nms.utils.MinecraftVersion;
import com.pretzel.dev.villagertradelimiter.nms.NbtApiException;
/**
* Temporary solution to hold Mojang to unmapped Spigot mappings.
*
*
* @author tr7zw
*
*/
@ -13,7 +16,7 @@ public class MojangToMapping {
@SuppressWarnings("serial")
private static Map<String, String> MC1_18R1 = new HashMap<String, String>() {
{
put("net.minecraft.nbt.CompoundTag#contains(java.lang.String)", "e");
put("net.minecraft.nbt.CompoundTag#getCompound(java.lang.String)", "p");
@ -70,11 +73,25 @@ public class MojangToMapping {
put("net.minecraft.world.level.block.entity.BlockEntity#load(net.minecraft.nbt.CompoundTag)", "a");
put("net.minecraft.server.level.ServerLevel#getBlockEntity(net.minecraft.core.BlockPos)", "c_");
}
};
@SuppressWarnings("serial")
private static Map<String, String> MC1_18R2 = new HashMap<String, String>() {
{
putAll(MC1_18R1);
put("net.minecraft.world.item.ItemStack#getTag()", "t");
}
};
public static Map<String, String> getMapping(){
return MC1_18R1;
switch(MinecraftVersion.getVersion()) {
case MC1_18_R2: return MC1_18R2;
case MC1_18_R1: return MC1_18R1;
default: return MC1_18R2;//throw new NbtApiException("This version of the NBTAPI is not compatible with this server version!");
}
}
}

View File

@ -6,14 +6,13 @@ import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.UUID;
import org.bukkit.inventory.ItemStack;
import com.pretzel.dev.villagertradelimiter.nms.NbtApiException;
import com.pretzel.dev.villagertradelimiter.nms.utils.MinecraftVersion;
import org.bukkit.inventory.ItemStack;
/**
* This class caches method reflections, keeps track of method name changes between versions and allows early checking for problems
*
*
* @author tr7zw
*
*/
@ -36,7 +35,7 @@ public enum ReflectionMethod {
COMPOUND_GET(ClassWrapper.NMS_NBTTAGCOMPOUND, new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "get"), new Since(MinecraftVersion.MC1_18_R1, "get(java.lang.String)")),
COMPOUND_GET_LIST(ClassWrapper.NMS_NBTTAGCOMPOUND, new Class[]{String.class, int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getList"), new Since(MinecraftVersion.MC1_18_R1, "getList(java.lang.String,int)")),
COMPOUND_OWN_TYPE(ClassWrapper.NMS_NBTBASE, new Class[]{}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getTypeId")), // Only needed for 1.7.10 getType
COMPOUND_GET_FLOAT(ClassWrapper.NMS_NBTTAGCOMPOUND, new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getFloat"), new Since(MinecraftVersion.MC1_18_R1, "getFloat(java.lang.String)")),
COMPOUND_GET_STRING(ClassWrapper.NMS_NBTTAGCOMPOUND, new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getString"), new Since(MinecraftVersion.MC1_18_R1, "getString(java.lang.String)")),
COMPOUND_GET_INT(ClassWrapper.NMS_NBTTAGCOMPOUND, new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getInt"), new Since(MinecraftVersion.MC1_18_R1, "getInt(java.lang.String)")),
@ -49,11 +48,11 @@ public enum ReflectionMethod {
COMPOUND_GET_BOOLEAN(ClassWrapper.NMS_NBTTAGCOMPOUND, new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getBoolean"), new Since(MinecraftVersion.MC1_18_R1, "getBoolean(java.lang.String)")),
COMPOUND_GET_UUID(ClassWrapper.NMS_NBTTAGCOMPOUND, new Class[]{String.class}, MinecraftVersion.MC1_16_R1, new Since(MinecraftVersion.MC1_16_R1, "a"), new Since(MinecraftVersion.MC1_18_R1, "getUUID(java.lang.String)")),
COMPOUND_GET_COMPOUND(ClassWrapper.NMS_NBTTAGCOMPOUND, new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getCompound"), new Since(MinecraftVersion.MC1_18_R1, "getCompound(java.lang.String)")),
NMSITEM_GETTAG(ClassWrapper.NMS_ITEMSTACK, new Class[] {}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getTag"), new Since(MinecraftVersion.MC1_18_R1, "getTag()")),
NMSITEM_SAVE(ClassWrapper.NMS_ITEMSTACK, new Class[] {ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "save"), new Since(MinecraftVersion.MC1_18_R1, "save(net.minecraft.nbt.CompoundTag)")),
NMSITEM_CREATESTACK(ClassWrapper.NMS_ITEMSTACK, new Class[] {ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_10_R1, new Since(MinecraftVersion.MC1_7_R4, "createStack")),
COMPOUND_REMOVE_KEY(ClassWrapper.NMS_NBTTAGCOMPOUND, new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "remove"), new Since(MinecraftVersion.MC1_18_R1, "remove(java.lang.String)")),
COMPOUND_HAS_KEY(ClassWrapper.NMS_NBTTAGCOMPOUND, new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "hasKey"), new Since(MinecraftVersion.MC1_18_R1, "contains(java.lang.String)")),
COMPOUND_GET_TYPE(ClassWrapper.NMS_NBTTAGCOMPOUND, new Class[]{String.class}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "b"), new Since(MinecraftVersion.MC1_9_R1, "d"), new Since(MinecraftVersion.MC1_15_R1, "e"), new Since(MinecraftVersion.MC1_16_R1, "d"), new Since(MinecraftVersion.MC1_18_R1, "getTagType(java.lang.String)")),
@ -68,7 +67,7 @@ public enum ReflectionMethod {
LIST_GET_STRING(ClassWrapper.NMS_NBTTAGLIST, new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getString"), new Since(MinecraftVersion.MC1_18_R1, "getString(int)")),
LIST_GET_COMPOUND(ClassWrapper.NMS_NBTTAGLIST, new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "get"), new Since(MinecraftVersion.MC1_18_R1, "getCompound(int)")),
LIST_GET(ClassWrapper.NMS_NBTTAGLIST, new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "get"), new Since(MinecraftVersion.MC1_8_R3, "g"), new Since(MinecraftVersion.MC1_9_R1, "h"), new Since(MinecraftVersion.MC1_12_R1, "i"), new Since(MinecraftVersion.MC1_13_R1, "get"), new Since(MinecraftVersion.MC1_18_R1, "get(int)")),
ITEMSTACK_SET_TAG(ClassWrapper.NMS_ITEMSTACK, new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setTag"), new Since(MinecraftVersion.MC1_18_R1, "setTag(net.minecraft.nbt.CompoundTag)")),
ITEMSTACK_NMSCOPY(ClassWrapper.CRAFT_ITEMSTACK, new Class[]{ItemStack.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "asNMSCopy")),
ITEMSTACK_BUKKITMIRROR(ClassWrapper.CRAFT_ITEMSTACK, new Class[]{ClassWrapper.NMS_ITEMSTACK.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "asCraftMirror")),
@ -85,7 +84,7 @@ public enum ReflectionMethod {
TILEENTITY_LOAD_LEGACY1121(ClassWrapper.NMS_TILEENTITY, new Class[]{ClassWrapper.NMS_WORLD.getClazz(), ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_10_R1, MinecraftVersion.MC1_12_R1, new Since(MinecraftVersion.MC1_10_R1, "a"), new Since(MinecraftVersion.MC1_12_R1, "create")),
TILEENTITY_LOAD_LEGACY1151(ClassWrapper.NMS_TILEENTITY, new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_13_R1, MinecraftVersion.MC1_15_R1, new Since(MinecraftVersion.MC1_12_R1, "create")),
TILEENTITY_LOAD(ClassWrapper.NMS_TILEENTITY, new Class[]{ClassWrapper.NMS_IBLOCKDATA.getClazz(), ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_16_R1, MinecraftVersion.MC1_16_R3, new Since(MinecraftVersion.MC1_16_R1, "create")),
TILEENTITY_GET_NBT(ClassWrapper.NMS_TILEENTITY, new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_17_R1, new Since(MinecraftVersion.MC1_7_R4, "b"), new Since(MinecraftVersion.MC1_9_R1, "save")),
TILEENTITY_GET_NBT_1181(ClassWrapper.NMS_TILEENTITY, new Class[]{}, MinecraftVersion.MC1_18_R1, new Since(MinecraftVersion.MC1_18_R1, "saveWithId()")),
TILEENTITY_SET_NBT_LEGACY1151(ClassWrapper.NMS_TILEENTITY, new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_15_R1, new Since(MinecraftVersion.MC1_7_R4, "a"), new Since(MinecraftVersion.MC1_12_R1, "load")),
@ -100,7 +99,7 @@ public enum ReflectionMethod {
NBTFILE_READ(ClassWrapper.NMS_NBTCOMPRESSEDSTREAMTOOLS, new Class[]{InputStream.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "a"), new Since(MinecraftVersion.MC1_18_R1, "readCompressed(java.io.InputStream)")),
NBTFILE_WRITE(ClassWrapper.NMS_NBTCOMPRESSEDSTREAMTOOLS, new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), OutputStream.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "a"), new Since(MinecraftVersion.MC1_18_R1, "writeCompressed(net.minecraft.nbt.CompoundTag,java.io.OutputStream)")),
PARSE_NBT(ClassWrapper.NMS_MOJANGSONPARSER, new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "parse"), new Since(MinecraftVersion.MC1_18_R1, "parseTag(java.lang.String)")),
REGISTRY_KEYSET (ClassWrapper.NMS_REGISTRYSIMPLE, new Class[]{}, MinecraftVersion.MC1_11_R1, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_11_R1, "keySet")),
REGISTRY_GET (ClassWrapper.NMS_REGISTRYSIMPLE, new Class[]{Object.class}, MinecraftVersion.MC1_11_R1, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_11_R1, "get")),
@ -112,12 +111,12 @@ public enum ReflectionMethod {
GAMEPROFILE_DESERIALIZE (ClassWrapper.NMS_GAMEPROFILESERIALIZER, new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "deserialize"), new Since(MinecraftVersion.MC1_18_R1, "readGameProfile(net.minecraft.nbt.CompoundTag)")),
GAMEPROFILE_SERIALIZE (ClassWrapper.NMS_GAMEPROFILESERIALIZER, new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), ClassWrapper.GAMEPROFILE.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "serialize"), new Since(MinecraftVersion.MC1_18_R1, "writeGameProfile(net.minecraft.nbt.CompoundTag,com.mojang.authlib.GameProfile)")),
CRAFT_PERSISTENT_DATA_CONTAINER_TO_TAG (ClassWrapper.CRAFT_PERSISTENTDATACONTAINER, new Class[]{}, MinecraftVersion.MC1_14_R1, new Since(MinecraftVersion.MC1_14_R1, "toTagCompound")),
CRAFT_PERSISTENT_DATA_CONTAINER_GET_MAP (ClassWrapper.CRAFT_PERSISTENTDATACONTAINER, new Class[]{}, MinecraftVersion.MC1_14_R1, new Since(MinecraftVersion.MC1_14_R1, "getRaw")),
CRAFT_PERSISTENT_DATA_CONTAINER_PUT_ALL (ClassWrapper.CRAFT_PERSISTENTDATACONTAINER, new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_14_R1, new Since(MinecraftVersion.MC1_14_R1, "putAll")),
;
private MinecraftVersion removedAfter;
private Since targetVersion;
private Method method;
@ -125,13 +124,13 @@ public enum ReflectionMethod {
private boolean compatible = false;
private String methodName = null;
private ClassWrapper parentClassWrapper;
ReflectionMethod(ClassWrapper targetClass, Class<?>[] args, MinecraftVersion addedSince, MinecraftVersion removedAfter, Since... methodnames){
this.removedAfter = removedAfter;
this.parentClassWrapper = targetClass;
if(!MinecraftVersion.isAtLeastVersion(addedSince) || (this.removedAfter != null && MinecraftVersion.isNewerThan(removedAfter)))return;
compatible = true;
MinecraftVersion server = MinecraftVersion.getVersion();
MinecraftVersion server = MinecraftVersion.getVersion();
Since target = methodnames[0];
for(Since s : methodnames){
if(s.version.getVersionId() <= server.getVersionId() && target.version.getVersionId() < s.version.getVersionId())
@ -155,39 +154,39 @@ public enum ReflectionMethod {
loaded = true;
methodName = targetVersion.name;
}catch(NullPointerException | NoSuchMethodException | SecurityException ex2){
System.out.println("[NBTAPI] Unable to find the method '" + targetMethodName + "' in '" + (targetClass.getClazz() == null ? targetClass.getMojangName() : targetClass.getClazz().getSimpleName()) + "' Args: " + Arrays.toString(args) + " Enum: " + this); //NOSONAR This gets loaded before the logger is loaded
MinecraftVersion.getLogger().warning("[NBTAPI] Unable to find the method '" + targetMethodName + "' in '" + (targetClass.getClazz() == null ? targetClass.getMojangName() : targetClass.getClazz().getSimpleName()) + "' Args: " + Arrays.toString(args) + " Enum: " + this); //NOSONAR This gets loaded before the logger is loaded
}
}
}
ReflectionMethod(ClassWrapper targetClass, Class<?>[] args, MinecraftVersion addedSince, Since... methodnames){
this(targetClass, args, addedSince, null, methodnames);
this(targetClass, args, addedSince, null, methodnames);
}
/**
* Runs the method on a given target object using the given args.
*
*
* @param target
* @param args
* @return Value returned by the method
*/
public Object run(Object target, Object... args){
if(method == null)
throw new NbtApiException("Method not loaded! '" + this + "'");
try{
throw new NbtApiException("Method not loaded! '" + this + "'");
try{
return method.invoke(target, args);
}catch(Exception ex){
throw new NbtApiException("Error while calling the method '" + methodName + "', loaded: " + loaded + ", Enum: " + this + " Passed Class: " + target.getClass(), ex);
}
}
/**
* @return The MethodName, used in this Minecraft Version
*/
public String getMethodName() {
return methodName;
return methodName;
}
/**
* @return Has this method been linked
*/
@ -201,11 +200,11 @@ public enum ReflectionMethod {
public boolean isCompatible() {
return compatible;
}
public Since getSelectedVersionInfo() {
return targetVersion;
}
/**
* @return Get Wrapper of the parent class
*/
@ -221,5 +220,5 @@ public enum ReflectionMethod {
this.name = name;
}
}
}

View File

@ -1,7 +1,7 @@
name: VillagerTradeLimiter
author: PretzelJohn
main: com.pretzel.dev.villagertradelimiter.VillagerTradeLimiter
version: 1.5.1
version: 1.5.2
api-version: 1.14
commands: