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,17 +3,15 @@ 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
@ -473,7 +471,7 @@ public class NBTCompound {
}
}
/**
/**
* Setter
*
* @param key
@ -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
@ -808,30 +836,30 @@ public class NBTCompound {
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

@ -39,7 +39,7 @@ public class NBTItem extends NBTCompound {
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);
@ -110,8 +110,8 @@ public class NBTItem extends NBTCompound {
* @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();
}
/**

View File

@ -10,7 +10,7 @@ public class NBTPersistentDataContainer extends NBTCompound {
private final PersistentDataContainer container;
protected NBTPersistentDataContainer(PersistentDataContainer container) {
public NBTPersistentDataContainer(PersistentDataContainer container) {
super(null, null);
this.container = container;
}

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;
@ -70,6 +68,9 @@ 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);
}
}
@ -229,13 +230,13 @@ public class NBTReflectionUtil {
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) {
@ -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);
@ -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;
}
@ -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);

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,5 +1,7 @@
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.
@ -13,6 +15,13 @@ 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;
/**
*
@ -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

@ -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,14 +30,14 @@ 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;
@ -55,17 +55,22 @@ 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
@ -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

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

@ -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,6 +3,9 @@ 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.
*
@ -73,8 +76,22 @@ public class MojangToMapping {
};
@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,10 +6,9 @@ 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
@ -131,7 +130,7 @@ public enum ReflectionMethod {
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,13 +154,13 @@ 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);
}
/**
@ -173,8 +172,8 @@ public enum ReflectionMethod {
*/
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);
@ -185,7 +184,7 @@ public enum ReflectionMethod {
* @return The MethodName, used in this Minecraft Version
*/
public String getMethodName() {
return methodName;
return methodName;
}
/**

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: