diff --git a/pom.xml b/pom.xml index 49da20c..1e58f04 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.skymc TabooLib - 4.53 + 4.55 UTF-8 @@ -36,6 +36,42 @@ true + + org.apache.maven.plugins + maven-resources-plugin + 3.0.1 + + UTF-8 + false + + jar + + + + + net.alchim31.maven + scala-maven-plugin + 3.4.2 + + + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + me.skymc.taboolib.socket.TabooLibServer + + + + org.apache.maven.plugins maven-shade-plugin @@ -59,29 +95,6 @@ - - net.alchim31.maven - scala-maven-plugin - 3.4.2 - - - - compile - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - me.skymc.taboolib.socket.TabooLibServer - - - - @@ -218,6 +231,13 @@ system ${basedir}/libs/BossBarAPI.jar + + deprecated + deprecated + 1 + system + ${basedir}/libs/TabooLibDeprecated.jar + \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/TabooLibLoader.java b/src/main/java/me/skymc/taboolib/TabooLibLoader.java index 05b0198..6664f14 100644 --- a/src/main/java/me/skymc/taboolib/TabooLibLoader.java +++ b/src/main/java/me/skymc/taboolib/TabooLibLoader.java @@ -4,9 +4,11 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.ilummc.tlib.TLib; import com.ilummc.tlib.annotations.Dependency; +import com.ilummc.tlib.dependency.TDependencyLoader; import com.ilummc.tlib.inject.TDependencyInjector; import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.bstats.Metrics; +import me.skymc.taboolib.deprecated.TabooLibDeprecated; import me.skymc.taboolib.fileutils.FileUtils; import me.skymc.taboolib.listener.TListener; import me.skymc.taboolib.listener.TListenerHandler; @@ -32,11 +34,13 @@ import java.util.*; @TListener public class TabooLibLoader implements Listener { + static TabooLibDeprecated tabooLibDeprecated; static Map> pluginClasses = Maps.newHashMap(); static List loaders = Lists.newArrayList(); static void setup() { testInternet(); + setupAddons(); setupDataFolder(); setupDatabase(); setupLibraries(); @@ -44,15 +48,24 @@ public class TabooLibLoader implements Listener { static void register() { setupClasses(); - loadClasses(); registerListener(); registerMetrics(); + loadClasses(); + try { + tabooLibDeprecated = new TabooLibDeprecated(); + } catch (Exception e) { + e.printStackTrace(); + } } static void unregister() { unloadClasses(); } + public static TabooLibDeprecated getTabooLibDeprecated() { + return tabooLibDeprecated; + } + public static Optional> getPluginClasses(Plugin plugin) { return Optional.ofNullable(pluginClasses.get(plugin.getName())); } @@ -84,6 +97,14 @@ public class TabooLibLoader implements Listener { metrics.addCustomChart(new Metrics.SingleLineChart("plugins_using_taboolib", () -> Math.toIntExact(Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> plugin.getDescription().getDepend().contains("TabooLib")).count()))); } + static void setupAddons() { + TabooLib.instance().saveResource("Addons/TabooLibDeprecated.jar", true); + File file = new File(TabooLib.instance().getDataFolder(), "Addons"); + if (file.exists()) { + Arrays.stream(file.listFiles()).forEach(listFile -> TDependencyLoader.addToPath(TabooLib.instance(), listFile)); + } + } + static void setupDataFolder() { Main.setPlayerDataFolder(FileUtils.folder(Main.getInst().getConfig().getString("DATAURL.PLAYER-DATA"))); Main.setServerDataFolder(FileUtils.folder(Main.getInst().getConfig().getString("DATAURL.SERVER-DATA"))); diff --git a/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java b/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java index 6bdd43f..904910c 100644 --- a/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java +++ b/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java @@ -2,7 +2,7 @@ package me.skymc.taboolib.anvil; import com.ilummc.tlib.util.asm.AsmClassLoader; import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.object.Instantiable; +import me.skymc.taboolib.common.loader.Instantiable; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/src/main/java/me/skymc/taboolib/commands/builder/SimpleCommandBuilder.java b/src/main/java/me/skymc/taboolib/commands/builder/SimpleCommandBuilder.java index 9e7efbd..209d1eb 100644 --- a/src/main/java/me/skymc/taboolib/commands/builder/SimpleCommandBuilder.java +++ b/src/main/java/me/skymc/taboolib/commands/builder/SimpleCommandBuilder.java @@ -31,6 +31,7 @@ public class SimpleCommandBuilder { private String permissionMessage; private CompleterTab completerTab = EMPTY_COMPLETER_TAB; private CompleterCommand completerCommand = EMPTY_COMPLETER_COMMAND; + private boolean silence; SimpleCommandBuilder(String command, Plugin plugin) { this.command = command; @@ -38,6 +39,7 @@ public class SimpleCommandBuilder { this.description = ""; this.usage = "/" + command; this.aliases = new ArrayList<>(); + this.silence = false; } public static SimpleCommandBuilder create(String command, Plugin plugin) { @@ -79,6 +81,11 @@ public class SimpleCommandBuilder { return this; } + public SimpleCommandBuilder silence() { + this.silence = true; + return this; + } + public SimpleCommandBuilder build() { Preconditions.checkNotNull(completerCommand, "缺少 \"CompleterCommand\" 部分"); Preconditions.checkNotNull(completerTab, "缺少 \"CompleterTab\" 部分"); @@ -91,7 +98,8 @@ public class SimpleCommandBuilder { permission, permissionMessage, (sender, command, s, args) -> completerCommand.execute(sender, args), - (sender, command, s, args) -> completerTab.execute(sender, args)); + (sender, command, s, args) -> completerTab.execute(sender, args), + silence); return this; } } diff --git a/src/main/java/me/skymc/taboolib/commands/internal/TCommandHandler.java b/src/main/java/me/skymc/taboolib/commands/internal/TCommandHandler.java index 9cfe49d..ee7f365 100644 --- a/src/main/java/me/skymc/taboolib/commands/internal/TCommandHandler.java +++ b/src/main/java/me/skymc/taboolib/commands/internal/TCommandHandler.java @@ -16,7 +16,9 @@ import org.bukkit.plugin.Plugin; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.ArrayList; +import java.util.Collection; import java.util.List; +import java.util.stream.Collectors; /** * @Author sky @@ -70,6 +72,10 @@ public class TCommandHandler implements Listener { return registerPluginCommand(plugin, command, description, usage, aliases, null, null, commandExecutor, tabCompleter); } + public static boolean registerPluginCommand(Plugin plugin, String command, String description, String usage, List aliases, String permission, String permissionMessage, CommandExecutor commandExecutor, TabCompleter tabCompleter) { + return registerPluginCommand(plugin, command, description, usage, aliases, permission, permissionMessage, commandExecutor, tabCompleter, false); + } + /** * 向服务端动态注册命令 * @@ -81,10 +87,11 @@ public class TCommandHandler implements Listener { * @param permission 权限 * @param permissionMessage 权限提示 * @param commandExecutor 命令执行器 - * @param tabCompleter 补全执行器 + * @param tabCompleter 补全执行器 + * @param silence 是否屏蔽提示 * @return 注册结果(boolean) */ - public static boolean registerPluginCommand(Plugin plugin, String command, String description, String usage, List aliases, String permission, String permissionMessage, CommandExecutor commandExecutor, TabCompleter tabCompleter) { + public static boolean registerPluginCommand(Plugin plugin, String command, String description, String usage, List aliases, String permission, String permissionMessage, CommandExecutor commandExecutor, TabCompleter tabCompleter, boolean silence) { try { Constructor constructor = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class); constructor.setAccessible(true); @@ -93,17 +100,18 @@ public class TCommandHandler implements Listener { pluginCommand.setTabCompleter(tabCompleter); ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "description", description); ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "usageMessage", usage); - ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "aliases", aliases); - ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "activeAliases", aliases); + ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "aliases", aliases.stream().map(String::toLowerCase).collect(Collectors.toList())); + ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "activeAliases", aliases.stream().map(String::toLowerCase).collect(Collectors.toList())); ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "permission", permission); ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "permissionMessage", permissionMessage); - commandMap.register(command, pluginCommand); - if (!TabooLib.isTabooLib(plugin)) { + commandMap.register(plugin.getName(), pluginCommand); + if (!TabooLib.isTabooLib(plugin) && !silence) { TLocale.Logger.info("COMMANDS.INTERNAL.COMMAND-CREATE", plugin.getName(), command); } return true; } catch (Exception e) { - TLocale.Logger.info("COMMANDS.INTERNAL.COMMAND-CREATE-FAILED", plugin.getName(), command, e.getMessage()); + TLocale.Logger.info("COMMANDS.INTERNAL.COMMAND-CREATE-FAILED", plugin.getName(), command, e.toString()); + e.printStackTrace(); return false; } } diff --git a/src/main/java/me/skymc/taboolib/commands/language/Language2Command.java b/src/main/java/me/skymc/taboolib/commands/language/Language2Command.java index f21c1f5..6cc56cc 100644 --- a/src/main/java/me/skymc/taboolib/commands/language/Language2Command.java +++ b/src/main/java/me/skymc/taboolib/commands/language/Language2Command.java @@ -4,7 +4,7 @@ import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.Main; import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.commands.builder.SimpleCommandBuilder; -import me.skymc.taboolib.object.Instantiable; +import me.skymc.taboolib.common.loader.Instantiable; import me.skymc.taboolib.string.language2.Language2Value; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/src/main/java/me/skymc/taboolib/commands/taboolib/TagDisplayCommand.java b/src/main/java/me/skymc/taboolib/commands/taboolib/TagDisplayCommand.java index 6dd46a0..8808e6d 100644 --- a/src/main/java/me/skymc/taboolib/commands/taboolib/TagDisplayCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/taboolib/TagDisplayCommand.java @@ -1,10 +1,8 @@ package me.skymc.taboolib.commands.taboolib; import com.ilummc.tlib.resources.TLocale; -import me.clip.placeholderapi.PlaceholderAPI; import me.skymc.taboolib.commands.SubCommand; import me.skymc.taboolib.itagapi.TagDataHandler; -import me.skymc.taboolib.team.TagAPI; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; diff --git a/src/main/java/me/skymc/taboolib/common/inject/TInjectLoader.java b/src/main/java/me/skymc/taboolib/common/inject/TInjectLoader.java index 002637c..0c0bcdb 100644 --- a/src/main/java/me/skymc/taboolib/common/inject/TInjectLoader.java +++ b/src/main/java/me/skymc/taboolib/common/inject/TInjectLoader.java @@ -3,6 +3,7 @@ package me.skymc.taboolib.common.inject; import com.google.common.collect.Maps; import com.ilummc.tlib.logger.TLogger; import me.skymc.taboolib.TabooLibLoader; +import me.skymc.taboolib.commands.builder.SimpleCommandBuilder; import me.skymc.taboolib.common.configuration.TConfiguration; import org.bukkit.plugin.Plugin; @@ -39,6 +40,14 @@ public class TInjectLoader implements TabooLibLoader.Loader { e.printStackTrace(); } }); + // SimpleCommandBuilder Inject + injectTypes.put(SimpleCommandBuilder.class, (plugin, field, args) -> { + try { + ((SimpleCommandBuilder) field.get(null)).build(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + }); } @Override diff --git a/src/main/java/me/skymc/taboolib/object/Instantiable.java b/src/main/java/me/skymc/taboolib/common/loader/Instantiable.java similarity index 89% rename from src/main/java/me/skymc/taboolib/object/Instantiable.java rename to src/main/java/me/skymc/taboolib/common/loader/Instantiable.java index fb7e32e..9ffadc4 100644 --- a/src/main/java/me/skymc/taboolib/object/Instantiable.java +++ b/src/main/java/me/skymc/taboolib/common/loader/Instantiable.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.object; +package me.skymc.taboolib.common.loader; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/me/skymc/taboolib/object/InstantiableLoader.java b/src/main/java/me/skymc/taboolib/common/loader/InstantiableLoader.java similarity index 98% rename from src/main/java/me/skymc/taboolib/object/InstantiableLoader.java rename to src/main/java/me/skymc/taboolib/common/loader/InstantiableLoader.java index 45e7c0d..62ae29b 100644 --- a/src/main/java/me/skymc/taboolib/object/InstantiableLoader.java +++ b/src/main/java/me/skymc/taboolib/common/loader/InstantiableLoader.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.object; +package me.skymc.taboolib.common.loader; import com.ilummc.tlib.util.Ref; import me.skymc.taboolib.TabooLibLoader; diff --git a/src/main/java/me/skymc/taboolib/common/pathfinder/SimpleAiSelector.java b/src/main/java/me/skymc/taboolib/common/pathfinder/SimpleAiSelector.java index f80d04d..ea74712 100644 --- a/src/main/java/me/skymc/taboolib/common/pathfinder/SimpleAiSelector.java +++ b/src/main/java/me/skymc/taboolib/common/pathfinder/SimpleAiSelector.java @@ -1,7 +1,7 @@ package me.skymc.taboolib.common.pathfinder; import me.skymc.taboolib.common.versioncontrol.SimpleVersionControl; -import me.skymc.taboolib.object.Instantiable; +import me.skymc.taboolib.common.loader.Instantiable; /** * @Author sky diff --git a/src/main/java/me/skymc/taboolib/common/versioncontrol/SimpleVersionControl.java b/src/main/java/me/skymc/taboolib/common/versioncontrol/SimpleVersionControl.java index 3e2f9bd..1f020cb 100644 --- a/src/main/java/me/skymc/taboolib/common/versioncontrol/SimpleVersionControl.java +++ b/src/main/java/me/skymc/taboolib/common/versioncontrol/SimpleVersionControl.java @@ -15,8 +15,6 @@ import java.util.ArrayList; import java.util.List; /** - * 我不信 ClassNotFound 的邪,自己写了一个发现还是一样。。。 - * * @Author sky * @Since 2018-09-19 21:05 */ @@ -64,6 +62,10 @@ public class SimpleVersionControl { } public Class translate() throws IOException { + return translate(plugin); + } + + public Class translate(Plugin plugin) throws IOException { ClassReader classReader = new ClassReader(FileUtils.getResource(plugin, target.replace(".", "/") + ".class")); ClassWriter classWriter = new ClassWriter(0); ClassVisitor classVisitor = new SimpleClassVisitor(this, classWriter); diff --git a/src/main/java/me/skymc/taboolib/cooldown/CooldownPack.java b/src/main/java/me/skymc/taboolib/cooldown/CooldownPack.java deleted file mode 100644 index 8066e7e..0000000 --- a/src/main/java/me/skymc/taboolib/cooldown/CooldownPack.java +++ /dev/null @@ -1,60 +0,0 @@ -package me.skymc.taboolib.cooldown; - -import java.util.HashMap; - -@Deprecated -public class CooldownPack { - - private String plugin; - private String name; - private int seconds; - - private HashMap data = new HashMap<>(); - - public CooldownPack(String n, int s) { - this.name = n; - this.seconds = s; - this.plugin = "null"; - } - - public String getPackName() { - return name; - } - - public int getPackSeconds() { - return seconds; - } - - public String getPlugin() { - return plugin; - } - - public void setPlugin(String p) { - this.plugin = p; - } - - public void unRegister(String player) { - data.remove(player); - } - - public int getCooldown(String player) { - if (!data.containsKey(player)) { - return 0; - } - int difference = (int) ((System.currentTimeMillis() - data.get(player)) / 1000); - - return difference >= seconds ? 0 : seconds - difference; - } - - public boolean isCooldown(String player, int cutseconds) { - if (!data.containsKey(player)) { - data.put(player, System.currentTimeMillis()); - return false; - } - if ((getCooldown(player) - (cutseconds*1000)) <= 0) { - data.put(player, System.currentTimeMillis()); - return false; - } - return true; - } -} diff --git a/src/main/java/me/skymc/taboolib/cooldown/CooldownUtils.java b/src/main/java/me/skymc/taboolib/cooldown/CooldownUtils.java deleted file mode 100644 index d63557e..0000000 --- a/src/main/java/me/skymc/taboolib/cooldown/CooldownUtils.java +++ /dev/null @@ -1,47 +0,0 @@ -package me.skymc.taboolib.cooldown; - -import com.ilummc.tlib.resources.TLocale; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.plugin.Plugin; - -import java.util.concurrent.ConcurrentHashMap; - -@Deprecated -public class CooldownUtils implements Listener { - - private static ConcurrentHashMap packlist = new ConcurrentHashMap<>(); - - public static void register(CooldownPack pack) { - packlist.put(pack.getPackName(), pack); - TLocale.Logger.info("COOLDOWNPACK.PACK-REGISTER-ANONYMOUS", pack.getPackName(), String.valueOf(pack.getPackSeconds())); - } - - public static void register(CooldownPack pack, Plugin plugin) { - pack.setPlugin(plugin.getName()); - packlist.put(pack.getPackName(), pack); - TLocale.Logger.info("COOLDOWNPACK.PACK-REGISTER", pack.getPackName(), String.valueOf(pack.getPackSeconds()), plugin.getName()); - } - - public static void unregister(String name) { - packlist.remove(name); - TLocale.Logger.info("COOLDOWNPACK.PACK-UNREGISTER", name); - } - - private static void unregister(CooldownPack pack) { - packlist.remove(pack.getPackName()); - TLocale.Logger.info("COOLDOWNPACK.PACK-UNREGISTER-AUTO", pack.getPackName()); - } - - @EventHandler - public void quit(PlayerQuitEvent e) { - packlist.values().stream().filter(pack -> !pack.isCooldown(e.getPlayer().getName(), 0)).forEach(pack -> pack.unRegister(e.getPlayer().getName())); - } - - @EventHandler - public void disable(PluginDisableEvent e) { - packlist.values().stream().filter(pack -> pack.getPlugin().equals(e.getPlugin().getName())).forEach(CooldownUtils::unregister); - } -} diff --git a/src/main/java/me/skymc/taboolib/cooldown/seconds/CooldownPack2.java b/src/main/java/me/skymc/taboolib/cooldown/seconds/CooldownPack2.java deleted file mode 100644 index 3a54f60..0000000 --- a/src/main/java/me/skymc/taboolib/cooldown/seconds/CooldownPack2.java +++ /dev/null @@ -1,58 +0,0 @@ -package me.skymc.taboolib.cooldown.seconds; - -import java.util.HashMap; - -public class CooldownPack2 { - - private String plugin; - private String name; - private int seconds; - - private HashMap data = new HashMap<>(); - - public CooldownPack2(String n, int s) { - this.name = n; - this.seconds = s; - this.plugin = "null"; - } - - public String getPackName() { - return name; - } - - public int getPackSeconds() { - return seconds; - } - - public String getPlugin() { - return plugin; - } - - public void setPlugin(String p) { - this.plugin = p; - } - - public void unRegister(String player) { - data.remove(player); - } - - public int getCooldown(String player, int cutseconds) { - if (!data.containsKey(player)) { - return 0; - } - int difference = (int) ((System.currentTimeMillis() + cutseconds) - data.get(player)); - return difference >= seconds ? 0 : seconds - difference; - } - - public boolean isCooldown(String player, int cutseconds) { - if (!data.containsKey(player)) { - data.put(player, System.currentTimeMillis()); - return false; - } - if (getCooldown(player, cutseconds) <= 0) { - data.put(player, System.currentTimeMillis()); - return false; - } - return true; - } -} diff --git a/src/main/java/me/skymc/taboolib/cooldown/seconds/CooldownUtils2.java b/src/main/java/me/skymc/taboolib/cooldown/seconds/CooldownUtils2.java deleted file mode 100644 index 91cfcdf..0000000 --- a/src/main/java/me/skymc/taboolib/cooldown/seconds/CooldownUtils2.java +++ /dev/null @@ -1,50 +0,0 @@ -package me.skymc.taboolib.cooldown.seconds; - -import com.ilummc.tlib.resources.TLocale; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.plugin.Plugin; - -import java.util.concurrent.ConcurrentHashMap; - -public class CooldownUtils2 implements Listener { - - private static ConcurrentHashMap packlist = new ConcurrentHashMap<>(); - - public static ConcurrentHashMap getCooldownPacks() { - return packlist; - } - - public static void register(CooldownPack2 pack) { - packlist.put(pack.getPackName(), pack); - TLocale.Logger.info("COOLDOWNPACK.PACK-REGISTER-ANONYMOUS", pack.getPackName(), String.valueOf(pack.getPackSeconds())); - } - - public static void register(CooldownPack2 pack, Plugin plugin) { - pack.setPlugin(plugin.getName()); - packlist.put(pack.getPackName(), pack); - TLocale.Logger.info("COOLDOWNPACK.PACK-REGISTER", pack.getPackName(), String.valueOf(pack.getPackSeconds()), plugin.getName()); - } - - public static void unregister(String name) { - packlist.remove(name); - TLocale.Logger.info("COOLDOWNPACK.PACK-UNREGISTER", name); - } - - private static void unregister(CooldownPack2 pack) { - packlist.remove(pack.getPackName()); - TLocale.Logger.info("COOLDOWNPACK.PACK-UNREGISTER-AUTO", pack.getPackName()); - } - - @EventHandler - public void quit(PlayerQuitEvent e) { - packlist.values().stream().filter(pack -> !pack.isCooldown(e.getPlayer().getName(), 0)).forEach(pack -> pack.unRegister(e.getPlayer().getName())); - } - - @EventHandler - public void disable(PluginDisableEvent e) { - packlist.values().stream().filter(pack -> pack.getPlugin().equals(e.getPlugin().getName())).forEach(CooldownUtils2::unregister); - } -} diff --git a/src/main/java/me/skymc/taboolib/csvutils/CsvReader.java b/src/main/java/me/skymc/taboolib/csvutils/CsvReader.java deleted file mode 100644 index fda2878..0000000 --- a/src/main/java/me/skymc/taboolib/csvutils/CsvReader.java +++ /dev/null @@ -1,1065 +0,0 @@ -package me.skymc.taboolib.csvutils; - -import java.io.*; -import java.nio.charset.Charset; -import java.text.NumberFormat; -import java.util.HashMap; - -public class CsvReader { - - private Reader inputStream; - private String fileName; - private UserSettings userSettings; - private Charset charset; - private boolean useCustomRecordDelimiter; - private DataBuffer dataBuffer; - private ColumnBuffer columnBuffer; - private RawRecordBuffer rawBuffer; - private boolean[] isQualified; - private String rawRecord; - private HeadersHolder headersHolder; - private boolean startedColumn; - private boolean startedWithQualifier; - private boolean hasMoreData; - private char lastLetter; - private boolean hasReadNextLine; - private int columnsCount; - private long currentRecord; - private String[] values; - private boolean initialized; - private boolean closed; - public static final int ESCAPE_MODE_DOUBLED = 1; - public static final int ESCAPE_MODE_BACKSLASH = 2; - - public CsvReader(final String fileName, final char delimiter, final Charset charset) throws FileNotFoundException { - this.inputStream = null; - this.fileName = null; - this.userSettings = new UserSettings(); - this.charset = null; - this.useCustomRecordDelimiter = false; - this.dataBuffer = new DataBuffer(); - this.columnBuffer = new ColumnBuffer(); - this.rawBuffer = new RawRecordBuffer(); - this.isQualified = null; - this.rawRecord = ""; - this.headersHolder = new HeadersHolder(); - this.startedColumn = false; - this.startedWithQualifier = false; - this.hasMoreData = true; - this.lastLetter = '\0'; - this.hasReadNextLine = false; - this.columnsCount = 0; - this.currentRecord = 0L; - this.values = new String[10]; - this.initialized = false; - this.closed = false; - if (fileName == null) { - throw new IllegalArgumentException("Parameter fileName can not be null."); - } - if (charset == null) { - throw new IllegalArgumentException("Parameter charset can not be null."); - } - if (!new File(fileName).exists()) { - throw new FileNotFoundException("File " + fileName + " does not exist."); - } - this.fileName = fileName; - this.userSettings.Delimiter = delimiter; - this.charset = charset; - this.isQualified = new boolean[this.values.length]; - } - - public CsvReader(final String s, final char c) throws FileNotFoundException { - this(s, c, Charset.forName("ISO-8859-1")); - } - - public CsvReader(final String s) throws FileNotFoundException { - this(s, ','); - } - - public CsvReader(final Reader inputStream, final char delimiter) { - this.inputStream = null; - this.fileName = null; - this.userSettings = new UserSettings(); - this.charset = null; - this.useCustomRecordDelimiter = false; - this.dataBuffer = new DataBuffer(); - this.columnBuffer = new ColumnBuffer(); - this.rawBuffer = new RawRecordBuffer(); - this.isQualified = null; - this.rawRecord = ""; - this.headersHolder = new HeadersHolder(); - this.startedColumn = false; - this.startedWithQualifier = false; - this.hasMoreData = true; - this.lastLetter = '\0'; - this.hasReadNextLine = false; - this.columnsCount = 0; - this.currentRecord = 0L; - this.values = new String[10]; - this.initialized = false; - this.closed = false; - if (inputStream == null) { - throw new IllegalArgumentException("Parameter inputStream can not be null."); - } - this.inputStream = inputStream; - this.userSettings.Delimiter = delimiter; - this.initialized = true; - this.isQualified = new boolean[this.values.length]; - } - - public CsvReader(final Reader reader) { - this(reader, ','); - } - - public CsvReader(final InputStream inputStream, final char c, final Charset charset) { - this(new InputStreamReader(inputStream, charset), c); - } - - public CsvReader(final InputStream inputStream, final Charset charset) { - this(new InputStreamReader(inputStream, charset)); - } - - public boolean getCaptureRawRecord() { - return this.userSettings.CaptureRawRecord; - } - - public void setCaptureRawRecord(final boolean captureRawRecord) { - this.userSettings.CaptureRawRecord = captureRawRecord; - } - - public String getRawRecord() { - return this.rawRecord; - } - - public boolean getTrimWhitespace() { - return this.userSettings.TrimWhitespace; - } - - public void setTrimWhitespace(final boolean trimWhitespace) { - this.userSettings.TrimWhitespace = trimWhitespace; - } - - public char getDelimiter() { - return this.userSettings.Delimiter; - } - - public void setDelimiter(final char delimiter) { - this.userSettings.Delimiter = delimiter; - } - - public char getRecordDelimiter() { - return this.userSettings.RecordDelimiter; - } - - public void setRecordDelimiter(final char recordDelimiter) { - this.useCustomRecordDelimiter = true; - this.userSettings.RecordDelimiter = recordDelimiter; - } - - public char getTextQualifier() { - return this.userSettings.TextQualifier; - } - - public void setTextQualifier(final char textQualifier) { - this.userSettings.TextQualifier = textQualifier; - } - - public boolean getUseTextQualifier() { - return this.userSettings.UseTextQualifier; - } - - public void setUseTextQualifier(final boolean useTextQualifier) { - this.userSettings.UseTextQualifier = useTextQualifier; - } - - public char getComment() { - return this.userSettings.Comment; - } - - public void setComment(final char comment) { - this.userSettings.Comment = comment; - } - - public boolean getUseComments() { - return this.userSettings.UseComments; - } - - public void setUseComments(final boolean useComments) { - this.userSettings.UseComments = useComments; - } - - public int getEscapeMode() { - return this.userSettings.EscapeMode; - } - - public void setEscapeMode(final int escapeMode) throws IllegalArgumentException { - if (escapeMode != 1 && escapeMode != 2) { - throw new IllegalArgumentException("Parameter escapeMode must be a valid value."); - } - this.userSettings.EscapeMode = escapeMode; - } - - public boolean getSkipEmptyRecords() { - return this.userSettings.SkipEmptyRecords; - } - - public void setSkipEmptyRecords(final boolean skipEmptyRecords) { - this.userSettings.SkipEmptyRecords = skipEmptyRecords; - } - - public boolean getSafetySwitch() { - return this.userSettings.SafetySwitch; - } - - public void setSafetySwitch(final boolean safetySwitch) { - this.userSettings.SafetySwitch = safetySwitch; - } - - public int getColumnCount() { - return this.columnsCount; - } - - public long getCurrentRecord() { - return this.currentRecord - 1L; - } - - // TODO 2017-11-29 18:38:13 UPDATED - public long setCurrentRecord(long currentRecord) { - return this.currentRecord = currentRecord; - } - - public int getHeaderCount() { - return this.headersHolder.Length; - } - - public String[] getHeaders() throws IOException { - this.checkClosed(); - if (this.headersHolder.Headers == null) { - return null; - } - final String[] array = new String[this.headersHolder.Length]; - System.arraycopy(this.headersHolder.Headers, 0, array, 0, this.headersHolder.Length); - return array; - } - - private static char hexToDec(final char c) { - char c2; - if (c >= 'a') { - c2 = (char) (c - 'a' + '\n'); - } else if (c >= 'A') { - c2 = (char) (c - 'A' + '\n'); - } else { - c2 = (char) (c - '0'); - } - return c2; - } - - public String[] getValues() throws IOException { - this.checkClosed(); - final String[] array = new String[this.columnsCount]; - System.arraycopy(this.values, 0, array, 0, this.columnsCount); - return array; - } - - public String get(final int n) throws IOException { - this.checkClosed(); - if (n > -1 && n < this.columnsCount) { - return this.values[n]; - } - return ""; - } - - public String get(final String s) throws IOException { - this.checkClosed(); - return this.get(this.getIndex(s)); - } - - public static CsvReader parse(final String s) { - if (s == null) { - throw new IllegalArgumentException("Parameter data can not be null."); - } - return new CsvReader(new StringReader(s)); - } - - public void setHeaders(final String[] headers) { - this.headersHolder.Headers = headers; - this.headersHolder.IndexByName.clear(); - if (headers != null) { - this.headersHolder.Length = headers.length; - } else { - this.headersHolder.Length = 0; - } - for (int i = 0; i < this.headersHolder.Length; ++i) { - this.headersHolder.IndexByName.put(headers[i], i); - } - } - - public boolean readRecord() throws IOException { - this.checkClosed(); - this.columnsCount = 0; - this.rawBuffer.Position = 0; - this.dataBuffer.LineStart = this.dataBuffer.Position; - this.hasReadNextLine = false; - if (this.hasMoreData) { - do { - if (this.dataBuffer.Position == this.dataBuffer.Count) { - this.checkDataLength(); - } else { - this.startedWithQualifier = false; - char c = this.dataBuffer.Buffer[this.dataBuffer.Position]; - if (this.userSettings.UseTextQualifier && c == this.userSettings.TextQualifier) { - this.lastLetter = c; - this.startedColumn = true; - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - this.startedWithQualifier = true; - int n = 0; - char textQualifier = this.userSettings.TextQualifier; - if (this.userSettings.EscapeMode == 2) { - textQualifier = '\\'; - } - int n2 = 0; - int n3 = 0; - int n4 = 0; - int n5 = 1; - int n6 = 0; - char c2 = '\0'; - final DataBuffer dataBuffer = this.dataBuffer; - ++dataBuffer.Position; - do { - if (this.dataBuffer.Position == this.dataBuffer.Count) { - this.checkDataLength(); - } else { - final char lastLetter = this.dataBuffer.Buffer[this.dataBuffer.Position]; - if (n2 != 0) { - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - if (lastLetter == this.userSettings.Delimiter) { - this.endColumn(); - } else if ((!this.useCustomRecordDelimiter && (lastLetter == '\r' || lastLetter == '\n')) || (this.useCustomRecordDelimiter && lastLetter == this.userSettings.RecordDelimiter)) { - this.endColumn(); - this.endRecord(); - } - } else if (n4 != 0) { - ++n6; - switch (n5) { - case 1: { - c2 = (char) ((char) (c2 * '\u0010') + hexToDec(lastLetter)); - if (n6 == 4) { - n4 = 0; - break; - } - break; - } - case 2: { - c2 = (char) ((char) (c2 * '\b') + (char) (lastLetter - '0')); - if (n6 == 3) { - n4 = 0; - break; - } - break; - } - case 3: { - c2 = (char) ((char) (c2 * '\n') + (char) (lastLetter - '0')); - if (n6 == 3) { - n4 = 0; - break; - } - break; - } - case 4: { - c2 = (char) ((char) (c2 * '\u0010') + hexToDec(lastLetter)); - if (n6 == 2) { - n4 = 0; - break; - } - break; - } - } - if (n4 == 0) { - this.appendLetter(c2); - } else { - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - } - } else if (lastLetter == this.userSettings.TextQualifier) { - if (n3 != 0) { - n3 = 0; - n = 0; - } else { - this.updateCurrentValue(); - if (this.userSettings.EscapeMode == 1) { - n3 = 1; - } - n = 1; - } - } else if (this.userSettings.EscapeMode == 2 && n3 != 0) { - switch (lastLetter) { - case 'n': { - this.appendLetter('\n'); - break; - } - case 'r': { - this.appendLetter('\r'); - break; - } - case 't': { - this.appendLetter('\t'); - break; - } - case 'b': { - this.appendLetter('\b'); - break; - } - case 'f': { - this.appendLetter('\f'); - break; - } - case 'e': { - this.appendLetter('\u001b'); - break; - } - case 'v': { - this.appendLetter('\u000b'); - break; - } - case 'a': { - this.appendLetter('\u0007'); - break; - } - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': { - n5 = 2; - n4 = 1; - n6 = 1; - c2 = (char) (lastLetter - '0'); - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - break; - } - case 'D': - case 'O': - case 'U': - case 'X': - case 'd': - case 'o': - case 'u': - case 'x': { - switch (lastLetter) { - case 'U': - case 'u': { - n5 = 1; - break; - } - case 'X': - case 'x': { - n5 = 4; - break; - } - case 'O': - case 'o': { - n5 = 2; - break; - } - case 'D': - case 'd': { - n5 = 3; - break; - } - } - n4 = 1; - n6 = 0; - c2 = '\0'; - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - break; - } - } - n3 = 0; - } else if (lastLetter == textQualifier) { - this.updateCurrentValue(); - n3 = 1; - } else if (n != 0) { - if (lastLetter == this.userSettings.Delimiter) { - this.endColumn(); - } else if ((!this.useCustomRecordDelimiter && (lastLetter == '\r' || lastLetter == '\n')) || (this.useCustomRecordDelimiter && lastLetter == this.userSettings.RecordDelimiter)) { - this.endColumn(); - this.endRecord(); - } else { - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - n2 = 1; - } - n = 0; - } - this.lastLetter = lastLetter; - if (!this.startedColumn) { - continue; - } - final DataBuffer dataBuffer2 = this.dataBuffer; - ++dataBuffer2.Position; - if (this.userSettings.SafetySwitch && this.dataBuffer.Position - this.dataBuffer.ColumnStart + this.columnBuffer.Position > 100000) { - this.close(); - throw new IOException("Maximum column length of 100,000 exceeded in column " + NumberFormat.getIntegerInstance().format(this.columnsCount) + " in record " + NumberFormat.getIntegerInstance().format(this.currentRecord) + ". Set the SafetySwitch property to false" + " if you're expecting column lengths greater than 100,000 characters to" + " avoid this error."); - } - } - } while (this.hasMoreData && this.startedColumn); - } else if (c == this.userSettings.Delimiter) { - this.lastLetter = c; - this.endColumn(); - } else if (this.useCustomRecordDelimiter && c == this.userSettings.RecordDelimiter) { - if (this.startedColumn || this.columnsCount > 0 || !this.userSettings.SkipEmptyRecords) { - this.endColumn(); - this.endRecord(); - } else { - this.dataBuffer.LineStart = this.dataBuffer.Position + 1; - } - this.lastLetter = c; - } else if (!this.useCustomRecordDelimiter && (c == '\r' || c == '\n')) { - if (this.startedColumn || this.columnsCount > 0 || (!this.userSettings.SkipEmptyRecords && (c == '\r' || this.lastLetter != '\r'))) { - this.endColumn(); - this.endRecord(); - } else { - this.dataBuffer.LineStart = this.dataBuffer.Position + 1; - } - this.lastLetter = c; - } else if (this.userSettings.UseComments && this.columnsCount == 0 && c == this.userSettings.Comment) { - this.lastLetter = c; - this.skipLine(); - } else if (this.userSettings.TrimWhitespace && (c == ' ' || c == '\t')) { - this.startedColumn = true; - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - } else { - this.startedColumn = true; - this.dataBuffer.ColumnStart = this.dataBuffer.Position; - int n7 = 0; - int n8 = 0; - int n9 = 1; - int n10 = 0; - char c3 = '\0'; - int n11 = 1; - do { - if (n11 == 0 && this.dataBuffer.Position == this.dataBuffer.Count) { - this.checkDataLength(); - } else { - if (n11 == 0) { - c = this.dataBuffer.Buffer[this.dataBuffer.Position]; - } - if (!this.userSettings.UseTextQualifier && this.userSettings.EscapeMode == 2 && c == '\\') { - if (n7 != 0) { - n7 = 0; - } else { - this.updateCurrentValue(); - n7 = 1; - } - } else if (n8 != 0) { - ++n10; - switch (n9) { - case 1: { - c3 = (char) ((char) (c3 * '\u0010') + hexToDec(c)); - if (n10 == 4) { - n8 = 0; - break; - } - break; - } - case 2: { - c3 = (char) ((char) (c3 * '\b') + (char) (c - '0')); - if (n10 == 3) { - n8 = 0; - break; - } - break; - } - case 3: { - c3 = (char) ((char) (c3 * '\n') + (char) (c - '0')); - if (n10 == 3) { - n8 = 0; - break; - } - break; - } - case 4: { - c3 = (char) ((char) (c3 * '\u0010') + hexToDec(c)); - if (n10 == 2) { - n8 = 0; - break; - } - break; - } - } - if (n8 == 0) { - this.appendLetter(c3); - } else { - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - } - } else if (this.userSettings.EscapeMode == 2 && n7 != 0) { - switch (c) { - case 'n': { - this.appendLetter('\n'); - break; - } - case 'r': { - this.appendLetter('\r'); - break; - } - case 't': { - this.appendLetter('\t'); - break; - } - case 'b': { - this.appendLetter('\b'); - break; - } - case 'f': { - this.appendLetter('\f'); - break; - } - case 'e': { - this.appendLetter('\u001b'); - break; - } - case 'v': { - this.appendLetter('\u000b'); - break; - } - case 'a': { - this.appendLetter('\u0007'); - break; - } - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': { - n9 = 2; - n8 = 1; - n10 = 1; - c3 = (char) (c - '0'); - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - break; - } - case 'D': - case 'O': - case 'U': - case 'X': - case 'd': - case 'o': - case 'u': - case 'x': { - switch (c) { - case 'U': - case 'u': { - n9 = 1; - break; - } - case 'X': - case 'x': { - n9 = 4; - break; - } - case 'O': - case 'o': { - n9 = 2; - break; - } - case 'D': - case 'd': { - n9 = 3; - break; - } - } - n8 = 1; - n10 = 0; - c3 = '\0'; - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - break; - } - } - n7 = 0; - } else if (c == this.userSettings.Delimiter) { - this.endColumn(); - } else if ((!this.useCustomRecordDelimiter && (c == '\r' || c == '\n')) || (this.useCustomRecordDelimiter && c == this.userSettings.RecordDelimiter)) { - this.endColumn(); - this.endRecord(); - } - this.lastLetter = c; - n11 = 0; - if (!this.startedColumn) { - continue; - } - final DataBuffer dataBuffer3 = this.dataBuffer; - ++dataBuffer3.Position; - if (this.userSettings.SafetySwitch && this.dataBuffer.Position - this.dataBuffer.ColumnStart + this.columnBuffer.Position > 100000) { - this.close(); - throw new IOException("Maximum column length of 100,000 exceeded in column " + NumberFormat.getIntegerInstance().format(this.columnsCount) + " in record " + NumberFormat.getIntegerInstance().format(this.currentRecord) + ". Set the SafetySwitch property to false" + " if you're expecting column lengths greater than 100,000 characters to" + " avoid this error."); - } - } - } while (this.hasMoreData && this.startedColumn); - } - if (!this.hasMoreData) { - continue; - } - final DataBuffer dataBuffer4 = this.dataBuffer; - ++dataBuffer4.Position; - } - } while (this.hasMoreData && !this.hasReadNextLine); - if (this.startedColumn || this.lastLetter == this.userSettings.Delimiter) { - this.endColumn(); - this.endRecord(); - } - } - if (this.userSettings.CaptureRawRecord) { - if (this.hasMoreData) { - if (this.rawBuffer.Position == 0) { - this.rawRecord = new String(this.dataBuffer.Buffer, this.dataBuffer.LineStart, this.dataBuffer.Position - this.dataBuffer.LineStart - 1); - } else { - this.rawRecord = new String(this.rawBuffer.Buffer, 0, this.rawBuffer.Position) + new String(this.dataBuffer.Buffer, this.dataBuffer.LineStart, this.dataBuffer.Position - this.dataBuffer.LineStart - 1); - } - } else { - this.rawRecord = new String(this.rawBuffer.Buffer, 0, this.rawBuffer.Position); - } - } else { - this.rawRecord = ""; - } - return this.hasReadNextLine; - } - - public boolean readHeaders() throws IOException { - final boolean record = this.readRecord(); - this.headersHolder.Length = this.columnsCount; - this.headersHolder.Headers = new String[this.columnsCount]; - for (int i = 0; i < this.headersHolder.Length; ++i) { - final String value = this.get(i); - this.headersHolder.Headers[i] = value; - this.headersHolder.IndexByName.put(value, i); - } - if (record) { - --this.currentRecord; - } - this.columnsCount = 0; - return record; - } - - public String getHeader(final int n) throws IOException { - this.checkClosed(); - if (n > -1 && n < this.headersHolder.Length) { - return this.headersHolder.Headers[n]; - } - return ""; - } - - public boolean isQualified(final int n) throws IOException { - this.checkClosed(); - return n < this.columnsCount && n > -1 && this.isQualified[n]; - } - - private void checkDataLength() throws IOException { - if (!this.initialized) { - if (this.fileName != null) { - this.inputStream = new BufferedReader(new InputStreamReader(new FileInputStream(this.fileName), this.charset), 4096); - } - this.charset = null; - this.initialized = true; - } - this.updateCurrentValue(); - if (this.userSettings.CaptureRawRecord && this.dataBuffer.Count > 0) { - if (this.rawBuffer.Buffer.length - this.rawBuffer.Position < this.dataBuffer.Count - this.dataBuffer.LineStart) { - final char[] buffer = new char[this.rawBuffer.Buffer.length + Math.max(this.dataBuffer.Count - this.dataBuffer.LineStart, this.rawBuffer.Buffer.length)]; - System.arraycopy(this.rawBuffer.Buffer, 0, buffer, 0, this.rawBuffer.Position); - this.rawBuffer.Buffer = buffer; - } - System.arraycopy(this.dataBuffer.Buffer, this.dataBuffer.LineStart, this.rawBuffer.Buffer, this.rawBuffer.Position, this.dataBuffer.Count - this.dataBuffer.LineStart); - final RawRecordBuffer rawBuffer = this.rawBuffer; - rawBuffer.Position += this.dataBuffer.Count - this.dataBuffer.LineStart; - } - try { - this.dataBuffer.Count = this.inputStream.read(this.dataBuffer.Buffer, 0, this.dataBuffer.Buffer.length); - } catch (IOException ex) { - this.close(); - throw ex; - } - if (this.dataBuffer.Count == -1) { - this.hasMoreData = false; - } - this.dataBuffer.Position = 0; - this.dataBuffer.LineStart = 0; - this.dataBuffer.ColumnStart = 0; - } - - private void appendLetter(final char c) { - if (this.columnBuffer.Position == this.columnBuffer.Buffer.length) { - final char[] buffer = new char[this.columnBuffer.Buffer.length * 2]; - System.arraycopy(this.columnBuffer.Buffer, 0, buffer, 0, this.columnBuffer.Position); - this.columnBuffer.Buffer = buffer; - } - this.columnBuffer.Buffer[this.columnBuffer.Position++] = c; - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - } - - private void updateCurrentValue() { - if (this.startedColumn && this.dataBuffer.ColumnStart < this.dataBuffer.Position) { - if (this.columnBuffer.Buffer.length - this.columnBuffer.Position < this.dataBuffer.Position - this.dataBuffer.ColumnStart) { - final char[] buffer = new char[this.columnBuffer.Buffer.length + Math.max(this.dataBuffer.Position - this.dataBuffer.ColumnStart, this.columnBuffer.Buffer.length)]; - System.arraycopy(this.columnBuffer.Buffer, 0, buffer, 0, this.columnBuffer.Position); - this.columnBuffer.Buffer = buffer; - } - System.arraycopy(this.dataBuffer.Buffer, this.dataBuffer.ColumnStart, this.columnBuffer.Buffer, this.columnBuffer.Position, this.dataBuffer.Position - this.dataBuffer.ColumnStart); - final ColumnBuffer columnBuffer = this.columnBuffer; - columnBuffer.Position += this.dataBuffer.Position - this.dataBuffer.ColumnStart; - } - this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - } - - public void endRecord() { - this.hasReadNextLine = true; - ++this.currentRecord; - } - - public int getIndex(final String s) throws IOException { - this.checkClosed(); - final Integer value = this.headersHolder.IndexByName.get(s); - if (value != null) { - return value; - } - return -1; - } - - public boolean skipRecord() throws IOException { - this.checkClosed(); - boolean record = false; - if (this.hasMoreData) { - record = this.readRecord(); - if (record) { - --this.currentRecord; - } - } - return record; - } - - public void endColumn() throws IOException { - String s = ""; - if (this.startedColumn) { - if (this.columnBuffer.Position == 0) { - if (this.dataBuffer.ColumnStart < this.dataBuffer.Position) { - int n = this.dataBuffer.Position - 1; - if (this.userSettings.TrimWhitespace && !this.startedWithQualifier) { - while (n >= this.dataBuffer.ColumnStart && (this.dataBuffer.Buffer[n] == ' ' || this.dataBuffer.Buffer[n] == '\t')) { - --n; - } - } - s = new String(this.dataBuffer.Buffer, this.dataBuffer.ColumnStart, n - this.dataBuffer.ColumnStart + 1); - } - } else { - this.updateCurrentValue(); - int n2 = this.columnBuffer.Position - 1; - if (this.userSettings.TrimWhitespace && !this.startedWithQualifier) { - while (n2 >= 0 && (this.columnBuffer.Buffer[n2] == ' ' || this.columnBuffer.Buffer[n2] == ' ')) { - --n2; - } - } - s = new String(this.columnBuffer.Buffer, 0, n2 + 1); - } - } - this.columnBuffer.Position = 0; - this.startedColumn = false; - if (this.columnsCount >= 100000 && this.userSettings.SafetySwitch) { - this.close(); - throw new IOException("Maximum column count of 100,000 exceeded in record " + NumberFormat.getIntegerInstance().format(this.currentRecord) + ". Set the SafetySwitch property to false" + " if you're expecting more than 100,000 columns per record to" + " avoid this error."); - } - if (this.columnsCount == this.values.length) { - final int n3 = this.values.length * 2; - final String[] values = new String[n3]; - System.arraycopy(this.values, 0, values, 0, this.values.length); - this.values = values; - final boolean[] isQualified = new boolean[n3]; - System.arraycopy(this.isQualified, 0, isQualified, 0, this.isQualified.length); - this.isQualified = isQualified; - } - this.values[this.columnsCount] = s; - this.isQualified[this.columnsCount] = this.startedWithQualifier; - ++this.columnsCount; - } - - public void close() { - if (!this.closed) { - this.close(true); - this.closed = true; - } - } - - private void close(final boolean b) { - if (!this.closed) { - if (b) { - this.charset = null; - this.headersHolder.Headers = null; - this.headersHolder.IndexByName = null; - this.dataBuffer.Buffer = null; - this.columnBuffer.Buffer = null; - this.rawBuffer.Buffer = null; - } - try { - if (this.initialized) { - this.inputStream.close(); - } - } catch (Exception ignored) { - } - this.inputStream = null; - this.closed = true; - } - } - - private void checkClosed() throws IOException { - if (this.closed) { - throw new IOException("This instance of the CsvReader class has already been closed."); - } - } - - public boolean skipLine() throws IOException { - this.checkClosed(); - this.columnsCount = 0; - boolean b = false; - if (this.hasMoreData) { - boolean b2 = false; - do { - if (this.dataBuffer.Position == this.dataBuffer.Count) { - this.checkDataLength(); - } else { - b = true; - final char lastLetter = this.dataBuffer.Buffer[this.dataBuffer.Position]; - if (lastLetter == '\r' || lastLetter == '\n') { - b2 = true; - } - this.lastLetter = lastLetter; - if (b2) { - continue; - } - final DataBuffer dataBuffer = this.dataBuffer; - ++dataBuffer.Position; - } - } while (this.hasMoreData && !b2); - this.columnBuffer.Position = 0; - this.dataBuffer.LineStart = this.dataBuffer.Position + 1; - } - this.rawBuffer.Position = 0; - this.rawRecord = ""; - return b; - } - - @Override - protected void finalize() { - this.close(false); - } - - private class StaticSettings { - public static final int MAX_BUFFER_SIZE = 1024; - public static final int MAX_FILE_BUFFER_SIZE = 4096; - public static final int INITIAL_COLUMN_COUNT = 10; - public static final int INITIAL_COLUMN_BUFFER_SIZE = 50; - } - - private class HeadersHolder { - public String[] Headers; - public int Length; - public HashMap IndexByName; - - public HeadersHolder() { - this.Headers = null; - this.Length = 0; - this.IndexByName = new HashMap<>(); - } - } - - private class UserSettings { - public boolean CaseSensitive; - public char TextQualifier; - public boolean TrimWhitespace; - public boolean UseTextQualifier; - public char Delimiter; - public char RecordDelimiter; - public char Comment; - public boolean UseComments; - public int EscapeMode; - public boolean SafetySwitch; - public boolean SkipEmptyRecords; - public boolean CaptureRawRecord; - - public UserSettings() { - this.CaseSensitive = true; - this.TextQualifier = '\"'; - this.TrimWhitespace = true; - this.UseTextQualifier = true; - this.Delimiter = ','; - this.RecordDelimiter = '\0'; - this.Comment = '#'; - this.UseComments = false; - this.EscapeMode = 1; - this.SafetySwitch = true; - this.SkipEmptyRecords = true; - this.CaptureRawRecord = true; - } - } - - private class Letters { - public static final char LF = '\n'; - public static final char CR = '\r'; - public static final char QUOTE = '\"'; - public static final char COMMA = ','; - public static final char SPACE = ' '; - public static final char TAB = '\t'; - public static final char POUND = '#'; - public static final char BACKSLASH = '\\'; - public static final char NULL = '\0'; - public static final char BACKSPACE = '\b'; - public static final char FORM_FEED = '\f'; - public static final char ESCAPE = '\u001b'; - public static final char VERTICAL_TAB = '\u000b'; - public static final char ALERT = '\u0007'; - } - - private class RawRecordBuffer { - public char[] Buffer; - public int Position; - - public RawRecordBuffer() { - this.Buffer = new char[500]; - this.Position = 0; - } - } - - private class ColumnBuffer { - public char[] Buffer; - public int Position; - - public ColumnBuffer() { - this.Buffer = new char[50]; - this.Position = 0; - } - } - - private class DataBuffer { - public char[] Buffer; - public int Position; - public int Count; - public int ColumnStart; - public int LineStart; - - public DataBuffer() { - this.Buffer = new char[1024]; - this.Position = 0; - this.Count = 0; - this.ColumnStart = 0; - this.LineStart = 0; - } - } - - private class ComplexEscape { - private static final int UNICODE = 1; - private static final int OCTAL = 2; - private static final int DECIMAL = 3; - private static final int HEX = 4; - } -} diff --git a/src/main/java/me/skymc/taboolib/csvutils/CsvWriter.java b/src/main/java/me/skymc/taboolib/csvutils/CsvWriter.java deleted file mode 100644 index 16923a2..0000000 --- a/src/main/java/me/skymc/taboolib/csvutils/CsvWriter.java +++ /dev/null @@ -1,320 +0,0 @@ -package me.skymc.taboolib.csvutils; - -import java.io.*; -import java.nio.charset.Charset; - -public class CsvWriter { - - private Writer outputStream; - private String fileName; - private boolean firstColumn; - private boolean useCustomRecordDelimiter; - private Charset charset; - private UserSettings userSettings; - private boolean initialized; - private boolean closed; - private String systemRecordDelimiter; - public static final int ESCAPE_MODE_DOUBLED = 1; - public static final int ESCAPE_MODE_BACKSLASH = 2; - - public CsvWriter(final String fileName, final char delimiter, final Charset charset) { - this.outputStream = null; - this.fileName = null; - this.firstColumn = true; - this.useCustomRecordDelimiter = false; - this.charset = null; - this.userSettings = new UserSettings(); - this.initialized = false; - this.closed = false; - this.systemRecordDelimiter = System.getProperty("line.separator"); - if (fileName == null) { - throw new IllegalArgumentException("Parameter fileName can not be null."); - } - if (charset == null) { - throw new IllegalArgumentException("Parameter charset can not be null."); - } - this.fileName = fileName; - this.userSettings.Delimiter = delimiter; - this.charset = charset; - } - - public CsvWriter(final String s) { - this(s, ',', Charset.forName("ISO-8859-1")); - } - - public CsvWriter(final Writer outputStream, final char delimiter) { - this.outputStream = null; - this.fileName = null; - this.firstColumn = true; - this.useCustomRecordDelimiter = false; - this.charset = null; - this.userSettings = new UserSettings(); - this.initialized = false; - this.closed = false; - this.systemRecordDelimiter = System.getProperty("line.separator"); - if (outputStream == null) { - throw new IllegalArgumentException("Parameter outputStream can not be null."); - } - this.outputStream = outputStream; - this.userSettings.Delimiter = delimiter; - this.initialized = true; - } - - public CsvWriter(final OutputStream outputStream, final char c, final Charset charset) { - this(new OutputStreamWriter(outputStream, charset), c); - } - - public char getDelimiter() { - return this.userSettings.Delimiter; - } - - public void setDelimiter(final char delimiter) { - this.userSettings.Delimiter = delimiter; - } - - public char getRecordDelimiter() { - return this.userSettings.RecordDelimiter; - } - - public void setRecordDelimiter(final char recordDelimiter) { - this.useCustomRecordDelimiter = true; - this.userSettings.RecordDelimiter = recordDelimiter; - } - - public char getTextQualifier() { - return this.userSettings.TextQualifier; - } - - public void setTextQualifier(final char textQualifier) { - this.userSettings.TextQualifier = textQualifier; - } - - public boolean getUseTextQualifier() { - return this.userSettings.UseTextQualifier; - } - - public void setUseTextQualifier(final boolean useTextQualifier) { - this.userSettings.UseTextQualifier = useTextQualifier; - } - - public int getEscapeMode() { - return this.userSettings.EscapeMode; - } - - public void setEscapeMode(final int escapeMode) { - this.userSettings.EscapeMode = escapeMode; - } - - public void setComment(final char comment) { - this.userSettings.Comment = comment; - } - - public char getComment() { - return this.userSettings.Comment; - } - - public boolean getForceQualifier() { - return this.userSettings.ForceQualifier; - } - - public void setForceQualifier(final boolean forceQualifier) { - this.userSettings.ForceQualifier = forceQualifier; - } - - public void write(String s, final boolean b) throws IOException { - this.checkClosed(); - this.checkInit(); - if (s == null) { - s = ""; - } - if (!this.firstColumn) { - this.outputStream.write(this.userSettings.Delimiter); - } - int forceQualifier = this.userSettings.ForceQualifier ? 1 : 0; - if (!b && s.length() > 0) { - s = s.trim(); - } - if (forceQualifier == 0 && this.userSettings.UseTextQualifier && (s.indexOf(this.userSettings.TextQualifier) > -1 || s.indexOf(this.userSettings.Delimiter) > -1 || (!this.useCustomRecordDelimiter && (s.indexOf(10) > -1 || s.indexOf(13) > -1)) || (this.useCustomRecordDelimiter && s.indexOf(this.userSettings.RecordDelimiter) > -1) || (this.firstColumn && s.length() > 0 && s.charAt(0) == this.userSettings.Comment) || (this.firstColumn && s.length() == 0))) { - forceQualifier = 1; - } - if (this.userSettings.UseTextQualifier && forceQualifier == 0 && s.length() > 0 && b) { - final char char1 = s.charAt(0); - if (char1 == ' ' || char1 == '\t') { - forceQualifier = 1; - } - if (forceQualifier == 0 && s.length() > 1) { - final char char2 = s.charAt(s.length() - 1); - if (char2 == ' ' || char2 == '\t') { - forceQualifier = 1; - } - } - } - if (forceQualifier != 0) { - this.outputStream.write(this.userSettings.TextQualifier); - if (this.userSettings.EscapeMode == 2) { - s = replace(s, "\\", "\\\\"); - s = replace(s, "" + this.userSettings.TextQualifier, "\\" + this.userSettings.TextQualifier); - } else { - s = replace(s, "" + this.userSettings.TextQualifier, "" + this.userSettings.TextQualifier + this.userSettings.TextQualifier); - } - } else if (this.userSettings.EscapeMode == 2) { - s = replace(s, "\\", "\\\\"); - s = replace(s, "" + this.userSettings.Delimiter, "\\" + this.userSettings.Delimiter); - if (this.useCustomRecordDelimiter) { - s = replace(s, "" + this.userSettings.RecordDelimiter, "\\" + this.userSettings.RecordDelimiter); - } else { - s = replace(s, "\r", "\\\r"); - s = replace(s, "\n", "\\\n"); - } - if (this.firstColumn && s.length() > 0 && s.charAt(0) == this.userSettings.Comment) { - if (s.length() > 1) { - s = "\\" + this.userSettings.Comment + s.substring(1); - } else { - s = "\\" + this.userSettings.Comment; - } - } - } - this.outputStream.write(s); - if (forceQualifier != 0) { - this.outputStream.write(this.userSettings.TextQualifier); - } - this.firstColumn = false; - } - - public void write(final String s) throws IOException { - this.write(s, false); - } - - public void writeComment(final String s) throws IOException { - this.checkClosed(); - this.checkInit(); - this.outputStream.write(this.userSettings.Comment); - this.outputStream.write(s); - if (this.useCustomRecordDelimiter) { - this.outputStream.write(this.userSettings.RecordDelimiter); - } else { - this.outputStream.write(this.systemRecordDelimiter); - } - this.firstColumn = true; - } - - public static String replace(final String s, final String s2, final String s3) { - final int length = s2.length(); - int i = s.indexOf(s2); - if (i > -1) { - final StringBuilder sb = new StringBuilder(); - int n; - for (n = 0; i != -1; i = s.indexOf(s2, n)) { - sb.append(s, n, i); - sb.append(s3); - n = i + length; - } - sb.append(s.substring(n)); - return sb.toString(); - } - return s; - } - - public void writeRecord(final String[] array) throws IOException { - this.writeRecord(array, false); - } - - public void endRecord() throws IOException { - this.checkClosed(); - this.checkInit(); - if (this.useCustomRecordDelimiter) { - this.outputStream.write(this.userSettings.RecordDelimiter); - } else { - this.outputStream.write(this.systemRecordDelimiter); - } - this.firstColumn = true; - } - - private void checkInit() throws IOException { - if (!this.initialized) { - if (this.fileName != null) { - this.outputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.fileName), this.charset)); - } - this.initialized = true; - } - } - - public void flush() throws IOException { - this.outputStream.flush(); - } - - public void close() { - if (!this.closed) { - this.close(true); - this.closed = true; - } - } - - public void writeRecord(final String[] array, final boolean b) throws IOException { - if (array != null && array.length > 0) { - for (String anArray : array) { - this.write(anArray, b); - } - this.endRecord(); - } - } - - private void checkClosed() throws IOException { - if (this.closed) { - throw new IOException("This instance of the CsvWriter class has already been closed."); - } - } - - @Override - protected void finalize() { - this.close(false); - } - - private void close(final boolean b) { - if (!this.closed) { - if (b) { - this.charset = null; - } - try { - if (this.initialized) { - this.outputStream.close(); - } - } catch (Exception ignored) { - } - this.outputStream = null; - this.closed = true; - } - } - - private class UserSettings { - public char TextQualifier; - public boolean UseTextQualifier; - public char Delimiter; - public char RecordDelimiter; - public char Comment; - public int EscapeMode; - public boolean ForceQualifier; - - public UserSettings() { - this.TextQualifier = '\"'; - this.UseTextQualifier = true; - this.Delimiter = ','; - this.RecordDelimiter = '\0'; - this.Comment = '#'; - this.EscapeMode = 1; - this.ForceQualifier = false; - } - } - - private class Letters { - public static final char LF = '\n'; - public static final char CR = '\r'; - public static final char QUOTE = '\"'; - public static final char COMMA = ','; - public static final char SPACE = ' '; - public static final char TAB = '\t'; - public static final char POUND = '#'; - public static final char BACKSLASH = '\\'; - public static final char NULL = '\0'; - } -} diff --git a/src/main/java/me/skymc/taboolib/damage/GetDamager.java b/src/main/java/me/skymc/taboolib/damage/GetDamager.java deleted file mode 100644 index cb171d3..0000000 --- a/src/main/java/me/skymc/taboolib/damage/GetDamager.java +++ /dev/null @@ -1,14 +0,0 @@ -package me.skymc.taboolib.damage; - -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.event.entity.EntityDamageByEntityEvent; - -@Deprecated -public class GetDamager { - - public static Player get(EntityDamageByEntityEvent e) { - return DamageUtils.getAttackerInDamageEvent(e); - } - -} diff --git a/src/main/java/me/skymc/taboolib/damage/GetKiller.java b/src/main/java/me/skymc/taboolib/damage/GetKiller.java deleted file mode 100644 index 0fcc95b..0000000 --- a/src/main/java/me/skymc/taboolib/damage/GetKiller.java +++ /dev/null @@ -1,13 +0,0 @@ -package me.skymc.taboolib.damage; - -import org.bukkit.entity.Player; -import org.bukkit.event.entity.EntityDeathEvent; - -@Deprecated -public class GetKiller { - - public static Player get(EntityDeathEvent e) { - return e.getEntity().getKiller(); - } - -} diff --git a/src/main/java/me/skymc/taboolib/display/ActionUtils.java b/src/main/java/me/skymc/taboolib/display/ActionUtils.java deleted file mode 100644 index 530224b..0000000 --- a/src/main/java/me/skymc/taboolib/display/ActionUtils.java +++ /dev/null @@ -1,49 +0,0 @@ -package me.skymc.taboolib.display; - -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.nms.NMSUtils; -import org.bukkit.entity.Player; - -import java.lang.reflect.Constructor; - -/** - * @author Bkm016 - * @since 2018-04-26 - */ -public class ActionUtils { - - private static Class Packet = NMSUtils.getNMSClass("Packet"); - private static Class ChatComponentText = NMSUtils.getNMSClass("ChatComponentText"); - private static Class ChatMessageType = NMSUtils.getNMSClass("ChatMessageType"); - private static Class PacketPlayOutChat = NMSUtils.getNMSClass("PacketPlayOutChat"); - private static Class IChatBaseComponent = NMSUtils.getNMSClass("IChatBaseComponent"); - - public static void send(Player player, String action) { - if (player == null) { - return; - } - try { - Object ab = ChatComponentText.getConstructor(String.class).newInstance(action); - Constructor ac; - Object abPacket; - if (TabooLib.getVerint() > 11100) { - ac = PacketPlayOutChat.getConstructor(IChatBaseComponent, ChatMessageType); - abPacket = ac.newInstance(ab, ChatMessageType.getMethod("a", Byte.TYPE).invoke(null, (byte) 2)); - } else { - ac = PacketPlayOutChat.getConstructor(IChatBaseComponent, Byte.TYPE); - abPacket = ac.newInstance(ab, (byte) 2); - } - sendPacket(player, abPacket); - } catch (Exception ignored) { - } - } - - private static void sendPacket(Player player, Object packet) { - try { - Object handle = player.getClass().getMethod("getHandle", new Class[0]).invoke(player); - Object playerConnection = handle.getClass().getField("playerConnection").get(handle); - playerConnection.getClass().getMethod("sendPacket", Packet).invoke(playerConnection, packet); - } catch (Exception ignored) { - } - } -} \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/display/TitleUtils.java b/src/main/java/me/skymc/taboolib/display/TitleUtils.java deleted file mode 100644 index 28cfb42..0000000 --- a/src/main/java/me/skymc/taboolib/display/TitleUtils.java +++ /dev/null @@ -1,66 +0,0 @@ -package me.skymc.taboolib.display; - -import me.skymc.taboolib.nms.NMSUtils; -import org.bukkit.entity.Player; - -import java.lang.reflect.Constructor; - -/** - * @author Bkm016 - * @since 2018-04-26 - */ -public class TitleUtils { - - private static Class Packet = NMSUtils.getNMSClass("Packet"); - private static Class PacketPlayOutTitle = NMSUtils.getNMSClass("PacketPlayOutTitle"); - private static Class IChatBaseComponent = NMSUtils.getNMSClass("IChatBaseComponent"); - private static Class EnumTitleAction = PacketPlayOutTitle.getDeclaredClasses()[0]; - - public static void sendTitle(Player p, String title, String subtitle, int fadein, int stay, int fadeout) { - sendTitle(p, title, fadein, stay, fadeout, subtitle, fadein, stay, fadeout); - } - - public static void sendTitle(Player p, String title, int fadeint, int stayt, int fadeoutt, String subtitle, int fadeinst, int stayst, int fadeoutst) { - if (p == null) { - return; - } - try { - if (title != null) { - Object times = EnumTitleAction.getField("TIMES").get(null); - Object chatTitle = IChatBaseComponent.getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + title + "\"}"); - Constructor subtitleConstructor = PacketPlayOutTitle.getConstructor(EnumTitleAction, IChatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE); - Object titlePacket = subtitleConstructor.newInstance(times, chatTitle, fadeint, stayt, fadeoutt); - sendPacket(p, titlePacket); - - times = EnumTitleAction.getField("TITLE").get(null); - chatTitle = IChatBaseComponent.getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + title + "\"}"); - subtitleConstructor = PacketPlayOutTitle.getConstructor(EnumTitleAction, IChatBaseComponent); - titlePacket = subtitleConstructor.newInstance(times, chatTitle); - sendPacket(p, titlePacket); - } - if (subtitle != null) { - Object times = EnumTitleAction.getField("TIMES").get(null); - Object chatSubtitle = IChatBaseComponent.getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + title + "\"}"); - Constructor subtitleConstructor = PacketPlayOutTitle.getConstructor(EnumTitleAction, IChatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE); - Object subtitlePacket = subtitleConstructor.newInstance(times, chatSubtitle, fadeinst, stayst, fadeoutst); - sendPacket(p, subtitlePacket); - - times = EnumTitleAction.getField("SUBTITLE").get(null); - chatSubtitle = IChatBaseComponent.getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + subtitle + "\"}"); - subtitleConstructor = PacketPlayOutTitle.getConstructor(EnumTitleAction, IChatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE); - subtitlePacket = subtitleConstructor.newInstance(times, chatSubtitle, fadeinst, stayst, fadeoutst); - sendPacket(p, subtitlePacket); - } - } catch (Exception ignored) { - } - } - - private static void sendPacket(Player player, Object packet) { - try { - Object handle = player.getClass().getDeclaredMethod("getHandle").invoke(player); - Object playerConnection = handle.getClass().getDeclaredField("playerConnection").get(handle); - playerConnection.getClass().getDeclaredMethod("sendPacket", Packet).invoke(playerConnection, packet); - } catch (Exception ignored) { - } - } -} diff --git a/src/main/java/me/skymc/taboolib/economy/EcoUtils.java b/src/main/java/me/skymc/taboolib/economy/EcoUtils.java deleted file mode 100644 index 9d4fb41..0000000 --- a/src/main/java/me/skymc/taboolib/economy/EcoUtils.java +++ /dev/null @@ -1,33 +0,0 @@ -package me.skymc.taboolib.economy; - -import me.skymc.taboolib.Main; -import net.milkbowl.vault.economy.Economy; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.plugin.RegisteredServiceProvider; - -public class EcoUtils { - - public static void setupEconomy() { - RegisteredServiceProvider l = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); - if (l != null) { - Main.setEconomy(l.getProvider()); - } - } - - public static void remove(OfflinePlayer p, double d) { - Main.getEconomy().withdrawPlayer(p, d); - } - - public static void add(OfflinePlayer p, double d) { - Main.getEconomy().depositPlayer(p, d); - } - - public static double get(OfflinePlayer p) { - return Main.getEconomy().getBalance(p); - } - - public static void create(OfflinePlayer p) { - Main.getEconomy().createPlayerAccount(p); - } -} diff --git a/src/main/java/me/skymc/taboolib/enchantment/EnchantmentUtils.java b/src/main/java/me/skymc/taboolib/enchantment/EnchantmentUtils.java deleted file mode 100644 index c1d05cc..0000000 --- a/src/main/java/me/skymc/taboolib/enchantment/EnchantmentUtils.java +++ /dev/null @@ -1,19 +0,0 @@ -package me.skymc.taboolib.enchantment; - -import org.bukkit.enchantments.Enchantment; - -import java.lang.reflect.Field; - -public class EnchantmentUtils { - - public static void setAcceptingNew(boolean value) { - try { - Field f = Enchantment.class.getDeclaredField("acceptingNew"); - f.setAccessible(true); - f.set(null, value); - } - catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/me/skymc/taboolib/entity/EntityTag.java b/src/main/java/me/skymc/taboolib/entity/EntityTag.java deleted file mode 100644 index f24ea66..0000000 --- a/src/main/java/me/skymc/taboolib/entity/EntityTag.java +++ /dev/null @@ -1,279 +0,0 @@ -package me.skymc.taboolib.entity; - -import me.skymc.taboolib.Main; -import org.bukkit.entity.Entity; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 伪 - MetaData - * - * @author sky - * @since 2018-03-11 11:43:41 - */ -public class EntityTag { - - private static EntityTag inst; - private static ConcurrentHashMap> entityData = new ConcurrentHashMap<>(); - - private EntityTag() { - new BukkitRunnable() { - - @Override - public void run() { - for (UUID uuid : entityData.keySet()) { - if (EntityUtils.getEntityWithUUID(uuid) == null) { - entityData.remove(uuid); - } - } - } - }.runTaskTimerAsynchronously(Main.getInst(), 20 * 180, 20 * 180); - } - - public static EntityTag getInst() { - if (inst == null) { - synchronized (EntityTag.class) { - if (inst == null) { - inst = new EntityTag(); - } - } - } - return inst; - } - - /** - * 设置标签 - * - * @param entity 实体 - * @param key 键 - * @param value 值 - */ - public void set(String key, Object value, Entity entity) { - if (contains(entity)) { - entityData.get(entity.getUniqueId()).put(key, value); - } else { - ConcurrentHashMap map = new ConcurrentHashMap<>(); - map.put(key, value); - entityData.put(entity.getUniqueId(), map); - } - } - - /** - * 设置标签 - * - * @param key 键 - * @param value 值 - */ - public void set(String key, Object value, Entity... entities) { - for (Entity entity : entities) { - set(key, value, entity); - } - } - - /** - * 设置标签 - * - * @param key 键 - * @param value 值 - */ - public void set(String key, Object value, List entities) { - for (Entity entity : entities) { - set(key, value, entity); - } - } - - /** - * 移除标签 - * - * @param key 键 - * @param entity 实体 - */ - public Object remove(String key, Entity entity) { - if (contains(entity)) { - entityData.get(entity.getUniqueId()).remove(key); - if (entityData.get(entity.getUniqueId()).size() == 0) { - return entityData.remove(entity.getUniqueId()); - } - } - return null; - } - - /** - * 移除标签 - * - * @param key 键 - * @param entities 实体 - */ - public void remove(String key, Entity... entities) { - for (Entity entity : entities) { - remove(key, entity); - } - } - - /** - * 移除标签 - * - * @param key 键 - * @param entities 实体 - */ - public void remove(String key, List entities) { - for (Entity entity : entities) { - remove(key, entity); - } - } - - /** - * 检查数据 - * - * @param entity 实体 - * @return boolean - */ - public boolean contains(Entity entity) { - return entityData.containsKey(entity.getUniqueId()); - } - - /** - * 检查标签 - * - * @param key 键 - * @param entity 实体 - * @return boolean - */ - public boolean hasKey(String key, Entity entity) { - return contains(entity) && entityData.get(entity.getUniqueId()).containsKey(key); - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return Object - */ - public Object get(String key, Entity entity) { - if (contains(entity)) { - return entityData.get(entity.getUniqueId()).get(key); - } - return null; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 值 - * @return String - */ - public String getString(String key, Entity entity) { - Object object = get(key, entity); - if (object instanceof String) { - return (String) object; - } - return null; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 值 - * @return int - */ - public int getInteger(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (int) object; - } - return 0; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 值 - * @return long - */ - public long getLong(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (long) object; - } - return 0L; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return boolean - */ - public boolean getBoolean(String key, Entity entity) { - Object object = get(key, entity); - return object != null && (boolean) object; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return double - */ - public double getDouble(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (double) object; - } - return 0D; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return float - */ - public double getFloat(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (float) object; - } - return 0F; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return short - */ - public short getShort(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (short) object; - } - return (short) 0; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return byte - */ - public byte getByte(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (byte) object; - } - return (byte) 0; - } -} diff --git a/src/main/java/me/skymc/taboolib/entity/EntityUtils.java b/src/main/java/me/skymc/taboolib/entity/EntityUtils.java deleted file mode 100644 index d324e00..0000000 --- a/src/main/java/me/skymc/taboolib/entity/EntityUtils.java +++ /dev/null @@ -1,111 +0,0 @@ -package me.skymc.taboolib.entity; - -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.listener.TListener; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntitySpawnEvent; - -import java.lang.reflect.InvocationTargetException; -import java.util.UUID; - -/** - * @author sky - */ -@TListener(condition = "check") -public class EntityUtils implements Listener { - - private static Entity lastSpawnedEntity = null; - - public static Entity getLastSpawnedEntity() { - return lastSpawnedEntity; - } - - public static boolean check() { - return TabooLib.getVerint() > 10700; - } - - /** - * 根据 UUID 获取生物 - * - * @param u - * @return - */ - public static Entity getEntityWithUUID(UUID u) { - return Bukkit.getWorlds().stream().flatMap(w -> w.getLivingEntities().stream()).filter(e -> e.getUniqueId().equals(u)).findFirst().orElse(null); - } - - /** - * 根据 UUID 获取生物(单世界) - * - * @param u - * @param world - * @return - */ - public static Entity getEntityWithUUID(UUID u, World world) { - return world.getLivingEntities().stream().filter(e -> e.getUniqueId().equals(u)).findFirst().orElse(null); - } - - /** - * 设置生物发光(ProcotolLib) - * - * @param player - * @param entity - */ - public static void addGlow(Player player, Entity entity) { - if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) { - TLocale.sendToConsole("ENTITY-UTILS.NOTFOUND-PROTOCOLLIB"); - } - PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); - packet.getIntegers().write(0, entity.getEntityId()); - WrappedDataWatcher watcher = new WrappedDataWatcher(); - WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(Byte.class); - watcher.setEntity(player); - watcher.setObject(0, serializer, (byte) (0x40)); - packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); - try { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - - /** - * 取消生物发光(ProcotolLib) - * - * @param player - * @param entity - */ - public static void delGlow(Player player, Entity entity) { - if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) { - TLocale.sendToConsole("ENTITY-UTILS.NOTFOUND-PROTOCOLLIB"); - } - PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); - packet.getIntegers().write(0, entity.getEntityId()); - WrappedDataWatcher watcher = new WrappedDataWatcher(); - WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(Byte.class); - watcher.setEntity(player); - watcher.setObject(0, serializer, (byte) (0x0)); - packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); - try { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - - @EventHandler - public void spawn(EntitySpawnEvent e) { - lastSpawnedEntity = e.getEntity(); - } - -} diff --git a/src/main/java/me/skymc/taboolib/entity/VectorUtils.java b/src/main/java/me/skymc/taboolib/entity/VectorUtils.java deleted file mode 100644 index e174206..0000000 --- a/src/main/java/me/skymc/taboolib/entity/VectorUtils.java +++ /dev/null @@ -1,122 +0,0 @@ -package me.skymc.taboolib.entity; - -import me.skymc.taboolib.other.NumberUtils; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Item; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.Vector; - -import java.util.stream.IntStream; - -/** - * @Author sky - * @Since 2018-06-24 16:32 - */ -public class VectorUtils { - - /** - * 物品丢弃 - *

- * 常用参数: - * itemDrop(player, itemStack, 0.2, 0.5) - * - * @param player 玩家 - * @param itemStack 丢弃物品 - * @param bulletSpread 视角偏移 - * @param radius 距离 - * @return {@link Item} - */ - public static Item itemDrop(Player player, ItemStack itemStack, double bulletSpread, double radius) { - Location location = player.getLocation().add(0, 1.5, 0); - Item item = player.getWorld().dropItem(location, itemStack); - - double yaw = Math.toRadians(-player.getLocation().getYaw() - 90.0F); - double pitch = Math.toRadians(-player.getLocation().getPitch()); - double x; - double y; - double z; - - if (bulletSpread > 0) { - double[] spread = {1.0D, 1.0D, 1.0D}; - IntStream.range(0, 3).forEach(t -> spread[t] = ((NumberUtils.getRandom().nextDouble() - NumberUtils.getRandom().nextDouble()) * bulletSpread * 0.1D)); - x = Math.cos(pitch) * Math.cos(yaw) + spread[0]; - y = Math.sin(pitch) + spread[1]; - z = -Math.sin(yaw) * Math.cos(pitch) + spread[2]; - } else { - x = Math.cos(pitch) * Math.cos(yaw); - y = Math.sin(pitch); - z = -Math.sin(yaw) * Math.cos(pitch); - } - - Vector dirVel = new Vector(x, y, z); - item.setVelocity(dirVel.normalize().multiply(radius)); - return item; - } - - /** - * 生物抛射 - *

- * 常用参数: - * entityPush(entity, location, 15) - * - * @param entity 目标生物 - * @param to 目标坐标 - * @param velocity 力量 - */ - public static void entityPush(Entity entity, Location to, double velocity) { - Location from = entity.getLocation(); - - Vector test = to.clone().subtract(from).toVector(); - double elevation = test.getY(); - - Double launchAngle = calculateLaunchAngle(from, to, velocity, elevation, 20.0D); - double distance = Math.sqrt(Math.pow(test.getX(), 2.0D) + Math.pow(test.getZ(), 2.0D)); - if (distance == 0.0D) { - return; - } - if (launchAngle == null) { - launchAngle = Math.atan((40.0D * elevation + Math.pow(velocity, 2.0D)) / (40.0D * elevation + 2.0D * Math.pow(velocity, 2.0D))); - } - double hangTime = calculateHangTime(launchAngle, velocity, elevation, 20.0D); - - test.setY(Math.tan(launchAngle) * distance); - test = normalizeVector(test); - - Vector noise = Vector.getRandom(); - noise = noise.multiply(1 / 10.0D); - test.add(noise); - - velocity = velocity + 1.188D * Math.pow(hangTime, 2.0D) + (NumberUtils.getRandom().nextDouble() - 0.8D) / 2.0D; - test = test.multiply(velocity / 20.0D); - - entity.setVelocity(test); - } - - // ********************************* - // - // Private Methods - // - // ********************************* - - private static double calculateHangTime(double launchAngle, double v, double elev, double g) { - double a = v * Math.sin(launchAngle); - double b = -2.0D * g * elev; - return Math.pow(a, 2.0D) + b < 0.0D ? 0.0D : (a + Math.sqrt(Math.pow(a, 2.0D) + b)) / g; - } - - private static Vector normalizeVector(Vector victor) { - double mag = Math.sqrt(Math.pow(victor.getX(), 2.0D) + Math.pow(victor.getY(), 2.0D) + Math.pow(victor.getZ(), 2.0D)); - return mag != 0.0D ? victor.multiply(1.0D / mag) : victor.multiply(0); - } - - private static Double calculateLaunchAngle(Location from, Location to, double v, double elevation, double g) { - Vector vector = from.clone().subtract(to).toVector(); - double distance = Math.sqrt(Math.pow(vector.getX(), 2.0D) + Math.pow(vector.getZ(), 2.0D)); - double v2 = Math.pow(v, 2.0D); - double v4 = Math.pow(v, 4.0D); - double check = g * (g * Math.pow(distance, 2.0D) + 2.0D * elevation * v2); - return v4 < check ? null : Math.atan((v2 - Math.sqrt(v4 - check)) / (g * distance)); - } -} diff --git a/src/main/java/me/skymc/taboolib/events/DefaultEvent.java b/src/main/java/me/skymc/taboolib/events/DefaultEvent.java deleted file mode 100644 index cc24099..0000000 --- a/src/main/java/me/skymc/taboolib/events/DefaultEvent.java +++ /dev/null @@ -1,28 +0,0 @@ -package me.skymc.taboolib.events; - -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -public class DefaultEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - private Player player; - - public DefaultEvent(Player player) { - this.player = player; - } - - public Player getPlayer() { - return this.player; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java index f11b99f..5c3ad6a 100644 --- a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java +++ b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java @@ -160,6 +160,20 @@ public class FileUtils { } } + /** + * 释放资源文件 + * + * @param plugin 所属插件 + * @param path 地址 + * @param replace 是否替换 + */ + public static void releaseResource(Plugin plugin, String path, boolean replace) { + File file = new File(plugin.getDataFolder(), path); + if (!file.exists() || replace) { + inputStreamToFile(getResource(plugin, path), file); + } + } + /** * 检测文件并创建 * diff --git a/src/main/java/me/skymc/taboolib/inventory/DropUtils.java b/src/main/java/me/skymc/taboolib/inventory/DropUtils.java deleted file mode 100644 index 0da14da..0000000 --- a/src/main/java/me/skymc/taboolib/inventory/DropUtils.java +++ /dev/null @@ -1,20 +0,0 @@ -package me.skymc.taboolib.inventory; - -import me.skymc.taboolib.entity.VectorUtils; -import me.skymc.taboolib.other.NumberUtils; -import org.bukkit.Location; -import org.bukkit.entity.Item; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.Vector; - -import java.util.stream.IntStream; - -@Deprecated -public class DropUtils { - - public static Item drop(Player player, ItemStack itemStack, double bulletSpread, double radius) { - return VectorUtils.itemDrop(player, itemStack, bulletSpread, radius); - } - -} diff --git a/src/main/java/me/skymc/taboolib/inventory/InventoryUtil.java b/src/main/java/me/skymc/taboolib/inventory/InventoryUtil.java deleted file mode 100644 index 67bd4da..0000000 --- a/src/main/java/me/skymc/taboolib/inventory/InventoryUtil.java +++ /dev/null @@ -1,120 +0,0 @@ -package me.skymc.taboolib.inventory; - -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.util.Arrays; -import java.util.LinkedList; - -/** - * @author sky - */ -public class InventoryUtil { - - public final static LinkedList SLOT_OF_CENTENTS = new LinkedList<>(Arrays.asList( - 10, 11, 12, 13, 14, 15, 16, - 19, 20, 21, 22, 23, 24, 25, - 28, 29, 30, 31, 32, 33, 34, - 37, 38, 39, 40, 41, 42, 43)); - - @Deprecated - public static boolean isEmpey(Player p) { - return isEmpty(p, 0); - } - - /** - * 检查背包是否有空位 - * - * @param p 玩家 - * @param i 起始位置 - */ - public static boolean isEmpty(Player p, int i) { - while (i < 35) { - if (p.getInventory().getItem(i) == null) { - return true; - } - i++; - } - return false; - } - - /** - * 检测玩家是否有指定物品 - * - * @param player 玩家 - * @param item 物品 - * @param amount 数量 - * @param remove 是否删除 - */ - public static boolean hasItem(Player player, ItemStack item, int amount, boolean remove) { - int hasAmount = 0; - for (ItemStack _item : player.getInventory()) { - if (item.isSimilar(_item)) { - hasAmount += _item.getAmount(); - } - } - if (hasAmount < amount) { - return false; - } - int requireAmount = amount; - for (int i = 0; i < player.getInventory().getSize() && remove; i++) { - ItemStack _item = player.getInventory().getItem(i); - if (_item != null && _item.isSimilar(item)) { - if (_item.getAmount() < requireAmount) { - player.getInventory().setItem(i, null); - requireAmount -= _item.getAmount(); - } else if (_item.getAmount() == requireAmount) { - player.getInventory().setItem(i, null); - return true; - } else { - _item.setAmount(_item.getAmount() - requireAmount); - return true; - } - } - } - return true; - } - - @Deprecated - public static boolean hasItem(Inventory targetInventory, ItemStack targetItem, Integer amount) { - int inventoryAmount = 0; - for (ItemStack item : targetInventory) { - if (item != null) { - if (item.isSimilar(targetItem)) { - inventoryAmount += item.getAmount(); - } - } - } - return inventoryAmount >= amount; - } - - @Deprecated - public static boolean takeItem2(Inventory inv, ItemStack takeitem, Integer amount) { - for (int i = 0; i < inv.getSize(); ++i) { - if (amount <= 0) { - return true; - } - - ItemStack item = inv.getItem(i); - if (item == null) { - continue; - } - if (!item.isSimilar(takeitem)) { - continue; - } - if (item.getAmount() >= amount) { - if (item.getAmount() - amount == 0) { - inv.setItem(i, null); - } else { - item.setAmount(item.getAmount() - amount); - } - return true; - } else { - amount -= item.getAmount(); - inv.setItem(i, null); - } - } - return false; - } -} diff --git a/src/main/java/me/skymc/taboolib/inventory/builder/ItemBuilder.java b/src/main/java/me/skymc/taboolib/inventory/builder/ItemBuilder.java index 6e3a7d5..b418223 100644 --- a/src/main/java/me/skymc/taboolib/inventory/builder/ItemBuilder.java +++ b/src/main/java/me/skymc/taboolib/inventory/builder/ItemBuilder.java @@ -42,6 +42,11 @@ public class ItemBuilder { itemMeta = itemStack.getItemMeta(); } + public ItemBuilder(ItemStack itemStack) { + this.itemStack = itemStack; + this.itemMeta = itemStack.getItemMeta(); + } + public ItemBuilder(OfflinePlayer player) { this(Material.SKULL_ITEM, 1, 3); this.skullOwner(player.getName()); diff --git a/src/main/java/me/skymc/taboolib/inventory/speciaitem/AbstractSpecialItem.java b/src/main/java/me/skymc/taboolib/inventory/speciaitem/AbstractSpecialItem.java deleted file mode 100644 index b29164a..0000000 --- a/src/main/java/me/skymc/taboolib/inventory/speciaitem/AbstractSpecialItem.java +++ /dev/null @@ -1,46 +0,0 @@ -package me.skymc.taboolib.inventory.speciaitem; - -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.Plugin; - -/** - * @author sky - * @since 2018年2月17日 下午8:35:42 - */ -public interface AbstractSpecialItem { - - /** - * 当接口被载入 - */ - default void onEnable() {} - - /** - * 当接口被卸载 - */ - default void onDisable() {} - - /** - * 获取识别名称 - * - * @return String - */ - String getName(); - - /** - * 获取载入插件 - * - * @return {@link Plugin} - */ - Plugin getPlugin(); - - /** - * 是否进行点击事件 - * - * @param player 玩家 - * @param currentItem 点击物品 - * @param cursorItem 持有物品 - * @return {@link SpecialItemResult[]} - */ - SpecialItemResult[] isCorrectClick(Player player, ItemStack currentItem, ItemStack cursorItem); -} diff --git a/src/main/java/me/skymc/taboolib/inventory/speciaitem/SpecialItem.java b/src/main/java/me/skymc/taboolib/inventory/speciaitem/SpecialItem.java deleted file mode 100644 index 6a5c9c8..0000000 --- a/src/main/java/me/skymc/taboolib/inventory/speciaitem/SpecialItem.java +++ /dev/null @@ -1,184 +0,0 @@ -package me.skymc.taboolib.inventory.speciaitem; - -import me.skymc.taboolib.Main; -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.message.MsgUtils; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.plugin.Plugin; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * @author sky - * @since 2018年2月17日 下午8:34:12 - */ -public class SpecialItem implements Listener { - - private static SpecialItem specialItem = null; - - private final List ITEM_DATA = new CopyOnWriteArrayList<>(); - - private boolean isLoaded; - - /** - * 构造方法 - */ - private SpecialItem() { - - } - - /** - * 获取工具对象 - * - * @return {@link SpecialItem} - */ - public static SpecialItem getInst() { - if (specialItem == null) { - synchronized (SpecialItem.class) { - if (specialItem == null) { - specialItem = new SpecialItem(); - // 注册监听器 - Bukkit.getPluginManager().registerEvents(specialItem, Main.getInst()); - } - } - } - return specialItem; - } - - public boolean isLoaded() { - return isLoaded; - } - - /** - * 注册接口 - * - * @param item 接口对象 - */ - public void register(AbstractSpecialItem item) { - if (contains(item.getName())) { - MsgUtils.warn("特殊物品接口已存在, 检查名称 &4" + item.getName() + " &c是否重复"); - } else { - ITEM_DATA.add(item); - if (isLoaded) { - item.onEnable(); - } - } - } - - /** - * 注销接口 - * - * @param name 注册名称 - */ - public void cancel(String name) { - for (AbstractSpecialItem specialitem : ITEM_DATA) { - if (specialitem.getName() != null && specialitem.getName().equals(specialitem.getName())) { - specialitem.onDisable(); - ITEM_DATA.remove(specialitem); - } - } - } - - /** - * 注销接口 - * - * @param plugin 注册插件 - */ - public void cancel(Plugin plugin) { - for (AbstractSpecialItem specialitem : ITEM_DATA) { - if (specialitem.getPlugin() != null && specialitem.getPlugin().equals(plugin)) { - specialitem.onDisable(); - ITEM_DATA.remove(specialitem); - } - } - } - - /** - * 判断名称是否存在 - * - * @param name 注册名称 - * @return boolean - */ - public boolean contains(String name) { - for (AbstractSpecialItem specialitem : ITEM_DATA) { - if (specialitem.getName().equals(name)) { - return true; - } - } - return false; - } - - /** - * 载入所有已注册接口 - */ - public void loadItems() { - ITEM_DATA.forEach(AbstractSpecialItem::onEnable); - isLoaded = true; - } - - /** - * 注销所有已注册接口 - */ - public void unloadItems() { - ITEM_DATA.forEach(AbstractSpecialItem::onDisable); - ITEM_DATA.clear(); - } - - @EventHandler - public void onDisable(PluginDisableEvent e) { - cancel(e.getPlugin()); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void click(InventoryClickEvent e) { - if (e.isCancelled()) { - return; - } - if (ItemUtils.isNull(e.getCurrentItem()) || ItemUtils.isNull(e.getCursor())) { - return; - } - Player player = (Player) e.getWhoClicked(); - for (AbstractSpecialItem specialItem : ITEM_DATA) { - for (SpecialItemResult result : specialItem.isCorrectClick(player, e.getCurrentItem(), e.getCursor())) { - if (result == null) { - break; - } - switch (result) { - case CANCEL: - e.setCancelled(true); - break; - case BREAK: - return; - case REMOVE_ITEM_CURRENT: - e.setCurrentItem(null); - break; - case REMOVE_ITEM_CURSOR: - e.getWhoClicked().setItemOnCursor(null); - break; - case REMOVE_ITEM_CURRENT_AMOUNT_1: - if (e.getCurrentItem().getAmount() > 1) { - e.getCurrentItem().setAmount(e.getCurrentItem().getAmount() - 1); - } else { - e.setCurrentItem(null); - } - break; - case REMOVE_ITEM_CURSOR_AMOUNT_1: - if (e.getCursor().getAmount() > 1) { - e.getCursor().setAmount(e.getCursor().getAmount() - 1); - } else { - e.getWhoClicked().setItemOnCursor(null); - } - break; - default: - } - } - } - } -} diff --git a/src/main/java/me/skymc/taboolib/inventory/speciaitem/SpecialItemResult.java b/src/main/java/me/skymc/taboolib/inventory/speciaitem/SpecialItemResult.java deleted file mode 100644 index 4e06ae2..0000000 --- a/src/main/java/me/skymc/taboolib/inventory/speciaitem/SpecialItemResult.java +++ /dev/null @@ -1,39 +0,0 @@ -package me.skymc.taboolib.inventory.speciaitem; - -/** - * @author sky - * @since 2018年2月17日 下午8:55:36 - */ -public enum SpecialItemResult { - - /** - * 停止接口检测 - */ - BREAK, - - /** - * 取消点击事件 - */ - CANCEL, - - /** - * 移除点击物品 - */ - REMOVE_ITEM_CURRENT, - - /** - * 移除鼠标物品 - */ - REMOVE_ITEM_CURSOR, - - /** - * 移除一个点击物品 - */ - REMOVE_ITEM_CURRENT_AMOUNT_1, - - /** - * 移除一个鼠标物品 - */ - REMOVE_ITEM_CURSOR_AMOUNT_1 - -} diff --git a/src/main/java/me/skymc/taboolib/itagapi/TagPacket.java b/src/main/java/me/skymc/taboolib/itagapi/TagPacket.java index d4d19f8..ca76c61 100644 --- a/src/main/java/me/skymc/taboolib/itagapi/TagPacket.java +++ b/src/main/java/me/skymc/taboolib/itagapi/TagPacket.java @@ -37,7 +37,7 @@ class TagPacket implements Listener { } public static void inst() { - assert !loaded : "TagAPI is already instanced!"; + Preconditions.checkArgument(!loaded, "TagAPI is already instanced!"); loaded = true; Bukkit.getServer().getOnlinePlayers().forEach(player -> entityIdMap.put(player.getEntityId(), player)); @@ -79,7 +79,6 @@ class TagPacket implements Listener { Preconditions.checkState(Main.getInst().isEnabled(), "Not Enabled!"); Preconditions.checkNotNull(player, "player"); Preconditions.checkNotNull(forWhom, "forWhom"); - if (player != forWhom && player.getWorld() == forWhom.getWorld() && forWhom.canSee(player)) { forWhom.hidePlayer(player); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Main.getInst(), () -> forWhom.showPlayer(player), 2); @@ -90,13 +89,11 @@ class TagPacket implements Listener { Preconditions.checkState(Main.getInst().isEnabled(), "Not Enabled!"); Preconditions.checkNotNull(player, "player"); Preconditions.checkNotNull(forWhom, "forWhom"); - forWhom.forEach(playerFor -> refreshPlayer(player, playerFor)); } private static WrappedGameProfile getSentName(int sentEntityId, WrappedGameProfile sent, Player destinationPlayer) { - Preconditions.checkState(Bukkit.getServer().isPrimaryThread(), "Can only process events on main thread."); - +// Preconditions.checkState(Bukkit.getServer().isPrimaryThread(), "Can only process events on main thread."); Player namedPlayer = entityIdMap.get(sentEntityId); if (namedPlayer == null) { // They probably were dead when we reloaded diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTCompound.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTCompound.java deleted file mode 100644 index d02e435..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTCompound.java +++ /dev/null @@ -1,196 +0,0 @@ -package me.skymc.taboolib.itemnbtapi; - -import me.skymc.taboolib.TabooLib; - -import java.util.Set; - -public class NBTCompound { - - private String compundName; - private NBTCompound parent; - - protected NBTCompound(NBTCompound owner, String name) { - this.compundName = name; - this.parent = owner; - } - - public String getName() { - return compundName; - } - - protected Object getCompound() { - return parent.getCompound(); - } - - protected void setCompound(Object compound) { - parent.setCompound(compound); - } - - public NBTCompound getParent() { - return parent; - } - - public void mergeCompound(NBTCompound comp){ - NBTReflectionUtil.addOtherNBTCompound(this, comp); - } - - public void setString(String key, String value) { - NBTReflectionUtil.setString(this, key, value); - } - - public String getString(String key) { - return NBTReflectionUtil.getString(this, key); - } - - protected String getContent(String key) { - return NBTReflectionUtil.getContent(this, key); - } - - public void setInteger(String key, Integer value) { - NBTReflectionUtil.setInt(this, key, value); - } - - public Integer getInteger(String key) { - return NBTReflectionUtil.getInt(this, key); - } - - public void setDouble(String key, Double value) { - NBTReflectionUtil.setDouble(this, key, value); - } - - public Double getDouble(String key) { - return NBTReflectionUtil.getDouble(this, key); - } - - public void setByte(String key, Byte value) { - NBTReflectionUtil.setByte(this, key, value); - } - - public Byte getByte(String key) { - return NBTReflectionUtil.getByte(this, key); - } - - public void setShort(String key, Short value) { - NBTReflectionUtil.setShort(this, key, value); - } - - public Short getShort(String key) { - return NBTReflectionUtil.getShort(this, key); - } - - public void setLong(String key, Long value) { - NBTReflectionUtil.setLong(this, key, value); - } - - public Long getLong(String key) { - return NBTReflectionUtil.getLong(this, key); - } - - public void setFloat(String key, Float value) { - NBTReflectionUtil.setFloat(this, key, value); - } - - public Float getFloat(String key) { - return NBTReflectionUtil.getFloat(this, key); - } - - public void setByteArray(String key, byte[] value) { - NBTReflectionUtil.setByteArray(this, key, value); - } - - public byte[] getByteArray(String key) { - return NBTReflectionUtil.getByteArray(this, key); - } - - public void setIntArray(String key, int[] value) { - NBTReflectionUtil.setIntArray(this, key, value); - } - - public int[] getIntArray(String key) { - return NBTReflectionUtil.getIntArray(this, key); - } - - public void setBoolean(String key, Boolean value) { - NBTReflectionUtil.setBoolean(this, key, value); - } - - protected void set(String key, Object val) { - NBTReflectionUtil.set(this, key, val); - } - - public Boolean getBoolean(String key) { - return NBTReflectionUtil.getBoolean(this, key); - } - - public void setObject(String key, Object value) { - NBTReflectionUtil.setObject(this, key, value); - } - - public T getObject(String key, Class type) { - return NBTReflectionUtil.getObject(this, key, type); - } - - public Boolean hasKey(String key) { - return NBTReflectionUtil.hasKey(this, key); - } - - public void removeKey(String key) { - NBTReflectionUtil.remove(this, key); - } - - public Set getKeys() { - return NBTReflectionUtil.getKeys(this); - } - - public NBTCompound addCompound(String name) { - NBTReflectionUtil.addNBTTagCompound(this, name); - return getCompound(name); - } - - public NBTCompound getCompound(String name) { - NBTCompound next = new NBTCompound(this, name); - if (NBTReflectionUtil.valideCompound(next)) { - return next; - } - return null; - } - - public NBTList getList(String name, NBTType type) { - return NBTReflectionUtil.getList(this, name, type); - } - - public NBTType getType(String name) { - if (TabooLib.getVerint() == 10700) { - return NBTType.NBTTagEnd; - } - return NBTType.valueOf(NBTReflectionUtil.getType(this, name)); - } - - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - for (String key : getKeys()) { - result.append(toString(key)); - } - return result.toString(); - } - - public String toString(String key) { - StringBuilder result = new StringBuilder(); - NBTCompound compound = this; - while (compound.getParent() != null) { - result.append(" "); - compound = compound.getParent(); - } - if (this.getType(key) == NBTType.NBTTagCompound) { - return this.getCompound(key).toString(); - } else { - return result + "-" + key + ": " + getContent(key) + System.lineSeparator(); - } - } - - public String asNBTString(){ - return getCompound() == null ? "" : getCompound().toString(); - } - -} diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTContainer.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTContainer.java deleted file mode 100644 index 119a0d8..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTContainer.java +++ /dev/null @@ -1,37 +0,0 @@ -package me.skymc.taboolib.itemnbtapi; - -public class NBTContainer extends NBTCompound { - - private Object nbt; - - public NBTContainer() { - super(null, null); - nbt = NBTReflectionUtil.getNewNBTTag(); - } - - protected NBTContainer(Object nbt) { - super(null, null); - this.nbt = nbt; - } - - public NBTContainer(String nbtString) throws IllegalArgumentException { - super(null, null); - try { - nbt = NBTReflectionUtil.parseNBT(nbtString); - } catch (Exception ex) { - ex.printStackTrace(); - throw new IllegalArgumentException("Malformed Json: " + ex.getMessage()); - } - } - - @Override - protected Object getCompound() { - return nbt; - } - - @Override - protected void setCompound(Object tag) { - nbt = tag; - } - -} diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTEntity.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTEntity.java deleted file mode 100644 index 43e4cee..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTEntity.java +++ /dev/null @@ -1,24 +0,0 @@ -package me.skymc.taboolib.itemnbtapi; - -import org.bukkit.entity.Entity; - -public class NBTEntity extends NBTCompound { - - private final Entity ent; - - public NBTEntity(Entity entity) { - super(null, null); - ent = entity; - } - - @Override - protected Object getCompound() { - return NBTReflectionUtil.getEntityNBTTagCompound(NBTReflectionUtil.getNMSEntity(ent)); - } - - @Override - protected void setCompound(Object compound) { - NBTReflectionUtil.setEntityNBTTag(compound, NBTReflectionUtil.getNMSEntity(ent)); - } - -} diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTFile.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTFile.java deleted file mode 100644 index 2bc2faa..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTFile.java +++ /dev/null @@ -1,48 +0,0 @@ -package me.skymc.taboolib.itemnbtapi; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -public class NBTFile extends NBTCompound { - - private final File file; - private Object nbt; - - public NBTFile(File file) throws IOException { - super(null, null); - this.file = file; - if (file.exists()) { - FileInputStream inputsteam = new FileInputStream(file); - nbt = NBTReflectionUtil.readNBTFile(inputsteam); - } else { - nbt = NBTReflectionUtil.getNewNBTTag(); - save(); - } - } - - public void save() throws IOException { - if (!file.exists()) { - file.getParentFile().mkdirs(); - file.createNewFile(); - } - FileOutputStream outStream = new FileOutputStream(file); - NBTReflectionUtil.saveNBTFile(nbt, outStream); - } - - public File getFile() { - return file; - } - - @Override - protected Object getCompound() { - return nbt; - } - - @Override - protected void setCompound(Object compound) { - nbt = compound; - } - -} diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTItem.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTItem.java deleted file mode 100644 index a2ce653..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTItem.java +++ /dev/null @@ -1,40 +0,0 @@ -package me.skymc.taboolib.itemnbtapi; - -import org.bukkit.inventory.ItemStack; - -public class NBTItem extends NBTCompound { - - private ItemStack bukkitItem; - - public NBTItem(ItemStack item) { - super(null, null); - bukkitItem = item.clone(); - } - - public static NBTContainer convertItemtoNBT(ItemStack item) { - return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(item)); - } - - public static ItemStack convertNBTtoItem(NBTCompound comp) { - return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp)); - } - - public ItemStack getItem() { - return bukkitItem; - } - - protected void setItem(ItemStack item) { - bukkitItem = item; - } - - @Override - protected Object getCompound() { - return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem)); - } - - @Override - protected void setCompound(Object compound) { - bukkitItem = NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.setNBTTag(compound, NBTReflectionUtil.getNMSItemStack(bukkitItem))); - } - -} diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTList.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTList.java deleted file mode 100644 index 86f1a8a..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTList.java +++ /dev/null @@ -1,128 +0,0 @@ -package me.skymc.taboolib.itemnbtapi; - -import me.skymc.taboolib.itemnbtapi.utils.MethodNames; -import me.skymc.taboolib.message.MsgUtils; - -import java.lang.reflect.Method; - -public class NBTList { - - private String listName; - private NBTCompound parent; - private NBTType type; - private Object listObject; - - protected NBTList(NBTCompound owner, String name, NBTType type, Object list) { - parent = owner; - listName = name; - this.type = type; - this.listObject = list; - if (!(type == NBTType.NBTTagString || type == NBTType.NBTTagCompound)) { - System.err.println("List types != String/Compound are currently not implemented!"); - } - } - - protected void save() { - parent.set(listName, listObject); - } - - public NBTListCompound addCompound() { - if (type != NBTType.NBTTagCompound) { - new Throwable("Using Compound method on a non Compound list!").printStackTrace(); - return null; - } - try { - Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); - Object compound = NBTReflectionUtil.getNBTTagCompound().newInstance(); - method.invoke(listObject, compound); - return new NBTListCompound(this, compound); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public NBTListCompound getCompound(int id) { - if (type != NBTType.NBTTagCompound) { - new Throwable("Using Compound method on a non Compound list!").printStackTrace(); - return null; - } - try { - Method method = listObject.getClass().getMethod("get", int.class); - Object compound = method.invoke(listObject, id); - return new NBTListCompound(this, compound); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public String getString(int i) { - if (type != NBTType.NBTTagString) { - new Throwable("Using String method on a non String list!").printStackTrace(); - return null; - } - try { - Method method = listObject.getClass().getMethod("getString", int.class); - return (String) method.invoke(listObject, i); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - @SuppressWarnings("unchecked") - public void addString(String s) { - if (type != NBTType.NBTTagString) { - new Throwable("Using String method on a non String list!").printStackTrace(); - return; - } - try { - Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); - method.invoke(listObject, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); - save(); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - @SuppressWarnings("unchecked") - public void setString(int i, String s) { - if (type != NBTType.NBTTagString) { - new Throwable("Using String method on a non String list!").printStackTrace(); - return; - } - try { - Method method = listObject.getClass().getMethod("a", int.class, NBTReflectionUtil.getNBTBase()); - method.invoke(listObject, i, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); - save(); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public void remove(int i) { - try { - Method method = listObject.getClass().getMethod(MethodNames.getRemoveMethodName(), int.class); - method.invoke(listObject, i); - save(); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public int size() { - try { - Method method = listObject.getClass().getMethod("size"); - return (int) method.invoke(listObject); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return -1; - } - - public NBTType getType() { - return type; - } - -} diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTListCompound.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTListCompound.java deleted file mode 100644 index 750f968..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTListCompound.java +++ /dev/null @@ -1,104 +0,0 @@ -package me.skymc.taboolib.itemnbtapi; - -import me.skymc.taboolib.message.MsgUtils; - -import java.util.HashSet; -import java.util.Set; - -public class NBTListCompound { - - private NBTList owner; - private Object compound; - - protected NBTListCompound(NBTList parent, Object obj) { - owner = parent; - compound = obj; - } - - public void setString(String key, String value) { - if (value == null) { - remove(key); - return; - } - try { - compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value); - owner.save(); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public void setInteger(String key, int value) { - try { - compound.getClass().getMethod("setInt", String.class, int.class).invoke(compound, key, value); - owner.save(); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public int getInteger(String value) { - try { - return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return 0; - } - - public void setDouble(String key, double value) { - try { - compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value); - owner.save(); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public double getDouble(String key) { - try { - return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return 0; - } - - - public String getString(String key) { - try { - return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return ""; - } - - public boolean hasKey(String key) { - try { - return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return false; - } - - @SuppressWarnings("unchecked") - public Set getKeys() { - try { - return (Set) compound.getClass().getMethod("c").invoke(compound); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return new HashSet<>(); - } - - public void remove(String key) { - try { - compound.getClass().getMethod("remove", String.class).invoke(compound, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - -} diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTReflectionUtil.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTReflectionUtil.java deleted file mode 100644 index 01fd1ca..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTReflectionUtil.java +++ /dev/null @@ -1,1018 +0,0 @@ -package me.skymc.taboolib.itemnbtapi; - -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.itemnbtapi.utils.GsonWrapper; -import me.skymc.taboolib.itemnbtapi.utils.MethodNames; -import me.skymc.taboolib.message.MsgUtils; -import org.bukkit.Bukkit; -import org.bukkit.block.BlockState; -import org.bukkit.entity.Entity; -import org.bukkit.inventory.ItemStack; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Method; -import java.util.Set; -import java.util.Stack; - -// TODO: finish codestyle cleanup -sgdc3 -public class NBTReflectionUtil { - - private static final String version = TabooLib.getVersion(); - - @SuppressWarnings("rawtypes") - private static Class getCraftItemStack() { - - try { - return Class.forName("org.bukkit.craftbukkit." + version + ".inventory.CraftItemStack"); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - @SuppressWarnings("rawtypes") - private static Class getCraftEntity() { - try { - return Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftEntity"); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - @SuppressWarnings("rawtypes") - protected static Class getNBTBase() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTBase"); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - @SuppressWarnings("rawtypes") - protected static Class getNBTTagString() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTTagString"); - } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - @SuppressWarnings("rawtypes") - protected static Class getNMSItemStack() { - try { - return Class.forName("net.minecraft.server." + version + ".ItemStack"); - } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - @SuppressWarnings("rawtypes") - protected static Class getNBTTagCompound() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); - } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - @SuppressWarnings("rawtypes") - protected static Class getNBTCompressedStreamTools() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTCompressedStreamTools"); - } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - @SuppressWarnings("rawtypes") - protected static Class getMojangsonParser() { - try { - return Class.forName("net.minecraft.server." + version + ".MojangsonParser"); - } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - @SuppressWarnings("rawtypes") - protected static Class getTileEntity() { - try { - return Class.forName("net.minecraft.server." + version + ".TileEntity"); - } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - @SuppressWarnings("rawtypes") - protected static Class getCraftWorld() { - try { - return Class.forName("org.bukkit.craftbukkit." + version + ".CraftWorld"); - } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - public static Object getNewNBTTag() { - String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - try { - @SuppressWarnings("rawtypes") - Class c = Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); - return c.newInstance(); - } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - private static Object getNewBlockPosition(int x, int y, int z) { - String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - try { - @SuppressWarnings("rawtypes") - Class clazz = Class.forName("net.minecraft.server." + version + ".BlockPosition"); - return clazz.getConstructor(int.class, int.class, int.class).newInstance(x, y, z); - } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - - public static Object setNBTTag(Object NBTTag, Object NMSItem) { - try { - Method method; - method = NMSItem.getClass().getMethod("setTag", NBTTag.getClass()); - method.invoke(NMSItem, NBTTag); - return NMSItem; - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - @SuppressWarnings("unchecked") - public static Object getNMSItemStack(ItemStack item) { - @SuppressWarnings("rawtypes") - Class clazz = getCraftItemStack(); - Method method; - try { - method = clazz.getMethod("asNMSCopy", ItemStack.class); - return method.invoke(clazz, item); - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - @SuppressWarnings("unchecked") - public static Object getNMSEntity(Entity entity) { - @SuppressWarnings("rawtypes") - Class clazz = getCraftEntity(); - Method method; - try { - method = clazz.getMethod("getHandle"); - return method.invoke(getCraftEntity().cast(entity)); - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - @SuppressWarnings({"unchecked"}) - public static Object parseNBT(String json) { - @SuppressWarnings("rawtypes") - Class cis = getMojangsonParser(); - java.lang.reflect.Method method; - try { - method = cis.getMethod("parse", String.class); - return method.invoke(null, json); - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - @SuppressWarnings({"unchecked"}) - public static Object readNBTFile(FileInputStream stream) { - @SuppressWarnings("rawtypes") - Class clazz = getNBTCompressedStreamTools(); - Method method; - try { - method = clazz.getMethod("a", InputStream.class); - return method.invoke(clazz, stream); - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - @SuppressWarnings({"unchecked"}) - public static Object saveNBTFile(Object nbt, FileOutputStream stream) { - @SuppressWarnings("rawtypes") - Class clazz = getNBTCompressedStreamTools(); - Method method; - try { - method = clazz.getMethod("a", getNBTTagCompound(), OutputStream.class); - return method.invoke(clazz, nbt, stream); - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - @SuppressWarnings({"unchecked"}) - public static ItemStack getBukkitItemStack(Object item) { - @SuppressWarnings("rawtypes") - Class clazz = getCraftItemStack(); - Method method; - try { - method = clazz.getMethod("asCraftMirror", item.getClass()); - Object answer = method.invoke(clazz, item); - return (ItemStack) answer; - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - @SuppressWarnings({"unchecked"}) - public static Object getItemRootNBTTagCompound(Object nmsitem) { - @SuppressWarnings("rawtypes") - Class clazz = nmsitem.getClass(); - Method method; - try { - method = clazz.getMethod("getTag"); - return method.invoke(nmsitem); - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - @SuppressWarnings({"unchecked"}) - public static Object convertNBTCompoundtoNMSItem(NBTCompound nbtcompound) { - @SuppressWarnings("rawtypes") - Class clazz = getNMSItemStack(); - try { - return clazz.getConstructor(getNBTTagCompound()).newInstance(nbtcompound.getCompound()); - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - @SuppressWarnings({"unchecked"}) - public static NBTContainer convertNMSItemtoNBTCompound(Object nmsitem) { - @SuppressWarnings("rawtypes") - Class clazz = nmsitem.getClass(); - Method method; - try { - method = clazz.getMethod("save", getNBTTagCompound()); - Object answer = method.invoke(nmsitem, getNewNBTTag()); - return new NBTContainer(answer); - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - @SuppressWarnings({"unchecked"}) - public static Object getEntityNBTTagCompound(Object nmsitem) { - @SuppressWarnings("rawtypes") - Class c = nmsitem.getClass(); - Method method; - try { - method = c.getMethod(MethodNames.getEntityNbtGetterMethodName(), getNBTTagCompound()); - Object nbt = getNBTTagCompound().newInstance(); - Object answer = method.invoke(nmsitem, nbt); - if (answer == null) { - answer = nbt; - } - return answer; - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - public static Object setEntityNBTTag(Object NBTTag, Object NMSItem) { - try { - Method method; - method = NMSItem.getClass().getMethod(MethodNames.getEntityNbtSetterMethodName(), getNBTTagCompound()); - method.invoke(NMSItem, NBTTag); - return NMSItem; - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static Object getTileEntityNBTTagCompound(BlockState tile) { - Method method; - try { - Object pos = getNewBlockPosition(tile.getX(), tile.getY(), tile.getZ()); - Object cworld = getCraftWorld().cast(tile.getWorld()); - Object nmsworld = cworld.getClass().getMethod("getHandle").invoke(cworld); - Object o = nmsworld.getClass().getMethod("getTileEntity", pos.getClass()).invoke(nmsworld, pos); - method = getTileEntity().getMethod(MethodNames.getTileDataMethodName(), getNBTTagCompound()); - Object tag = getNBTTagCompound().newInstance(); - Object answer = method.invoke(o, tag); - if (answer == null) { - answer = tag; - } - return answer; - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - public static void setTileEntityNBTTagCompound(BlockState tile, Object comp) { - Method method; - try { - Object pos = getNewBlockPosition(tile.getX(), tile.getY(), tile.getZ()); - Object cworld = getCraftWorld().cast(tile.getWorld()); - Object nmsworld = cworld.getClass().getMethod("getHandle").invoke(cworld); - Object o = nmsworld.getClass().getMethod("getTileEntity", pos.getClass()).invoke(nmsworld, pos); - method = getTileEntity().getMethod("a", getNBTTagCompound()); - method.invoke(o, comp); - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - } - - - @SuppressWarnings("unchecked") - public static Object getSubNBTTagCompound(Object compound, String name) { - @SuppressWarnings("rawtypes") - Class c = compound.getClass(); - Method method; - try { - method = c.getMethod("getCompound", String.class); - return method.invoke(compound, name); - } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); - } - return null; - } - - public static void addNBTTagCompound(NBTCompound comp, String name) { - if (name == null) { - remove(comp, name); - return; - } - Object nbttag = comp.getCompound(); - if (nbttag == null) { - nbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(nbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("set", String.class, getNBTBase()); - method.invoke(workingtag, name, getNBTTagCompound().newInstance()); - comp.setCompound(nbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static Boolean valideCompound(NBTCompound comp) { - Object root = comp.getCompound(); - if (root == null) { - root = getNewNBTTag(); - } - return (gettoCompount(root, comp)) != null; - } - - private static Object gettoCompount(Object nbttag, NBTCompound comp) { - Stack structure = new Stack<>(); - while (comp.getParent() != null) { - structure.add(comp.getName()); - comp = comp.getParent(); - } - while (!structure.isEmpty()) { - nbttag = getSubNBTTagCompound(nbttag, structure.pop()); - if (nbttag == null) { - return null; - } - } - return nbttag; - } - - public static void addOtherNBTCompound(NBTCompound comp, NBTCompound nbtcompound) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("a", getNBTTagCompound()); - method.invoke(workingtag, nbtcompound.getCompound()); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static void setString(NBTCompound comp, String key, String text) { - if (text == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("setString", String.class, String.class); - method.invoke(workingtag, key, text); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static String getString(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("getString", String.class); - return (String) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static String getContent(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("get", String.class); - return method.invoke(workingtag, key).toString(); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static void setInt(NBTCompound comp, String key, Integer i) { - if (i == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("setInt", String.class, int.class); - method.invoke(workingtag, key, i); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static Integer getInt(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("getInt", String.class); - return (Integer) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static void setByteArray(NBTCompound comp, String key, byte[] b) { - if (b == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("setByteArray", String.class, byte[].class); - method.invoke(workingtag, key, b); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static byte[] getByteArray(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("getByteArray", String.class); - return (byte[]) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static void setIntArray(NBTCompound comp, String key, int[] i) { - if (i == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("setIntArray", String.class, int[].class); - method.invoke(workingtag, key, i); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static int[] getIntArray(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("getIntArray", String.class); - return (int[]) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static void setFloat(NBTCompound comp, String key, Float f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("setFloat", String.class, float.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static Float getFloat(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("getFloat", String.class); - return (Float) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static void setLong(NBTCompound comp, String key, Long f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("setLong", String.class, long.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static Long getLong(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("getLong", String.class); - return (Long) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static void setShort(NBTCompound comp, String key, Short f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("setShort", String.class, short.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static Short getShort(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("getShort", String.class); - return (Short) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static void setByte(NBTCompound comp, String key, Byte f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("setByte", String.class, byte.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static Byte getByte(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("getByte", String.class); - return (Byte) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static void setDouble(NBTCompound comp, String key, Double d) { - if (d == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("setDouble", String.class, double.class); - method.invoke(workingtag, key, d); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static Double getDouble(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("getDouble", String.class); - return (Double) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static byte getType(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return 0; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod(MethodNames.getTypeMethodName(), String.class); - return (byte) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return 0; - } - - public static void setBoolean(NBTCompound comp, String key, Boolean d) { - if (d == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("setBoolean", String.class, boolean.class); - method.invoke(workingtag, key, d); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static Boolean getBoolean(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("getBoolean", String.class); - return (Boolean) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static void set(NBTCompound comp, String key, Object val) { - if (val == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - new Throwable("InvalideCompound").printStackTrace(); - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("set", String.class, getNBTBase()); - method.invoke(workingtag, key, val); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static NBTList getList(NBTCompound comp, String key, NBTType type) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("getList", String.class, int.class); - return new NBTList(comp, key, type, method.invoke(workingtag, key, type.getId())); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - public static void setObject(NBTCompound comp, String key, Object value) { - try { - String json = GsonWrapper.getString(value); - setString(comp, key, json); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static T getObject(NBTCompound comp, String key, Class type) { - String json = getString(comp, key); - if (json == null) { - return null; - } - return GsonWrapper.deserializeJson(json, type); - } - - public static void remove(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("remove", String.class); - method.invoke(workingtag, key); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - } - - public static Boolean hasKey(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("hasKey", String.class); - return (Boolean) method.invoke(workingtag, key); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - - @SuppressWarnings("unchecked") - public static Set getKeys(NBTCompound comp) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - return null; - } - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("c"); - return (Set) method.invoke(workingtag); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - } - return null; - } - -} diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTTileEntity.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTTileEntity.java deleted file mode 100644 index 3b25d70..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTTileEntity.java +++ /dev/null @@ -1,24 +0,0 @@ -package me.skymc.taboolib.itemnbtapi; - -import org.bukkit.block.BlockState; - -public class NBTTileEntity extends NBTCompound { - - private final BlockState tile; - - public NBTTileEntity(BlockState tile) { - super(null, null); - this.tile = tile; - } - - @Override - protected Object getCompound() { - return NBTReflectionUtil.getTileEntityNBTTagCompound(tile); - } - - @Override - protected void setCompound(Object compound) { - NBTReflectionUtil.setTileEntityNBTTagCompound(tile, compound); - } - -} diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTType.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTType.java deleted file mode 100644 index 1d3d4e2..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTType.java +++ /dev/null @@ -1,37 +0,0 @@ -package me.skymc.taboolib.itemnbtapi; - -public enum NBTType { - - NBTTagEnd(0), - NBTTagByte(1), - NBTTagShort(2), - NBTTagInt(3), - NBTTagLong(4), - NBTTagFloat(5), - NBTTagDouble(6), - NBTTagByteArray(7), - NBTTagIntArray(11), - NBTTagString(8), - NBTTagList(9), - NBTTagCompound(10); - - NBTType(int i) { - id = i; - } - - private final int id; - - public int getId() { - return id; - } - - public static NBTType valueOf(int id) { - for (NBTType t : values()) { - if (t.getId() == id) { - return t; - } - } - return NBTType.NBTTagEnd; - } - -} diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/utils/GsonWrapper.java b/src/main/java/me/skymc/taboolib/itemnbtapi/utils/GsonWrapper.java deleted file mode 100644 index 581a6d7..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/utils/GsonWrapper.java +++ /dev/null @@ -1,28 +0,0 @@ -package me.skymc.taboolib.itemnbtapi.utils; - -import com.google.gson.Gson; -import me.skymc.taboolib.message.MsgUtils; - -public class GsonWrapper { - - private static final Gson gson = new Gson(); - - public static String getString(Object obj) { - return gson.toJson(obj); - } - - public static T deserializeJson(String json, Class type) { - try { - if (json == null) { - return null; - } - - T obj = gson.fromJson(json, type); - return type.cast(obj); - } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); - return null; - } - } - -} diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/utils/MethodNames.java b/src/main/java/me/skymc/taboolib/itemnbtapi/utils/MethodNames.java deleted file mode 100644 index 7c02ebe..0000000 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/utils/MethodNames.java +++ /dev/null @@ -1,35 +0,0 @@ -package me.skymc.taboolib.itemnbtapi.utils; - -import me.skymc.taboolib.TabooLib; - -public class MethodNames { - - public static String getEntityNbtGetterMethodName() { - return "b"; - } - - public static String getEntityNbtSetterMethodName() { - return "a"; - } - - public static String getTileDataMethodName() { - if (TabooLib.getVerint() <= 10800) { - return "b"; - } - return "save"; - } - - public static String getTypeMethodName() { - if (TabooLib.getVerint() <= 10800) { - return "b"; - } - return "d"; - } - - public static String getRemoveMethodName() { - if (TabooLib.getVerint() <= 10800) { - return "a"; - } - return "remove"; - } -} diff --git a/src/main/java/me/skymc/taboolib/json/CDL.java b/src/main/java/me/skymc/taboolib/json/CDL.java deleted file mode 100644 index 22b7947..0000000 --- a/src/main/java/me/skymc/taboolib/json/CDL.java +++ /dev/null @@ -1,155 +0,0 @@ -package me.skymc.taboolib.json; - -public class CDL { - - private static String getValue(JSONTokener x) throws JSONException { - char c; - char q; - StringBuffer sb; - do { - c = x.next(); - } while (c == ' ' || c == '\t'); - switch (c) { - case 0: - return null; - case '"': - case '\'': - q = c; - sb = new StringBuffer(); - for (; ; ) { - c = x.next(); - if (c == q) { - break; - } - if (c == 0 || c == '\n' || c == '\r') { - throw x.syntaxError("Missing close quote '" + q + "'."); - } - sb.append(c); - } - return sb.toString(); - case ',': - x.back(); - return ""; - default: - x.back(); - return x.nextTo(','); - } - } - - public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { - JSONArray ja = new JSONArray(); - for (; ; ) { - String value = getValue(x); - char c = x.next(); - if (value == null || - (ja.length() == 0 && value.length() == 0 && c != ',')) { - return null; - } - ja.put(value); - while (c != ',') { - if (c != ' ') { - if (c == '\n' || c == '\r' || c == 0) { - return ja; - } - throw x.syntaxError("Bad character '" + c + "' (" + - (int) c + ")."); - } - c = x.next(); - } - } - } - - public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) - throws JSONException { - JSONArray ja = rowToJSONArray(x); - return ja != null ? ja.toJSONObject(names) : null; - } - - public static String rowToString(JSONArray ja) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < ja.length(); i += 1) { - if (i > 0) { - sb.append(','); - } - Object object = ja.opt(i); - if (object != null) { - String string = object.toString(); - if (string.length() > 0 && (string.indexOf(',') >= 0 || - string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || - string.indexOf(0) >= 0 || string.charAt(0) == '"')) { - sb.append('"'); - int length = string.length(); - for (int j = 0; j < length; j += 1) { - char c = string.charAt(j); - if (c >= ' ' && c != '"') { - sb.append(c); - } - } - sb.append('"'); - } else { - sb.append(string); - } - } - } - sb.append('\n'); - return sb.toString(); - } - - public static JSONArray toJSONArray(String string) throws JSONException { - return toJSONArray(new JSONTokener(string)); - } - - public static JSONArray toJSONArray(JSONTokener x) throws JSONException { - return toJSONArray(rowToJSONArray(x), x); - } - - public static JSONArray toJSONArray(JSONArray names, String string) - throws JSONException { - return toJSONArray(names, new JSONTokener(string)); - } - - public static JSONArray toJSONArray(JSONArray names, JSONTokener x) - throws JSONException { - if (names == null || names.length() == 0) { - return null; - } - JSONArray ja = new JSONArray(); - for (; ; ) { - JSONObject jo = rowToJSONObject(names, x); - if (jo == null) { - break; - } - ja.put(jo); - } - if (ja.length() == 0) { - return null; - } - return ja; - } - - public static String toString(JSONArray ja) throws JSONException { - JSONObject jo = ja.optJSONObject(0); - if (jo != null) { - JSONArray names = jo.names(); - if (names != null) { - return rowToString(names) + toString(names, ja); - } - } - return null; - } - - public static String toString(JSONArray names, JSONArray ja) - throws JSONException { - if (names == null || names.length() == 0) { - return null; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < ja.length(); i += 1) { - JSONObject jo = ja.optJSONObject(i); - if (jo != null) { - sb.append(rowToString(jo.toJSONArray(names))); - } - } - return sb.toString(); - } -} diff --git a/src/main/java/me/skymc/taboolib/json/Cookie.java b/src/main/java/me/skymc/taboolib/json/Cookie.java deleted file mode 100644 index d1e014f..0000000 --- a/src/main/java/me/skymc/taboolib/json/Cookie.java +++ /dev/null @@ -1,92 +0,0 @@ -package me.skymc.taboolib.json; - -public class Cookie { - - public static String escape(String string) { - char c; - String s = string.trim(); - StringBuilder sb = new StringBuilder(); - int length = s.length(); - for (int i = 0; i < length; i += 1) { - c = s.charAt(i); - if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { - sb.append('%'); - sb.append(Character.forDigit((char) ((c >>> 4) & 0x0f), 16)); - sb.append(Character.forDigit((char) (c & 0x0f), 16)); - } else { - sb.append(c); - } - } - return sb.toString(); - } - - public static JSONObject toJSONObject(String string) throws JSONException { - String name; - JSONObject jo = new JSONObject(); - Object value; - JSONTokener x = new JSONTokener(string); - jo.put("name", x.nextTo('=')); - x.next('='); - jo.put("value", x.nextTo(';')); - x.next(); - while (x.more()) { - name = unescape(x.nextTo("=;")); - if (x.next() != '=') { - if ("secure".equals(name)) { - value = Boolean.TRUE; - } else { - throw x.syntaxError("Missing '=' in cookie parameter."); - } - } else { - value = unescape(x.nextTo(';')); - x.next(); - } - jo.put(name, value); - } - return jo; - } - - public static String toString(JSONObject jo) throws JSONException { - StringBuilder sb = new StringBuilder(); - - sb.append(escape(jo.getString("name"))); - sb.append("="); - sb.append(escape(jo.getString("value"))); - if (jo.has("expires")) { - sb.append(";expires="); - sb.append(jo.getString("expires")); - } - if (jo.has("domain")) { - sb.append(";domain="); - sb.append(escape(jo.getString("domain"))); - } - if (jo.has("path")) { - sb.append(";path="); - sb.append(escape(jo.getString("path"))); - } - if (jo.optBoolean("secure")) { - sb.append(";secure"); - } - return sb.toString(); - } - - public static String unescape(String string) { - int length = string.length(); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; ++i) { - char c = string.charAt(i); - if (c == '+') { - c = ' '; - } else if (c == '%' && i + 2 < length) { - int d = JSONTokener.dehexchar(string.charAt(i + 1)); - int e = JSONTokener.dehexchar(string.charAt(i + 2)); - if (d >= 0 && e >= 0) { - c = (char) (d * 16 + e); - i += 2; - } - } - sb.append(c); - } - return sb.toString(); - } -} diff --git a/src/main/java/me/skymc/taboolib/json/CookieList.java b/src/main/java/me/skymc/taboolib/json/CookieList.java deleted file mode 100644 index 439ed6f..0000000 --- a/src/main/java/me/skymc/taboolib/json/CookieList.java +++ /dev/null @@ -1,39 +0,0 @@ -package me.skymc.taboolib.json; - -import java.util.Iterator; - -public class CookieList { - - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - JSONTokener x = new JSONTokener(string); - while (x.more()) { - String name = Cookie.unescape(x.nextTo('=')); - x.next('='); - jo.put(name, Cookie.unescape(x.nextTo(';'))); - x.next(); - } - return jo; - } - - @SuppressWarnings("rawtypes") - public static String toString(JSONObject jo) throws JSONException { - boolean b = false; - Iterator keys = jo.keys(); - String string; - StringBuilder sb = new StringBuilder(); - while (keys.hasNext()) { - string = keys.next().toString(); - if (!jo.isNull(string)) { - if (b) { - sb.append(';'); - } - sb.append(Cookie.escape(string)); - sb.append("="); - sb.append(Cookie.escape(jo.getString(string))); - b = true; - } - } - return sb.toString(); - } -} diff --git a/src/main/java/me/skymc/taboolib/json/HTTP.java b/src/main/java/me/skymc/taboolib/json/HTTP.java deleted file mode 100644 index b0b4552..0000000 --- a/src/main/java/me/skymc/taboolib/json/HTTP.java +++ /dev/null @@ -1,71 +0,0 @@ -package me.skymc.taboolib.json; - -import java.util.Iterator; - -public class HTTP { - - public static final String CRLF = "\r\n"; - - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - HTTPTokener x = new HTTPTokener(string); - String token; - - token = x.nextToken(); - if (token.toUpperCase().startsWith("HTTP")) { - jo.put("HTTP-Version", token); - jo.put("Status-Code", x.nextToken()); - jo.put("Reason-Phrase", x.nextTo('\0')); - x.next(); - } else { - jo.put("Method", token); - jo.put("Request-URI", x.nextToken()); - jo.put("HTTP-Version", x.nextToken()); - } - while (x.more()) { - String name = x.nextTo(':'); - x.next(':'); - jo.put(name, x.nextTo('\0')); - x.next(); - } - return jo; - } - - @SuppressWarnings("rawtypes") - public static String toString(JSONObject jo) throws JSONException { - Iterator keys = jo.keys(); - String string; - StringBuilder sb = new StringBuilder(); - if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { - sb.append(jo.getString("HTTP-Version")); - sb.append(' '); - sb.append(jo.getString("Status-Code")); - sb.append(' '); - sb.append(jo.getString("Reason-Phrase")); - } else if (jo.has("Method") && jo.has("Request-URI")) { - sb.append(jo.getString("Method")); - sb.append(' '); - sb.append('"'); - sb.append(jo.getString("Request-URI")); - sb.append('"'); - sb.append(' '); - sb.append(jo.getString("HTTP-Version")); - } else { - throw new JSONException("Not enough material for an HTTP header."); - } - sb.append(CRLF); - while (keys.hasNext()) { - string = keys.next().toString(); - if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && - !"Reason-Phrase".equals(string) && !"Method".equals(string) && - !"Request-URI".equals(string) && !jo.isNull(string)) { - sb.append(string); - sb.append(": "); - sb.append(jo.getString(string)); - sb.append(CRLF); - } - } - sb.append(CRLF); - return sb.toString(); - } -} diff --git a/src/main/java/me/skymc/taboolib/json/HTTPTokener.java b/src/main/java/me/skymc/taboolib/json/HTTPTokener.java deleted file mode 100644 index d04b607..0000000 --- a/src/main/java/me/skymc/taboolib/json/HTTPTokener.java +++ /dev/null @@ -1,37 +0,0 @@ -package me.skymc.taboolib.json; - -public class HTTPTokener extends JSONTokener { - - public HTTPTokener(String string) { - super(string); - } - - public String nextToken() throws JSONException { - char c; - char q; - StringBuilder sb = new StringBuilder(); - do { - c = next(); - } while (Character.isWhitespace(c)); - if (c == '"' || c == '\'') { - q = c; - for (; ; ) { - c = next(); - if (c < ' ') { - throw syntaxError("Unterminated string."); - } - if (c == q) { - return sb.toString(); - } - sb.append(c); - } - } - for (; ; ) { - if (c == 0 || Character.isWhitespace(c)) { - return sb.toString(); - } - sb.append(c); - c = next(); - } - } -} diff --git a/src/main/java/me/skymc/taboolib/json/JSONArray.java b/src/main/java/me/skymc/taboolib/json/JSONArray.java deleted file mode 100644 index 6277d3a..0000000 --- a/src/main/java/me/skymc/taboolib/json/JSONArray.java +++ /dev/null @@ -1,413 +0,0 @@ -package me.skymc.taboolib.json; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; - -@SuppressWarnings({"rawtypes", "unchecked"}) -public class JSONArray { - - private final ArrayList myArrayList; - - public JSONArray() { - this.myArrayList = new ArrayList(); - } - - public JSONArray(JSONTokener x) throws JSONException { - this(); - if (x.nextClean() != '[') { - throw x.syntaxError("A JSONArray text must start with '['"); - } - if (x.nextClean() != ']') { - x.back(); - for (; ; ) { - if (x.nextClean() == ',') { - x.back(); - this.myArrayList.add(JSONObject.NULL); - } else { - x.back(); - this.myArrayList.add(x.nextValue()); - } - switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == ']') { - return; - } - x.back(); - break; - case ']': - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); - } - } - } - } - - public JSONArray(String source) throws JSONException { - this(new JSONTokener(source)); - } - - public JSONArray(Collection collection) { - this.myArrayList = new ArrayList(); - if (collection != null) { - for (Object aCollection : collection) { - this.myArrayList.add(JSONObject.wrap(aCollection)); - } - } - } - - public JSONArray(Object array) throws JSONException { - this(); - if (array.getClass().isArray()) { - int length = Array.getLength(array); - for (int i = 0; i < length; i += 1) { - this.put(JSONObject.wrap(Array.get(array, i))); - } - } else { - throw new JSONException("JSONArray initial value should be a string or collection or array."); - } - } - - public Object get(int index) throws JSONException { - Object object = this.opt(index); - if (object == null) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - return object; - } - - public boolean getBoolean(int index) throws JSONException { - Object object = this.get(index); - if (object.equals(Boolean.FALSE) || - (object instanceof String && - "false".equalsIgnoreCase((String) object))) { - return false; - } else if (object.equals(Boolean.TRUE) || - (object instanceof String && - "true".equalsIgnoreCase((String) object))) { - return true; - } - throw new JSONException("JSONArray[" + index + "] is not a boolean."); - } - - public double getDouble(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number - ? ((Number) object).doubleValue() - : Double.parseDouble((String) object); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + - "] is not a number."); - } - } - - public int getInt(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number - ? ((Number) object).intValue() - : Integer.parseInt((String) object); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + - "] is not a number."); - } - } - - public JSONArray getJSONArray(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof JSONArray) { - return (JSONArray) object; - } - throw new JSONException("JSONArray[" + index + - "] is not a JSONArray."); - } - - public JSONObject getJSONObject(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof JSONObject) { - return (JSONObject) object; - } - throw new JSONException("JSONArray[" + index + - "] is not a JSONObject."); - } - - public long getLong(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number - ? ((Number) object).longValue() - : Long.parseLong((String) object); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + - "] is not a number."); - } - } - - public String getString(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof String) { - return (String) object; - } - throw new JSONException("JSONArray[" + index + "] not a string."); - } - - public boolean isNull(int index) { - return JSONObject.NULL.equals(this.opt(index)); - } - - public String join(String separator) throws JSONException { - int len = this.length(); - StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < len; i += 1) { - if (i > 0) { - sb.append(separator); - } - sb.append(JSONObject.valueToString(this.myArrayList.get(i))); - } - return sb.toString(); - } - - public int length() { - return this.myArrayList.size(); - } - - public Object opt(int index) { - return (index < 0 || index >= this.length()) - ? null - : this.myArrayList.get(index); - } - - public boolean optBoolean(int index) { - return this.optBoolean(index, false); - } - - public boolean optBoolean(int index, boolean defaultValue) { - try { - return this.getBoolean(index); - } catch (Exception e) { - return defaultValue; - } - } - - public double optDouble(int index) { - return this.optDouble(index, Double.NaN); - } - - public double optDouble(int index, double defaultValue) { - try { - return this.getDouble(index); - } catch (Exception e) { - return defaultValue; - } - } - - public int optInt(int index) { - return this.optInt(index, 0); - } - - public int optInt(int index, int defaultValue) { - try { - return this.getInt(index); - } catch (Exception e) { - return defaultValue; - } - } - - public JSONArray optJSONArray(int index) { - Object o = this.opt(index); - return o instanceof JSONArray ? (JSONArray) o : null; - } - - public JSONObject optJSONObject(int index) { - Object o = this.opt(index); - return o instanceof JSONObject ? (JSONObject) o : null; - } - - public long optLong(int index) { - return this.optLong(index, 0); - } - - public long optLong(int index, long defaultValue) { - try { - return this.getLong(index); - } catch (Exception e) { - return defaultValue; - } - } - - public String optString(int index) { - return this.optString(index, ""); - } - - public String optString(int index, String defaultValue) { - Object object = this.opt(index); - return JSONObject.NULL.equals(object) - ? defaultValue : object - .toString(); - } - - public JSONArray put(boolean value) { - this.put(value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - public JSONArray put(Collection value) { - this.put(new JSONArray(value)); - return this; - } - - public JSONArray put(double value) throws JSONException { - Double d = value; - JSONObject.testValidity(d); - this.put(d); - return this; - } - - public JSONArray put(int value) { - this.put(new Integer(value)); - return this; - } - - public JSONArray put(long value) { - this.put(new Long(value)); - return this; - } - - public JSONArray put(Map value) { - this.put(new JSONObject(value)); - return this; - } - - public JSONArray put(Object value) { - this.myArrayList.add(value); - return this; - } - - public JSONArray put(int index, boolean value) throws JSONException { - this.put(index, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - public JSONArray put(int index, Collection value) throws JSONException { - this.put(index, new JSONArray(value)); - return this; - } - - public JSONArray put(int index, double value) throws JSONException { - this.put(index, new Double(value)); - return this; - } - - public JSONArray put(int index, int value) throws JSONException { - this.put(index, new Integer(value)); - return this; - } - - public JSONArray put(int index, long value) throws JSONException { - this.put(index, new Long(value)); - return this; - } - - public JSONArray put(int index, Map value) throws JSONException { - this.put(index, new JSONObject(value)); - return this; - } - - public JSONArray put(int index, Object value) throws JSONException { - JSONObject.testValidity(value); - if (index < 0) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - if (index < this.length()) { - this.myArrayList.set(index, value); - } else { - while (index != this.length()) { - this.put(JSONObject.NULL); - } - this.put(value); - } - return this; - } - - public Object remove(int index) { - Object o = this.opt(index); - this.myArrayList.remove(index); - return o; - } - - public JSONObject toJSONObject(JSONArray names) throws JSONException { - if (names == null || names.length() == 0 || this.length() == 0) { - return null; - } - JSONObject jo = new JSONObject(); - for (int i = 0; i < names.length(); i += 1) { - jo.put(names.getString(i), this.opt(i)); - } - return jo; - } - - @Override - public String toString() { - try { - return '[' + this.join(",") + ']'; - } catch (Exception e) { - return null; - } - } - - public String toString(int indentFactor) throws JSONException { - StringWriter sw = new StringWriter(); - synchronized (sw.getBuffer()) { - return this.write(sw, indentFactor, 0).toString(); - } - } - - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { - try { - boolean commanate = false; - int length = this.length(); - writer.write('['); - - if (length == 1) { - JSONObject.writeValue(writer, this.myArrayList.get(0), - indentFactor, indent); - } else if (length != 0) { - final int newindent = indent + indentFactor; - - for (int i = 0; i < length; i += 1) { - if (commanate) { - writer.write(','); - } - if (indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, newindent); - JSONObject.writeValue(writer, this.myArrayList.get(i), - indentFactor, newindent); - commanate = true; - } - if (indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, indent); - } - writer.write(']'); - return writer; - } catch (IOException e) { - throw new JSONException(e); - } - } -} diff --git a/src/main/java/me/skymc/taboolib/json/JSONException.java b/src/main/java/me/skymc/taboolib/json/JSONException.java deleted file mode 100644 index 5827e53..0000000 --- a/src/main/java/me/skymc/taboolib/json/JSONException.java +++ /dev/null @@ -1,22 +0,0 @@ -package me.skymc.taboolib.json; - - -public class JSONException extends Exception { - - private static final long serialVersionUID = 0; - private Throwable cause; - - public JSONException(String message) { - super(message); - } - - public JSONException(Throwable cause) { - super(cause.getMessage()); - this.cause = cause; - } - - @Override - public Throwable getCause() { - return this.cause; - } -} diff --git a/src/main/java/me/skymc/taboolib/json/JSONML.java b/src/main/java/me/skymc/taboolib/json/JSONML.java deleted file mode 100644 index 2a3ca14..0000000 --- a/src/main/java/me/skymc/taboolib/json/JSONML.java +++ /dev/null @@ -1,310 +0,0 @@ -package me.skymc.taboolib.json; - -import java.util.Iterator; - -@SuppressWarnings({"rawtypes"}) -public class JSONML { - - private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException { - String attribute; - char c; - String closeTag; - int i; - JSONArray newja; - JSONObject newjo; - Object token; - String tagName; - - while (true) { - if (!x.more()) { - throw x.syntaxError("Bad XML"); - } - token = x.nextContent(); - if (token == XML.LT) { - token = x.nextToken(); - if (token instanceof Character) { - if (token == XML.SLASH) { - token = x.nextToken(); - if (!(token instanceof String)) { - throw new JSONException( - "Expected a closing name instead of '" + - token + "'."); - } - if (x.nextToken() != XML.GT) { - throw x.syntaxError("Misshaped close tag"); - } - return token; - } else if (token == XML.BANG) { - c = x.next(); - switch (c) { - case '-': - if (x.next() == '-') { - x.skipPast("-->"); - } else { - x.back(); - } - break; - case '[': - token = x.nextToken(); - if ("CDATA".equals(token) && x.next() == '[') { - if (ja != null) { - ja.put(x.nextCDATA()); - } - } else { - throw x.syntaxError("Expected 'CDATA['"); - } - break; - default: - i = 1; - do { - token = x.nextMeta(); - if (token == null) { - throw x.syntaxError("Missing '>' after ' 0); - break; - } - } else if (token == XML.QUEST) { - x.skipPast("?>"); - } else { - throw x.syntaxError("Misshaped tag"); - } - } else { - if (!(token instanceof String)) { - throw x.syntaxError("Bad tagName '" + token + "'."); - } - tagName = (String) token; - newja = new JSONArray(); - newjo = new JSONObject(); - if (arrayForm) { - newja.put(tagName); - if (ja != null) { - ja.put(newja); - } - } else { - newjo.put("tagName", tagName); - if (ja != null) { - ja.put(newjo); - } - } - token = null; - for (; ; ) { - if (token == null) { - token = x.nextToken(); - } - if (token == null) { - throw x.syntaxError("Misshaped tag"); - } - if (!(token instanceof String)) { - break; - } - attribute = (String) token; - if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { - throw x.syntaxError("Reserved attribute."); - } - token = x.nextToken(); - if (token == XML.EQ) { - token = x.nextToken(); - if (!(token instanceof String)) { - throw x.syntaxError("Missing value"); - } - newjo.accumulate(attribute, XML.stringToValue((String) token)); - token = null; - } else { - newjo.accumulate(attribute, ""); - } - } - if (arrayForm && newjo.length() > 0) { - newja.put(newjo); - } - if (token == XML.SLASH) { - if (x.nextToken() != XML.GT) { - throw x.syntaxError("Misshaped tag"); - } - if (ja == null) { - if (arrayForm) { - return newja; - } else { - return newjo; - } - } - } else { - if (token != XML.GT) { - throw x.syntaxError("Misshaped tag"); - } - closeTag = (String) parse(x, arrayForm, newja); - if (closeTag != null) { - if (!closeTag.equals(tagName)) { - throw x.syntaxError("Mismatched '" + tagName + - "' and '" + closeTag + "'"); - } - if (!arrayForm && newja.length() > 0) { - newjo.put("childNodes", newja); - } - if (ja == null) { - if (arrayForm) { - return newja; - } else { - return newjo; - } - } - } - } - } - } else { - if (ja != null) { - ja.put(token instanceof String - ? XML.stringToValue((String) token) - : token); - } - } - } - } - - public static JSONArray toJSONArray(String string) throws JSONException { - return toJSONArray(new XMLTokener(string)); - } - - public static JSONArray toJSONArray(XMLTokener x) throws JSONException { - return (JSONArray) parse(x, true, null); - } - - public static JSONObject toJSONObject(XMLTokener x) throws JSONException { - return (JSONObject) parse(x, false, null); - } - - public static JSONObject toJSONObject(String string) throws JSONException { - return toJSONObject(new XMLTokener(string)); - } - - public static String toString(JSONArray ja) throws JSONException { - int i; - JSONObject jo; - String key; - Iterator keys; - int length; - Object object; - StringBuilder sb = new StringBuilder(); - String tagName; - String value; - tagName = ja.getString(0); - XML.noSpace(tagName); - tagName = XML.escape(tagName); - sb.append('<'); - sb.append(tagName); - - object = ja.opt(1); - if (object instanceof JSONObject) { - i = 2; - jo = (JSONObject) object; - keys = jo.keys(); - while (keys.hasNext()) { - key = keys.next().toString(); - XML.noSpace(key); - value = jo.optString(key); - if (value != null) { - sb.append(' '); - sb.append(XML.escape(key)); - sb.append('='); - sb.append('"'); - sb.append(XML.escape(value)); - sb.append('"'); - } - } - } else { - i = 1; - } - length = ja.length(); - if (i >= length) { - sb.append('/'); - sb.append('>'); - } else { - sb.append('>'); - do { - object = ja.get(i); - i += 1; - if (object != null) { - if (object instanceof String) { - sb.append(XML.escape(object.toString())); - } else if (object instanceof JSONObject) { - sb.append(toString((JSONObject) object)); - } else if (object instanceof JSONArray) { - sb.append(toString((JSONArray) object)); - } - } - } while (i < length); - sb.append('<'); - sb.append('/'); - sb.append(tagName); - sb.append('>'); - } - return sb.toString(); - } - - public static String toString(JSONObject jo) throws JSONException { - StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - String key; - Iterator keys; - int length; - Object object; - String tagName; - String value; - tagName = jo.optString("tagName"); - if (tagName == null) { - return XML.escape(jo.toString()); - } - XML.noSpace(tagName); - tagName = XML.escape(tagName); - sb.append('<'); - sb.append(tagName); - keys = jo.keys(); - while (keys.hasNext()) { - key = keys.next().toString(); - if (!"tagName".equals(key) && !"childNodes".equals(key)) { - XML.noSpace(key); - value = jo.optString(key); - if (value != null) { - sb.append(' '); - sb.append(XML.escape(key)); - sb.append('='); - sb.append('"'); - sb.append(XML.escape(value)); - sb.append('"'); - } - } - } - ja = jo.optJSONArray("childNodes"); - if (ja == null) { - sb.append('/'); - sb.append('>'); - } else { - sb.append('>'); - length = ja.length(); - for (i = 0; i < length; i += 1) { - object = ja.get(i); - if (object != null) { - if (object instanceof String) { - sb.append(XML.escape(object.toString())); - } else if (object instanceof JSONObject) { - sb.append(toString((JSONObject) object)); - } else if (object instanceof JSONArray) { - sb.append(toString((JSONArray) object)); - } else { - sb.append(object.toString()); - } - } - } - sb.append('<'); - sb.append('/'); - sb.append(tagName); - sb.append('>'); - } - return sb.toString(); - } -} diff --git a/src/main/java/me/skymc/taboolib/json/JSONObject.java b/src/main/java/me/skymc/taboolib/json/JSONObject.java deleted file mode 100644 index f335cf8..0000000 --- a/src/main/java/me/skymc/taboolib/json/JSONObject.java +++ /dev/null @@ -1,872 +0,0 @@ -package me.skymc.taboolib.json; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.*; - -@SuppressWarnings({"rawtypes", "unchecked"}) -public class JSONObject { - - private static final class Null { - - @Override - protected final Object clone() { - return this; - } - - @Override - public boolean equals(Object object) { - return object == null || object == this; - } - - @Override - public String toString() { - return "null"; - } - } - - private final Map map; - - public static final Object NULL = new Null(); - - public JSONObject() { - this.map = new HashMap(); - } - - public JSONObject(JSONObject jo, String[] names) { - this(); - for (String name : names) { - try { - this.putOnce(name, jo.opt(name)); - } catch (Exception ignore) { - } - } - } - - public JSONObject(JSONTokener x) throws JSONException { - this(); - char c; - String key; - - if (x.nextClean() != '{') { - throw x.syntaxError("A JSONObject text must begin with '{'"); - } - for (; ; ) { - c = x.nextClean(); - switch (c) { - case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); - case '}': - return; - default: - x.back(); - key = x.nextValue().toString(); - } - c = x.nextClean(); - if (c == '=') { - if (x.next() != '>') { - x.back(); - } - } else if (c != ':') { - throw x.syntaxError("Expected a ':' after a key"); - } - this.putOnce(key, x.nextValue()); - switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == '}') { - return; - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); - } - } - } - - public JSONObject(Map map) { - this.map = new HashMap(); - if (map != null) { - for (Object o : map.entrySet()) { - Map.Entry e = (Map.Entry) o; - Object value = e.getValue(); - if (value != null) { - this.map.put(e.getKey(), wrap(value)); - } - } - } - } - - public JSONObject(Object bean) { - this(); - this.populateMap(bean); - } - - public JSONObject(Object object, String[] names) { - this(); - Class c = object.getClass(); - for (String name : names) { - try { - this.putOpt(name, c.getField(name).get(object)); - } catch (Exception ignore) { - } - } - } - - public JSONObject(String source) throws JSONException { - this(new JSONTokener(source)); - } - - public JSONObject(String baseName, Locale locale) throws JSONException { - this(); - ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, - Thread.currentThread().getContextClassLoader()); - Enumeration keys = bundle.getKeys(); - while (keys.hasMoreElements()) { - Object key = keys.nextElement(); - if (key instanceof String) { - String[] path = ((String) key).split("\\."); - int last = path.length - 1; - JSONObject target = this; - for (int i = 0; i < last; i += 1) { - String segment = path[i]; - JSONObject nextTarget = target.optJSONObject(segment); - if (nextTarget == null) { - nextTarget = new JSONObject(); - target.put(segment, nextTarget); - } - target = nextTarget; - } - target.put(path[last], bundle.getString((String) key)); - } - } - } - - public void accumulate(String key, Object value) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if (object == null) { - this.put(key, value instanceof JSONArray - ? new JSONArray().put(value) - : value); - } else if (object instanceof JSONArray) { - ((JSONArray) object).put(value); - } else { - this.put(key, new JSONArray().put(object).put(value)); - } - } - - public JSONObject append(String key, Object value) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if (object == null) { - this.put(key, new JSONArray().put(value)); - } else if (object instanceof JSONArray) { - this.put(key, ((JSONArray) object).put(value)); - } else { - throw new JSONException("JSONObject[" + key + - "] is not a JSONArray."); - } - return this; - } - - public static String doubleToString(double d) { - if (Double.isInfinite(d) || Double.isNaN(d)) { - return "null"; - } - String string = Double.toString(d); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && - string.indexOf('E') < 0) { - while (string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if (string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - public Object get(String key) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - Object object = this.opt(key); - if (object == null) { - throw new JSONException("JSONObject[" + quote(key) + - "] not found."); - } - return object; - } - - public boolean getBoolean(String key) throws JSONException { - Object object = this.get(key); - if (object.equals(Boolean.FALSE) || - (object instanceof String && - "false".equalsIgnoreCase((String) object))) { - return false; - } else if (object.equals(Boolean.TRUE) || - (object instanceof String && - "true".equalsIgnoreCase((String) object))) { - return true; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a Boolean."); - } - - public double getDouble(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number - ? ((Number) object).doubleValue() - : Double.parseDouble((String) object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) + - "] is not a number."); - } - } - - public int getInt(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number - ? ((Number) object).intValue() - : Integer.parseInt((String) object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) + - "] is not an int."); - } - } - - public JSONArray getJSONArray(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof JSONArray) { - return (JSONArray) object; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a JSONArray."); - } - - public JSONObject getJSONObject(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof JSONObject) { - return (JSONObject) object; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a JSONObject."); - } - - public long getLong(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number - ? ((Number) object).longValue() - : Long.parseLong((String) object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) + - "] is not a long."); - } - } - - public static String[] getNames(JSONObject jo) { - int length = jo.length(); - if (length == 0) { - return null; - } - Iterator iterator = jo.keys(); - String[] names = new String[length]; - int i = 0; - while (iterator.hasNext()) { - names[i] = (String) iterator.next(); - i += 1; - } - return names; - } - - public static String[] getNames(Object object) { - if (object == null) { - return null; - } - Class klass = object.getClass(); - Field[] fields = klass.getFields(); - int length = fields.length; - if (length == 0) { - return null; - } - String[] names = new String[length]; - for (int i = 0; i < length; i += 1) { - names[i] = fields[i].getName(); - } - return names; - } - - public String getString(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof String) { - return (String) object; - } - throw new JSONException("JSONObject[" + quote(key) + - "] not a string."); - } - - public boolean has(String key) { - return this.map.containsKey(key); - } - - public static Object stringToValue(String string) { - Double d; - if ("".equals(string)) { - return string; - } - if ("true".equalsIgnoreCase(string)) { - return Boolean.TRUE; - } - if ("false".equalsIgnoreCase(string)) { - return Boolean.FALSE; - } - if ("null".equalsIgnoreCase(string)) { - return JSONObject.NULL; - } - char b = string.charAt(0); - if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { - try { - if (string.indexOf('.') > -1 || - string.indexOf('e') > -1 || string.indexOf('E') > -1) { - d = Double.valueOf(string); - if (!d.isInfinite() && !d.isNaN()) { - return d; - } - } else { - Long myLong = new Long(string); - if (myLong == myLong.intValue()) { - return myLong.intValue(); - } else { - return myLong; - } - } - } catch (Exception ignore) { - } - } - return string; - } - - public boolean isNull(String key) { - return JSONObject.NULL.equals(this.opt(key)); - } - - public Iterator keys() { - return this.map.keySet().iterator(); - } - - public int length() { - return this.map.size(); - } - - public JSONArray names() { - JSONArray ja = new JSONArray(); - Iterator keys = this.keys(); - while (keys.hasNext()) { - ja.put(keys.next()); - } - return ja.length() == 0 ? null : ja; - } - - public static String numberToString(Number number) - throws JSONException { - if (number == null) { - throw new JSONException("Null pointer"); - } - testValidity(number); - String string = number.toString(); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && - string.indexOf('E') < 0) { - while (string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if (string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - public Object opt(String key) { - return key == null ? null : this.map.get(key); - } - - public boolean optBoolean(String key) { - return this.optBoolean(key, false); - } - - public boolean optBoolean(String key, boolean defaultValue) { - try { - return this.getBoolean(key); - } catch (Exception e) { - return defaultValue; - } - } - - public double optDouble(String key) { - return this.optDouble(key, Double.NaN); - } - - public double optDouble(String key, double defaultValue) { - try { - return this.getDouble(key); - } catch (Exception e) { - return defaultValue; - } - } - - public int optInt(String key) { - return this.optInt(key, 0); - } - - public int optInt(String key, int defaultValue) { - try { - return this.getInt(key); - } catch (Exception e) { - return defaultValue; - } - } - - public JSONArray optJSONArray(String key) { - Object o = this.opt(key); - return o instanceof JSONArray ? (JSONArray) o : null; - } - - public JSONObject optJSONObject(String key) { - Object object = this.opt(key); - return object instanceof JSONObject ? (JSONObject) object : null; - } - - public long optLong(String key) { - return this.optLong(key, 0); - } - - public long optLong(String key, long defaultValue) { - try { - return this.getLong(key); - } catch (Exception e) { - return defaultValue; - } - } - - public String optString(String key) { - return this.optString(key, ""); - } - - public String optString(String key, String defaultValue) { - Object object = this.opt(key); - return NULL.equals(object) ? defaultValue : object.toString(); - } - - public static String valueToString(Object value) throws JSONException { - if (value == null || value == null) { - return "null"; - } - if (value instanceof JSONString) { - Object object; - try { - object = ((JSONString) value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - if (object != null) { - return (String) object; - } - throw new JSONException("Bad value from toJSONString: " + object); - } - if (value instanceof Number) { - return numberToString((Number) value); - } - if (value instanceof Boolean || value instanceof JSONObject || - value instanceof JSONArray) { - return value.toString(); - } - if (value instanceof Map) { - return new JSONObject((Map) value).toString(); - } - if (value instanceof Collection) { - return new JSONArray((Collection) value).toString(); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(); - } - return quote(value.toString()); - } - - public JSONObject put(String key, boolean value) throws JSONException { - this.put(key, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - public JSONObject put(String key, Collection value) throws JSONException { - this.put(key, new JSONArray(value)); - return this; - } - - public JSONObject put(String key, double value) throws JSONException { - this.put(key, new Double(value)); - return this; - } - - public JSONObject put(String key, int value) throws JSONException { - this.put(key, new Integer(value)); - return this; - } - - public JSONObject put(String key, long value) throws JSONException { - this.put(key, new Long(value)); - return this; - } - - public JSONObject put(String key, Map value) throws JSONException { - this.put(key, new JSONObject(value)); - return this; - } - - public JSONObject put(String key, Object value) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - if (value != null) { - testValidity(value); - this.map.put(key, value); - } else { - this.remove(key); - } - return this; - } - - public JSONObject putOnce(String key, Object value) throws JSONException { - if (key != null && value != null) { - if (this.opt(key) != null) { - throw new JSONException("Duplicate key \"" + key + "\""); - } - this.put(key, value); - } - return this; - } - - public JSONObject putOpt(String key, Object value) throws JSONException { - if (key != null && value != null) { - this.put(key, value); - } - return this; - } - - public static String quote(String string) { - StringWriter sw = new StringWriter(); - synchronized (sw.getBuffer()) { - try { - return quote(string, sw).toString(); - } catch (IOException ignored) { - return ""; - } - } - } - - public static Writer quote(String string, Writer w) throws IOException { - if (string == null || string.length() == 0) { - w.write("\"\""); - return w; - } - - char b; - char c = 0; - String hhhh; - int i; - int len = string.length(); - - w.write('"'); - for (i = 0; i < len; i += 1) { - b = c; - c = string.charAt(i); - switch (c) { - case '\\': - case '"': - w.write('\\'); - w.write(c); - break; - case '/': - if (b == '<') { - w.write('\\'); - } - w.write(c); - break; - case '\b': - w.write("\\b"); - break; - case '\t': - w.write("\\t"); - break; - case '\n': - w.write("\\n"); - break; - case '\f': - w.write("\\f"); - break; - case '\r': - w.write("\\r"); - break; - default: - if (c < ' ' || (c >= '\u0080' && c < '\u00a0') - || (c >= '\u2000' && c < '\u2100')) { - hhhh = "000" + Integer.toHexString(c); - w.write("\\u" + hhhh.substring(hhhh.length() - 4)); - } else { - w.write(c); - } - } - } - w.write('"'); - return w; - } - - public Object remove(String key) { - return this.map.remove(key); - } - - static void writeValue(Writer writer, Object value, int indentFactor, int indent) throws JSONException, IOException { - if (value == null) { - writer.write("null"); - } else if (value instanceof JSONObject) { - ((JSONObject) value).write(writer, indentFactor, indent); - } else if (value instanceof JSONArray) { - ((JSONArray) value).write(writer, indentFactor, indent); - } else if (value instanceof Map) { - new JSONObject((Map) value).write(writer, indentFactor, indent); - } else if (value instanceof Collection) { - new JSONArray((Collection) value).write(writer, indentFactor, - indent); - } else if (value.getClass().isArray()) { - new JSONArray(value).write(writer, indentFactor, indent); - } else if (value instanceof Number) { - writer.write(numberToString((Number) value)); - } else if (value instanceof Boolean) { - writer.write(value.toString()); - } else if (value instanceof JSONString) { - Object o; - try { - o = ((JSONString) value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - writer.write(o != null ? o.toString() : quote(value.toString())); - } else { - quote(value.toString(), writer); - } - } - - public static void testValidity(Object o) throws JSONException { - if (o != null) { - if (o instanceof Double) { - if (((Double) o).isInfinite() || ((Double) o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); - } - } else if (o instanceof Float) { - if (((Float) o).isInfinite() || ((Float) o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); - } - } - } - } - - public JSONArray toJSONArray(JSONArray names) throws JSONException { - if (names == null || names.length() == 0) { - return null; - } - JSONArray ja = new JSONArray(); - for (int i = 0; i < names.length(); i += 1) { - ja.put(this.opt(names.getString(i))); - } - return ja; - } - - @Override - public String toString() { - try { - return this.toString(0); - } catch (Exception e) { - return null; - } - } - - public String toString(int indentFactor) throws JSONException { - StringWriter w = new StringWriter(); - synchronized (w.getBuffer()) { - return this.write(w, indentFactor, 0).toString(); - } - } - - static void indent(Writer writer, int indent) throws IOException { - for (int i = 0; i < indent; i += 1) { - writer.write(' '); - } - } - - public static Object wrap(Object object) { - try { - if (object == null) { - return NULL; - } - if (object instanceof JSONObject || object instanceof JSONArray || - NULL.equals(object) || object instanceof JSONString || - object instanceof Byte || object instanceof Character || - object instanceof Short || object instanceof Integer || - object instanceof Long || object instanceof Boolean || - object instanceof Float || object instanceof Double || - object instanceof String || object instanceof Enum) { - return object; - } - - if (object instanceof Collection) { - return new JSONArray((Collection) object); - } - if (object.getClass().isArray()) { - return new JSONArray(object); - } - if (object instanceof Map) { - return new JSONObject((Map) object); - } - Package objectPackage = object.getClass().getPackage(); - String objectPackageName = objectPackage != null - ? objectPackage.getName() - : ""; - if ( - objectPackageName.startsWith("java.") || - objectPackageName.startsWith("javax.") || - object.getClass().getClassLoader() == null - ) { - return object.toString(); - } - return new JSONObject(object); - } catch (Exception exception) { - return null; - } - } - - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - public JSONObject increment(String key) throws JSONException { - Object value = this.opt(key); - if (value == null) { - this.put(key, 1); - } else if (value instanceof Integer) { - this.put(key, (Integer) value + 1); - } else if (value instanceof Long) { - this.put(key, (Long) value + 1); - } else if (value instanceof Double) { - this.put(key, (Double) value + 1); - } else if (value instanceof Float) { - this.put(key, (Float) value + 1); - } else { - throw new JSONException("Unable to increment [" + quote(key) + "]."); - } - return this; - } - - private void populateMap(Object bean) { - Class klass = bean.getClass(); - boolean includeSuperClass = klass.getClassLoader() != null; - - Method[] methods = includeSuperClass - ? klass.getMethods() - : klass.getDeclaredMethods(); - for (Method method1 : methods) { - try { - Method method = method1; - if (Modifier.isPublic(method.getModifiers())) { - String name = method.getName(); - String key = ""; - if (name.startsWith("get")) { - if ("getClass".equals(name) || - "getDeclaringClass".equals(name)) { - key = ""; - } else { - key = name.substring(3); - } - } else if (name.startsWith("is")) { - key = name.substring(2); - } - if (key.length() > 0 && - Character.isUpperCase(key.charAt(0)) && - method.getParameterTypes().length == 0) { - if (key.length() == 1) { - key = key.toLowerCase(); - } else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase() + - key.substring(1); - } - - Object result = method.invoke(bean, (Object[]) null); - if (result != null) { - this.map.put(key, wrap(result)); - } - } - } - } catch (Exception ignore) { - } - } - } - - Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { - try { - boolean commanate = false; - final int length = this.length(); - Iterator keys = this.keys(); - writer.write('{'); - - if (length == 1) { - Object key = keys.next(); - writer.write(quote(key.toString())); - writer.write(':'); - if (indentFactor > 0) { - writer.write(' '); - } - writeValue(writer, this.map.get(key), indentFactor, indent); - } else if (length != 0) { - final int newindent = indent + indentFactor; - while (keys.hasNext()) { - Object key = keys.next(); - if (commanate) { - writer.write(','); - } - if (indentFactor > 0) { - writer.write('\n'); - } - indent(writer, newindent); - writer.write(quote(key.toString())); - writer.write(':'); - if (indentFactor > 0) { - writer.write(' '); - } - writeValue(writer, this.map.get(key), indentFactor, - newindent); - commanate = true; - } - if (indentFactor > 0) { - writer.write('\n'); - } - indent(writer, indent); - } - writer.write('}'); - return writer; - } catch (IOException exception) { - throw new JSONException(exception); - } - } -} diff --git a/src/main/java/me/skymc/taboolib/json/JSONReader.java b/src/main/java/me/skymc/taboolib/json/JSONReader.java deleted file mode 100644 index 393cdd0..0000000 --- a/src/main/java/me/skymc/taboolib/json/JSONReader.java +++ /dev/null @@ -1,50 +0,0 @@ -package me.skymc.taboolib.json; - -import java.util.regex.Pattern; - -/** - * @Author sky - * @Since 2018-07-01 11:10 - */ -public class JSONReader { - - private static Pattern pattern = Pattern.compile("[\t\n]"); - - public static String formatJson(String content) { - StringBuilder builder = new StringBuilder(); - int index = 0; - int count = 0; - while (index < content.length()) { - char ch = content.charAt(index); - if (ch == '{' || ch == '[') { - builder.append(ch); - builder.append('\n'); - count++; - for (int i = 0; i < count; i++) { - builder.append('\t'); - } - } else if (ch == '}' || ch == ']') { - builder.append('\n'); - count--; - for (int i = 0; i < count; i++) { - builder.append('\t'); - } - builder.append(ch); - } else if (ch == ',') { - builder.append(ch); - builder.append('\n'); - for (int i = 0; i < count; i++) { - builder.append('\t'); - } - } else { - builder.append(ch); - } - index++; - } - return compactJson(builder.toString()); - } - - private static String compactJson(String content) { - return pattern.matcher(content).replaceAll("").trim(); - } -} diff --git a/src/main/java/me/skymc/taboolib/json/JSONString.java b/src/main/java/me/skymc/taboolib/json/JSONString.java deleted file mode 100644 index c7842f6..0000000 --- a/src/main/java/me/skymc/taboolib/json/JSONString.java +++ /dev/null @@ -1,6 +0,0 @@ -package me.skymc.taboolib.json; - -public interface JSONString { - - String toJSONString(); -} diff --git a/src/main/java/me/skymc/taboolib/json/JSONStringer.java b/src/main/java/me/skymc/taboolib/json/JSONStringer.java deleted file mode 100644 index dddfca5..0000000 --- a/src/main/java/me/skymc/taboolib/json/JSONStringer.java +++ /dev/null @@ -1,15 +0,0 @@ -package me.skymc.taboolib.json; - -import java.io.StringWriter; - -public class JSONStringer extends JSONWriter { - - public JSONStringer() { - super(new StringWriter()); - } - - @Override - public String toString() { - return this.mode == 'd' ? this.writer.toString() : null; - } -} diff --git a/src/main/java/me/skymc/taboolib/json/JSONTokener.java b/src/main/java/me/skymc/taboolib/json/JSONTokener.java deleted file mode 100644 index d659a66..0000000 --- a/src/main/java/me/skymc/taboolib/json/JSONTokener.java +++ /dev/null @@ -1,283 +0,0 @@ -package me.skymc.taboolib.json; - - -import java.io.*; - -public class JSONTokener { - - private long character; - private boolean eof; - private long index; - private long line; - private char previous; - private Reader reader; - private boolean usePrevious; - - public JSONTokener(Reader reader) { - this.reader = reader.markSupported() - ? reader - : new BufferedReader(reader); - this.eof = false; - this.usePrevious = false; - this.previous = 0; - this.index = 0; - this.character = 1; - this.line = 1; - } - - public JSONTokener(InputStream inputStream) { - this(new InputStreamReader(inputStream)); - } - - public JSONTokener(String s) { - this(new StringReader(s)); - } - - public void back() throws JSONException { - if (this.usePrevious || this.index <= 0) { - throw new JSONException("Stepping back two steps is not supported"); - } - this.index -= 1; - this.character -= 1; - this.usePrevious = true; - this.eof = false; - } - - public static int dehexchar(char c) { - if (c >= '0' && c <= '9') { - return c - '0'; - } - if (c >= 'A' && c <= 'F') { - return c - ('A' - 10); - } - if (c >= 'a' && c <= 'f') { - return c - ('a' - 10); - } - return -1; - } - - public boolean end() { - return this.eof && !this.usePrevious; - } - - public boolean more() throws JSONException { - this.next(); - if (this.end()) { - return false; - } - this.back(); - return true; - } - - public char next() throws JSONException { - int c; - if (this.usePrevious) { - this.usePrevious = false; - c = this.previous; - } else { - try { - c = this.reader.read(); - } catch (IOException exception) { - throw new JSONException(exception); - } - - if (c <= 0) { - this.eof = true; - c = 0; - } - } - this.index += 1; - if (this.previous == '\r') { - this.line += 1; - this.character = c == '\n' ? 0 : 1; - } else if (c == '\n') { - this.line += 1; - this.character = 0; - } else { - this.character += 1; - } - this.previous = (char) c; - return this.previous; - } - - public char next(char c) throws JSONException { - char n = this.next(); - if (n != c) { - throw this.syntaxError("Expected '" + c + "' and instead saw '" + - n + "'"); - } - return n; - } - - public String next(int n) throws JSONException { - if (n == 0) { - return ""; - } - - char[] chars = new char[n]; - int pos = 0; - - while (pos < n) { - chars[pos] = this.next(); - if (this.end()) { - throw this.syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(chars); - } - - public char nextClean() throws JSONException { - for (; ; ) { - char c = this.next(); - if (c == 0 || c > ' ') { - return c; - } - } - } - - public String nextString(char quote) throws JSONException { - char c; - StringBuilder sb = new StringBuilder(); - for (; ; ) { - c = this.next(); - switch (c) { - case 0: - case '\n': - case '\r': - throw this.syntaxError("Unterminated string"); - case '\\': - c = this.next(); - switch (c) { - case 'b': - sb.append('\b'); - break; - case 't': - sb.append('\t'); - break; - case 'n': - sb.append('\n'); - break; - case 'f': - sb.append('\f'); - break; - case 'r': - sb.append('\r'); - break; - case 'u': - sb.append((char) Integer.parseInt(this.next(4), 16)); - break; - case '"': - case '\'': - case '\\': - case '/': - sb.append(c); - break; - default: - throw this.syntaxError("Illegal escape."); - } - break; - default: - if (c == quote) { - return sb.toString(); - } - sb.append(c); - } - } - } - - public String nextTo(char delimiter) throws JSONException { - StringBuilder sb = new StringBuilder(); - for (; ; ) { - char c = this.next(); - if (c == delimiter || c == 0 || c == '\n' || c == '\r') { - if (c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - public String nextTo(String delimiters) throws JSONException { - char c; - StringBuilder sb = new StringBuilder(); - for (; ; ) { - c = this.next(); - if (delimiters.indexOf(c) >= 0 || c == 0 || - c == '\n' || c == '\r') { - if (c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - public Object nextValue() throws JSONException { - char c = this.nextClean(); - String string; - - switch (c) { - case '"': - case '\'': - return this.nextString(c); - case '{': - this.back(); - return new JSONObject(this); - case '[': - this.back(); - return new JSONArray(this); - } - - StringBuilder sb = new StringBuilder(); - while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { - sb.append(c); - c = this.next(); - } - this.back(); - - string = sb.toString().trim(); - if ("".equals(string)) { - throw this.syntaxError("Missing value"); - } - return JSONObject.stringToValue(string); - } - - public char skipTo(char to) throws JSONException { - char c; - try { - long startIndex = this.index; - long startCharacter = this.character; - long startLine = this.line; - this.reader.mark(1000000); - do { - c = this.next(); - if (c == 0) { - this.reader.reset(); - this.index = startIndex; - this.character = startCharacter; - this.line = startLine; - return c; - } - } while (c != to); - } catch (IOException exc) { - throw new JSONException(exc); - } - - this.back(); - return c; - } - - public JSONException syntaxError(String message) { - return new JSONException(message + this.toString()); - } - - @Override - public String toString() { - return " at " + this.index + " [character " + this.character + " line " + - this.line + "]"; - } -} diff --git a/src/main/java/me/skymc/taboolib/json/JSONWriter.java b/src/main/java/me/skymc/taboolib/json/JSONWriter.java deleted file mode 100644 index 399056d..0000000 --- a/src/main/java/me/skymc/taboolib/json/JSONWriter.java +++ /dev/null @@ -1,160 +0,0 @@ -package me.skymc.taboolib.json; - -import java.io.IOException; -import java.io.Writer; - -public class JSONWriter { - - private static final int maxdepth = 200; - - private boolean comma; - - protected char mode; - - private final JSONObject[] stack; - - private int top; - - protected Writer writer; - - public JSONWriter(Writer w) { - this.comma = false; - this.mode = 'i'; - this.stack = new JSONObject[maxdepth]; - this.top = 0; - this.writer = w; - } - - private JSONWriter append(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null pointer"); - } - if (this.mode == 'o' || this.mode == 'a') { - try { - if (this.comma && this.mode == 'a') { - this.writer.write(','); - } - this.writer.write(string); - } catch (IOException e) { - throw new JSONException(e); - } - if (this.mode == 'o') { - this.mode = 'k'; - } - this.comma = true; - return this; - } - throw new JSONException("Value out of sequence."); - } - - public JSONWriter array() throws JSONException { - if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { - this.push(null); - this.append("["); - this.comma = false; - return this; - } - throw new JSONException("Misplaced array."); - } - - private JSONWriter end(char mode, char c) throws JSONException { - if (this.mode != mode) { - throw new JSONException(mode == 'a' - ? "Misplaced endArray." - : "Misplaced endObject."); - } - this.pop(mode); - try { - this.writer.write(c); - } catch (IOException e) { - throw new JSONException(e); - } - this.comma = true; - return this; - } - - public JSONWriter endArray() throws JSONException { - return this.end('a', ']'); - } - - public JSONWriter endObject() throws JSONException { - return this.end('k', '}'); - } - - public JSONWriter key(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null key."); - } - if (this.mode == 'k') { - try { - this.stack[this.top - 1].putOnce(string, Boolean.TRUE); - if (this.comma) { - this.writer.write(','); - } - this.writer.write(JSONObject.quote(string)); - this.writer.write(':'); - this.comma = false; - this.mode = 'o'; - return this; - } catch (IOException e) { - throw new JSONException(e); - } - } - throw new JSONException("Misplaced key."); - } - - public JSONWriter object() throws JSONException { - if (this.mode == 'i') { - this.mode = 'o'; - } - if (this.mode == 'o' || this.mode == 'a') { - this.append("{"); - this.push(new JSONObject()); - this.comma = false; - return this; - } - throw new JSONException("Misplaced object."); - - } - - private void pop(char c) throws JSONException { - if (this.top <= 0) { - throw new JSONException("Nesting error."); - } - char m = this.stack[this.top - 1] == null ? 'a' : 'k'; - if (m != c) { - throw new JSONException("Nesting error."); - } - this.top -= 1; - this.mode = this.top == 0 - ? 'd' - : this.stack[this.top - 1] == null - ? 'a' - : 'k'; - } - - private void push(JSONObject jo) throws JSONException { - if (this.top >= maxdepth) { - throw new JSONException("Nesting too deep."); - } - this.stack[this.top] = jo; - this.mode = jo == null ? 'a' : 'k'; - this.top += 1; - } - - public JSONWriter value(boolean b) throws JSONException { - return this.append(b ? "true" : "false"); - } - - public JSONWriter value(double d) throws JSONException { - return this.value(new Double(d)); - } - - public JSONWriter value(long l) throws JSONException { - return this.append(Long.toString(l)); - } - - public JSONWriter value(Object object) throws JSONException { - return this.append(JSONObject.valueToString(object)); - } -} diff --git a/src/main/java/me/skymc/taboolib/json/XML.java b/src/main/java/me/skymc/taboolib/json/XML.java deleted file mode 100644 index 6d98271..0000000 --- a/src/main/java/me/skymc/taboolib/json/XML.java +++ /dev/null @@ -1,338 +0,0 @@ -package me.skymc.taboolib.json; - - -import java.util.Iterator; - -@SuppressWarnings({"rawtypes"}) -public class XML { - - public static final Character AMP = '&'; - - public static final Character APOS = '\''; - - public static final Character BANG = '!'; - - public static final Character EQ = '='; - - public static final Character GT = '>'; - - public static final Character LT = '<'; - - public static final Character QUEST = '?'; - - public static final Character QUOT = '"'; - - public static final Character SLASH = '/'; - - public static String escape(String string) { - StringBuilder sb = new StringBuilder(); - for (int i = 0, length = string.length(); i < length; i++) { - char c = string.charAt(i); - switch (c) { - case '&': - sb.append("&"); - break; - case '<': - sb.append("<"); - break; - case '>': - sb.append(">"); - break; - case '"': - sb.append("""); - break; - case '\'': - sb.append("'"); - break; - default: - sb.append(c); - } - } - return sb.toString(); - } - - public static void noSpace(String string) throws JSONException { - int i, length = string.length(); - if (length == 0) { - throw new JSONException("Empty string."); - } - for (i = 0; i < length; i += 1) { - if (Character.isWhitespace(string.charAt(i))) { - throw new JSONException("'" + string + - "' contains a space character."); - } - } - } - - private static boolean parse(XMLTokener x, JSONObject context, - String name) throws JSONException { - char c; - int i; - JSONObject jsonobject = null; - String string; - String tagName; - Object token; - token = x.nextToken(); - if (token == BANG) { - c = x.next(); - if (c == '-') { - if (x.next() == '-') { - x.skipPast("-->"); - return false; - } - x.back(); - } else if (c == '[') { - token = x.nextToken(); - if ("CDATA".equals(token)) { - if (x.next() == '[') { - string = x.nextCDATA(); - if (string.length() > 0) { - context.accumulate("content", string); - } - return false; - } - } - throw x.syntaxError("Expected 'CDATA['"); - } - i = 1; - do { - token = x.nextMeta(); - if (token == null) { - throw x.syntaxError("Missing '>' after ' 0); - return false; - } else if (token == QUEST) { - x.skipPast("?>"); - return false; - } else if (token == SLASH) { - token = x.nextToken(); - if (name == null) { - throw x.syntaxError("Mismatched close tag " + token); - } - if (!token.equals(name)) { - throw x.syntaxError("Mismatched " + name + " and " + token); - } - if (x.nextToken() != GT) { - throw x.syntaxError("Misshaped close tag"); - } - return true; - - } else if (token instanceof Character) { - throw x.syntaxError("Misshaped tag"); - } else { - tagName = (String) token; - token = null; - jsonobject = new JSONObject(); - for (; ; ) { - if (token == null) { - token = x.nextToken(); - } - if (token instanceof String) { - string = (String) token; - token = x.nextToken(); - if (token == EQ) { - token = x.nextToken(); - if (!(token instanceof String)) { - throw x.syntaxError("Missing value"); - } - jsonobject.accumulate(string, - XML.stringToValue((String) token)); - token = null; - } else { - jsonobject.accumulate(string, ""); - } - } else if (token == SLASH) { - if (x.nextToken() != GT) { - throw x.syntaxError("Misshaped tag"); - } - if (jsonobject.length() > 0) { - context.accumulate(tagName, jsonobject); - } else { - context.accumulate(tagName, ""); - } - return false; - } else if (token == GT) { - for (; ; ) { - token = x.nextContent(); - if (token == null) { - if (tagName != null) { - throw x.syntaxError("Unclosed tag " + tagName); - } - return false; - } else if (token instanceof String) { - string = (String) token; - if (string.length() > 0) { - jsonobject.accumulate("content", - XML.stringToValue(string)); - } - } else if (token == LT) { - if (parse(x, jsonobject, tagName)) { - if (jsonobject.length() == 0) { - context.accumulate(tagName, ""); - } else if (jsonobject.length() == 1 && - jsonobject.opt("content") != null) { - context.accumulate(tagName, - jsonobject.opt("content")); - } else { - context.accumulate(tagName, jsonobject); - } - return false; - } - } - } - } else { - throw x.syntaxError("Misshaped tag"); - } - } - } - } - - public static Object stringToValue(String string) { - if ("".equals(string)) { - return string; - } - if ("true".equalsIgnoreCase(string)) { - return Boolean.TRUE; - } - if ("false".equalsIgnoreCase(string)) { - return Boolean.FALSE; - } - if ("null".equalsIgnoreCase(string)) { - return JSONObject.NULL; - } - if ("0".equals(string)) { - return 0; - } - try { - char initial = string.charAt(0); - boolean negative = false; - if (initial == '-') { - initial = string.charAt(1); - negative = true; - } - if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') { - return string; - } - if ((initial >= '0' && initial <= '9')) { - if (string.indexOf('.') >= 0) { - return Double.valueOf(string); - } else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) { - Long myLong = new Long(string); - if (myLong == myLong.intValue()) { - return myLong.intValue(); - } else { - return myLong; - } - } - } - } catch (Exception ignore) { - } - return string; - } - - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - XMLTokener x = new XMLTokener(string); - while (x.more() && x.skipPast("<")) { - parse(x, jo, null); - } - return jo; - } - - public static String toString(Object object) throws JSONException { - return toString(object, null); - } - - public static String toString(Object object, String tagName) throws JSONException { - StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - JSONObject jo; - String key; - Iterator keys; - int length; - String string; - Object value; - if (object instanceof JSONObject) { - if (tagName != null) { - sb.append('<'); - sb.append(tagName); - sb.append('>'); - } - jo = (JSONObject) object; - keys = jo.keys(); - while (keys.hasNext()) { - key = keys.next().toString(); - value = jo.opt(key); - if (value == null) { - value = ""; - } - if ("content".equals(key)) { - if (value instanceof JSONArray) { - ja = (JSONArray) value; - length = ja.length(); - for (i = 0; i < length; i += 1) { - if (i > 0) { - sb.append('\n'); - } - sb.append(escape(ja.get(i).toString())); - } - } else { - sb.append(escape(value.toString())); - } - } else if (value instanceof JSONArray) { - ja = (JSONArray) value; - length = ja.length(); - for (i = 0; i < length; i += 1) { - value = ja.get(i); - if (value instanceof JSONArray) { - sb.append('<'); - sb.append(key); - sb.append('>'); - sb.append(toString(value)); - sb.append("'); - } else { - sb.append(toString(value, key)); - } - } - } else if ("".equals(value)) { - sb.append('<'); - sb.append(key); - sb.append("/>"); - } else { - sb.append(toString(value, key)); - } - } - if (tagName != null) { - sb.append("'); - } - return sb.toString(); - } else { - if (object.getClass().isArray()) { - object = new JSONArray(object); - } - if (object instanceof JSONArray) { - ja = (JSONArray) object; - length = ja.length(); - for (i = 0; i < length; i += 1) { - sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); - } - return sb.toString(); - } else { - string = escape(object.toString()); - return (tagName == null) ? "\"" + string + "\"" : - (string.length() == 0) ? "<" + tagName + "/>" : - "<" + tagName + ">" + string + ""; - } - } - } -} \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/json/XMLTokener.java b/src/main/java/me/skymc/taboolib/json/XMLTokener.java deleted file mode 100644 index c242bd0..0000000 --- a/src/main/java/me/skymc/taboolib/json/XMLTokener.java +++ /dev/null @@ -1,252 +0,0 @@ -package me.skymc.taboolib.json; - -@SuppressWarnings({"rawtypes", "unchecked"}) -public class XMLTokener extends JSONTokener { - - public static final java.util.HashMap entity; - - static { - entity = new java.util.HashMap(8); - entity.put("amp", XML.AMP); - entity.put("apos", XML.APOS); - entity.put("gt", XML.GT); - entity.put("lt", XML.LT); - entity.put("quot", XML.QUOT); - } - - public XMLTokener(String s) { - super(s); - } - - public String nextCDATA() throws JSONException { - char c; - int i; - StringBuilder sb = new StringBuilder(); - for (; ; ) { - c = next(); - if (end()) { - throw syntaxError("Unclosed CDATA"); - } - sb.append(c); - i = sb.length() - 3; - if (i >= 0 && sb.charAt(i) == ']' && - sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { - sb.setLength(i); - return sb.toString(); - } - } - } - - public Object nextContent() throws JSONException { - char c; - StringBuffer sb; - do { - c = next(); - } while (Character.isWhitespace(c)); - if (c == 0) { - return null; - } - if (c == '<') { - return XML.LT; - } - sb = new StringBuffer(); - for (; ; ) { - if (c == '<' || c == 0) { - back(); - return sb.toString().trim(); - } - if (c == '&') { - sb.append(nextEntity(c)); - } else { - sb.append(c); - } - c = next(); - } - } - - public Object nextEntity(char ampersand) throws JSONException { - StringBuilder sb = new StringBuilder(); - for (; ; ) { - char c = next(); - if (Character.isLetterOrDigit(c) || c == '#') { - sb.append(Character.toLowerCase(c)); - } else if (c == ';') { - break; - } else { - throw syntaxError("Missing ';' in XML entity: &" + sb); - } - } - String string = sb.toString(); - Object object = entity.get(string); - return object != null ? object : ampersand + string + ";"; - } - - public Object nextMeta() throws JSONException { - char c; - char q; - do { - c = next(); - } while (Character.isWhitespace(c)); - switch (c) { - case 0: - throw syntaxError("Misshaped meta tag"); - case '<': - return XML.LT; - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - case '"': - case '\'': - q = c; - for (; ; ) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); - } - if (c == q) { - return Boolean.TRUE; - } - } - default: - for (; ; ) { - c = next(); - if (Character.isWhitespace(c)) { - return Boolean.TRUE; - } - switch (c) { - case 0: - case '<': - case '>': - case '/': - case '=': - case '!': - case '?': - case '"': - case '\'': - back(); - return Boolean.TRUE; - } - } - } - } - - public Object nextToken() throws JSONException { - char c; - char q; - StringBuffer sb; - do { - c = next(); - } while (Character.isWhitespace(c)); - switch (c) { - case 0: - throw syntaxError("Misshaped element"); - case '<': - throw syntaxError("Misplaced '<'"); - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - case '"': - case '\'': - q = c; - sb = new StringBuffer(); - for (; ; ) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); - } - if (c == q) { - return sb.toString(); - } - if (c == '&') { - sb.append(nextEntity(c)); - } else { - sb.append(c); - } - } - default: - sb = new StringBuffer(); - for (; ; ) { - sb.append(c); - c = next(); - if (Character.isWhitespace(c)) { - return sb.toString(); - } - switch (c) { - case 0: - return sb.toString(); - case '>': - case '/': - case '=': - case '!': - case '?': - case '[': - case ']': - back(); - return sb.toString(); - case '<': - case '"': - case '\'': - throw syntaxError("Bad character in a name"); - } - } - } - } - - public boolean skipPast(String to) throws JSONException { - boolean b; - char c; - int i; - int j; - int offset = 0; - int length = to.length(); - char[] circle = new char[length]; - - for (i = 0; i < length; i += 1) { - c = next(); - if (c == 0) { - return false; - } - circle[i] = c; - } - for (; ; ) { - j = offset; - b = true; - for (i = 0; i < length; i += 1) { - if (circle[j] != to.charAt(i)) { - b = false; - break; - } - j += 1; - if (j >= length) { - j -= length; - } - } - if (b) { - return true; - } - c = next(); - if (c == 0) { - return false; - } - circle[offset] = c; - offset += 1; - if (offset >= length) { - offset -= length; - } - } - } -} diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java b/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java deleted file mode 100644 index 6ac0c21..0000000 --- a/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java +++ /dev/null @@ -1,465 +0,0 @@ -package me.skymc.taboolib.jsonformatter; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.json.JSONArray; -import me.skymc.taboolib.json.JSONObject; -import me.skymc.taboolib.jsonformatter.click.ClickEvent; -import me.skymc.taboolib.jsonformatter.hover.HoverEvent; -import me.skymc.taboolib.nms.NMSUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Unknown - */ -@Deprecated -public class JSONFormatter { - - public static void sendRawMessage(Player player, String message) { - TLocale.Tellraw.send(player, message); - } - - private JSONArray ja = new JSONArray(); - private Builder builder = new Builder(); - private String color = ""; - private List all = new ArrayList<>(); - private boolean newline = true; - - public JSONFormatter() { - } - - public JSONFormatter(boolean newline) { - this.newline = newline; - } - - public JSONFormatter append(JSONFormatter json) { - if (json.ja.length() == 0) { - return this; - } - try { - if (newline && json.newline) { - all.addAll(json.all); - } - for (int i = 0; i < json.ja.length(); i++) { - add(json.ja.get(i)); - } - } catch (Exception e) { - e.printStackTrace(); - } - return this; - } - - public int getSize() { - if (newline) { - return 1; - } - return all.size() + 1; - } - - public JSONFormatter newLine() { - if (newline) { - append("\n"); - } else { - all.add(ja); - ja = new JSONArray(); - } - resetAll(); - return this; - } - - public JSONFormatter newLine(int amount) { - for (int i = 0; i < amount; i++) { - newLine(); - } - return this; - } - - public void clear() { - ja = new JSONArray(); - builder = new Builder(); - color = ""; - } - - public JSONFormatter resetAll() { - return resetColors().resetModifiers(); - } - - public JSONFormatter resetColors() { - color = ""; - return this; - } - - public JSONFormatter resetModifiers() { - builder = new Builder(); - return this; - } - - public String toJSON() { - JSONObject jo = new JSONObject(); - try { - if (ja.length() > 0) { - jo.put("extra", ja); - } - jo.put("text", ""); - } catch (Exception e) { - e.printStackTrace(); - } - return jo.toString(); - } - - public List toJSONList() { - List list = new ArrayList<>(); - try { - for (JSONArray ja : all) { - JSONObject jo = new JSONObject(); - if (ja.length() > 0) { - jo.put("extra", ja); - } - jo.put("text", ""); - list.add(jo.toString()); - } - JSONObject jo = new JSONObject(); - if (ja.length() > 0) { - jo.put("extra", ja); - } - jo.put("text", ""); - list.add(jo.toString()); - return list; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public Object toSerialized() { - try { - return a.invoke(null, toJSON()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public List toSerializedList() { - List list = new ArrayList<>(); - try { - for (String s : toJSONList()) { - list.add(a.invoke(null, s)); - } - return list; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public JSONFormatter send(Player player) { - JSONFormatter.send(player, this); - return this; - } - - private void add(Object jo) { - if (ja == null) { - ja = new JSONArray(); - } - if (jo != null) { - ja.put(jo); - } - } - - private JSONFormatter append(String text, BuilderMaker bm) { - builder = new Builder(builder); - for (int i = 0; i < text.length(); i++) { - char c = text.charAt(i); - switch (c) { - case '§': { - if ((i + 1) == text.length()) { - builder.append(c); - continue; - } - ChatColor cc = ChatColor.getByChar(text.charAt(i + 1)); - if (cc == null) { - builder.append(c); - break; - } - add(bm.make()); - switch (cc) { - case BOLD: - builder = new Builder(builder); - builder.bold = true; - break; - case ITALIC: - builder = new Builder(builder); - builder.italic = true; - break; - case MAGIC: - builder = new Builder(builder); - builder.magic = true; - break; - case RESET: - builder = new Builder(); - color = ""; - break; - case STRIKETHROUGH: - builder = new Builder(builder); - builder.strikethrough = true; - break; - case UNDERLINE: - builder = new Builder(builder); - builder.underline = true; - break; - default: { - builder = new Builder(); - color = cc.name().toLowerCase(); - break; - } - } - i++; - break; - } - default: { - builder.append(c); - } - } - } - add(bm.make()); - return this; - } - - public JSONFormatter append(String text) { - return append(text, new BuilderMaker() { - @Override - public JSONObject make() { - return builder.toString(color); - } - }); - } - - public JSONFormatter appendHover(String text, final HoverEvent hevent) { - return append(text, new BuilderMaker() { - @Override - public JSONObject make() { - return builder.toStringHover(color, hevent); - } - }); - } - - public JSONFormatter appendClick(String text, final ClickEvent cevent) { - return append(text, new BuilderMaker() { - @Override - public JSONObject make() { - return builder.toStringClick(color, cevent); - } - }); - } - - public JSONFormatter appendHoverClick(String text, final HoverEvent hevent, final ClickEvent cevent) { - return append(text, new BuilderMaker() { - @Override - public JSONObject make() { - return builder.toStringHoverClick(color, hevent, cevent); - } - }); - } - - public Object getPacket() { - try { - return ppocc.newInstance(toSerialized()); - } catch (Exception ignored) { - } - return null; - } - - public List getPacketList() { - List list = new ArrayList<>(); - try { - for (Object o : toSerializedList()) { - list.add(ppocc.newInstance(o)); - } - return list; - } catch (Exception ignored) { - } - return null; - } - - private static Class cs = NMSUtils.getNMSClassSilent("ChatSerializer", "IChatBaseComponent"); - private static Class icbc = NMSUtils.getNMSClassSilent("IChatBaseComponent"); - private static Class ppoc = NMSUtils.getNMSClassSilent("PacketPlayOutChat"); - private static Class pc = NMSUtils.getNMSClassSilent("PlayerConnection"); - private static Class p = NMSUtils.getNMSClassSilent("Packet"); - private static Class ep = NMSUtils.getNMSClassSilent("EntityPlayer"); - private static Method a = NMSUtils.getMethodSilent(cs, "a", String.class), sp = NMSUtils.getMethodSilent(pc, "sendPacket", p); - private static Field ppc = NMSUtils.getFieldSilent(ep, "playerConnection"); - private static Constructor ppocc = NMSUtils.getConstructorSilent(ppoc, icbc); - private static boolean b = check(cs, icbc, ppoc, pc, p, ep, a, sp, ppc, ppocc); - - private static boolean check(Object... o) { - for (Object a : o) { - if (a == null) { - return false; - } - } - return true; - } - - private static void send(Player player, JSONFormatter jf) { - if (!jf.newline) { - send1(player, jf); - } else if (b) { - try { - Object entityplayer = NMSUtils.getHandle(player); - Object ppco = ppc.get(entityplayer); - sp.invoke(ppco, jf.getPacket()); - } catch (Exception e) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON()); - } - } else { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON()); - } - } - - private static void send1(Player player, JSONFormatter jf) { - if (b) { - try { - Object entityplayer = NMSUtils.getHandle(player); - Object ppco = ppc.get(entityplayer); - List packets = jf.getPacketList(); - List jsons = null; - for (int i = 0; i < packets.size(); i++) { - try { - sp.invoke(ppco, packets.get(i)); - } catch (Exception e) { - if (jsons == null) { - jsons = jf.toJSONList(); - } - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jsons.get(i)); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } else { - for (String json : jf.toJSONList()) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + json); - } - } - } - - private class Builder { - - private StringBuilder sb = new StringBuilder(); - private boolean bold = false, italic = false, magic = false, strikethrough = false, underline = false, changed = false; - - public Builder() { - } - - public Builder(Builder b) { - bold = b.bold; - italic = b.italic; - magic = b.magic; - strikethrough = b.strikethrough; - underline = b.underline; - } - - public void append(char c) { - sb.append(c); - changed = true; - } - - private JSONObject toString(String color, BuilderHelper bh) { - String string = sb.toString(); - if (!changed) { - return null; - } - if (string.length() == 0) { - return null; - } - JSONObject jo = new JSONObject(); - try { - if (!"".equals(color)) { - jo.put("color", color); - } - if (bold) { - jo.put("bold", true); - } - if (italic) { - jo.put("italic", true); - } - if (magic) { - jo.put("obfuscated", true); - } - if (strikethrough) { - jo.put("strikethrough", true); - } - if (underline) { - jo.put("underlined", true); - } - bh.add(jo); - jo.put("text", string); - } catch (Exception e) { - e.printStackTrace(); - } - return jo; - } - - public JSONObject toString(String color) { - return toString(color, new BuilderHelper() { - @Override - public void add(JSONObject jo) { - } - }); - } - - public JSONObject toStringHover(String color, final HoverEvent event) { - return toString(color, new BuilderHelper() { - @Override - public void add(JSONObject jo) throws Exception { - if (event.getEvent().length() > 1) { - jo.put("hoverEvent", event.getEvent()); - } - } - }); - } - - public JSONObject toStringClick(String color, final ClickEvent event) { - return toString(color, new BuilderHelper() { - @Override - public void add(JSONObject jo) throws Exception { - if (event.getEvent().length() > 1) { - jo.put("clickEvent", event.getEvent()); - } - } - }); - } - - public JSONObject toStringHoverClick(String color, final HoverEvent hevent, final ClickEvent cevent) { - return toString(color, new BuilderHelper() { - @Override - public void add(JSONObject jo) throws Exception { - if (hevent.getEvent().length() > 1) { - jo.put("hoverEvent", hevent.getEvent()); - } - if (cevent.getEvent().length() > 1) { - jo.put("clickEvent", cevent.getEvent()); - } - } - }); - } - - } - - private abstract class BuilderMaker { - public abstract JSONObject make(); - } - - private abstract class BuilderHelper { - public abstract void add(JSONObject jo) throws Exception; - } -} diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/click/ClickEvent.java b/src/main/java/me/skymc/taboolib/jsonformatter/click/ClickEvent.java deleted file mode 100644 index 6ec1f8a..0000000 --- a/src/main/java/me/skymc/taboolib/jsonformatter/click/ClickEvent.java +++ /dev/null @@ -1,9 +0,0 @@ -package me.skymc.taboolib.jsonformatter.click; - -import me.skymc.taboolib.json.JSONObject; - -public abstract class ClickEvent{ - - public abstract JSONObject getEvent(); - -} diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/click/OpenUrlEvent.java b/src/main/java/me/skymc/taboolib/jsonformatter/click/OpenUrlEvent.java deleted file mode 100644 index 8ab37a4..0000000 --- a/src/main/java/me/skymc/taboolib/jsonformatter/click/OpenUrlEvent.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.skymc.taboolib.jsonformatter.click; - -import me.skymc.taboolib.json.JSONObject; - -public class OpenUrlEvent extends ClickEvent{ - - private JSONObject object = new JSONObject(); - - public OpenUrlEvent(String suggest){ - try{ - object.put("action", "open_url"); - object.put("value", suggest); - }catch(Exception e){ - e.printStackTrace(); - } - } - - @Override - public JSONObject getEvent(){ - return object; - } - -} diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/click/RunCommandEvent.java b/src/main/java/me/skymc/taboolib/jsonformatter/click/RunCommandEvent.java deleted file mode 100644 index 7494750..0000000 --- a/src/main/java/me/skymc/taboolib/jsonformatter/click/RunCommandEvent.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.skymc.taboolib.jsonformatter.click; - -import me.skymc.taboolib.json.JSONObject; - -public class RunCommandEvent extends ClickEvent{ - - private JSONObject object = new JSONObject(); - - public RunCommandEvent(String command){ - try{ - object.put("action", "run_command"); - object.put("value", command); - }catch(Exception e){ - e.printStackTrace(); - } - } - - @Override - public JSONObject getEvent(){ - return object; - } - -} diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/click/SuggestCommandEvent.java b/src/main/java/me/skymc/taboolib/jsonformatter/click/SuggestCommandEvent.java deleted file mode 100644 index 01496df..0000000 --- a/src/main/java/me/skymc/taboolib/jsonformatter/click/SuggestCommandEvent.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.skymc.taboolib.jsonformatter.click; - -import me.skymc.taboolib.json.JSONObject; - -public class SuggestCommandEvent extends ClickEvent{ - - private JSONObject object = new JSONObject(); - - public SuggestCommandEvent(String suggest){ - try{ - object.put("action", "suggest_command"); - object.put("value", suggest); - }catch(Exception e){ - e.printStackTrace(); - } - } - - @Override - public JSONObject getEvent(){ - return object; - } - -} diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/hover/HoverEvent.java b/src/main/java/me/skymc/taboolib/jsonformatter/hover/HoverEvent.java deleted file mode 100644 index 24f4c1d..0000000 --- a/src/main/java/me/skymc/taboolib/jsonformatter/hover/HoverEvent.java +++ /dev/null @@ -1,9 +0,0 @@ -package me.skymc.taboolib.jsonformatter.hover; - -import me.skymc.taboolib.json.JSONObject; - -public abstract class HoverEvent{ - - public abstract JSONObject getEvent(); - -} diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowAchievementEvent.java b/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowAchievementEvent.java deleted file mode 100644 index 58c3c20..0000000 --- a/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowAchievementEvent.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.skymc.taboolib.jsonformatter.hover; - -import me.skymc.taboolib.json.JSONObject; - -public class ShowAchievementEvent extends HoverEvent{ - - private JSONObject object = new JSONObject(); - - public ShowAchievementEvent(String achievement){ - try{ - object.put("action", "show_achievement"); - object.put("value", achievement); - }catch(Exception e){ - e.printStackTrace(); - } - } - - @Override - public JSONObject getEvent(){ - return object; - } - -} diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowItemEvent.java b/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowItemEvent.java deleted file mode 100644 index 54e02a5..0000000 --- a/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowItemEvent.java +++ /dev/null @@ -1,81 +0,0 @@ -package me.skymc.taboolib.jsonformatter.hover; - -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.json.JSONObject; -import me.skymc.taboolib.json.tellraw.TellrawJson; -import me.skymc.taboolib.nms.item.DabItemUtils; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -public class ShowItemEvent extends HoverEvent { - - private JSONObject object = new JSONObject(); - - public Object getItemTag(ItemStack item) { - try { - return DabItemUtils.getInstance().getTag(DabItemUtils.getInstance().getNMSCopy(item)); - } catch (Exception e) { - return null; - } - } - - @SuppressWarnings("deprecation") - public ShowItemEvent(ItemStack is) { - if (TabooLib.getVerint() > 10700) { - try { - object.put("action", "show_item"); - object.put("value", TellrawJson.create().getItemComponent(is)); - } catch (Exception ignored) { - } - } - try { - object.put("action", "show_item"); - StringBuilder tag = new StringBuilder(); - Object itemTag = getItemTag(is); - if (itemTag != null) { - tag.append(",tag:").append(itemTag); - } else { - ItemMeta im = is.getItemMeta(); - List lore = im.hasLore() ? im.getLore() : new ArrayList<>(); - Map enchants = is.getItemMeta().getEnchants(); - tag.append(",tag:{display:{Name:").append(enchants.size() > 0 ? "§b§o" : "§f").append(ItemUtils.getCustomName(is)); - if (lore.size() > 0) { - tag.append(",Lore:["); - for (String s : lore) { - tag.append("\"").append(s).append("\","); - } - tag.delete(tag.length() - 1, tag.length()); - tag.append("]"); - } - tag.append("}"); - if (enchants.size() > 0) { - if (tag.length() > 6) { - tag.append(","); - } - tag.append("ench:["); - for (Entry e : enchants.entrySet()) { - tag.append("{id:").append(e.getKey().getId()).append(",lvl:").append(e.getValue()).append("},"); - } - tag.delete(tag.length() - 1, tag.length()); - tag.append("]"); - } - tag.append("}"); - } - object.put("value", "{id:" + (TabooLib.getVerint() > 10700 ? DabItemUtils.getMinecraftName(is) : is.getTypeId()) + ",Count:" + is.getAmount() + tag.toString() + "}"); - } catch (Exception ignored) { - } - } - - @Override - public JSONObject getEvent() { - return object; - } - -} diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowTextEvent.java b/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowTextEvent.java deleted file mode 100644 index 7bd316f..0000000 --- a/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowTextEvent.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.skymc.taboolib.jsonformatter.hover; - -import me.skymc.taboolib.json.JSONObject; - -public class ShowTextEvent extends HoverEvent{ - - private JSONObject object = new JSONObject(); - - public ShowTextEvent(String text){ - try{ - object.put("action", "show_text"); - object.put("value", text); - }catch(Exception e){ - e.printStackTrace(); - } - } - - @Override - public JSONObject getEvent(){ - return object; - } - -} diff --git a/src/main/java/me/skymc/taboolib/location/LocationUtils.java b/src/main/java/me/skymc/taboolib/location/LocationUtils.java deleted file mode 100644 index 23dc1be..0000000 --- a/src/main/java/me/skymc/taboolib/location/LocationUtils.java +++ /dev/null @@ -1,66 +0,0 @@ -package me.skymc.taboolib.location; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; - -public class LocationUtils { - - /** - * 序列化 - * - * @param location - * @return - */ - public static String fromString(Location location) { - return location.getWorld().getName() + "," + location.getX() + "," + location.getY() + "," + location.getZ() + "," + location.getYaw() + "," + location.getPitch(); - } - - /** - * 反序列化 - * - * @param string - * @return - */ - public static Location toString(String string) { - Location location = new Location(null, 0, 0, 0); - try { - location.setWorld(Bukkit.getWorld(string.split(",")[0])); - location.setX(Double.valueOf(string.split(",")[1])); - location.setY(Double.valueOf(string.split(",")[2])); - location.setZ(Double.valueOf(string.split(",")[3])); - location.setYaw(Float.valueOf(string.split(",")[4])); - location.setPitch(Float.valueOf(string.split(",")[5])); - } catch (Exception e) { - // TODO: handle exception - } - return location; - } - - public static double getBetween(Location l1, Location l2) { - if (l1.getWorld().equals(l2.getWorld())) { - return Math.ceil(l1.distance(l2)); - } - return -1D; - } - - @Deprecated - public static Block findBlockByLocation(Location l) { - while (l.getY() < 255 && l.getBlock().getType() != Material.AIR) { - l.add(0, 1, 0); - } - return l.getY() < 255 && l.getBlock().getType() == Material.AIR ? l.getBlock() : null; - } - - @Deprecated - public static String formatToString(Location l) { - return l.getWorld().getName() + "," + String.valueOf(l.getX()).replace(".", "#") + "," + String.valueOf(l.getY()).replace(".", "#") + "," + String.valueOf(l.getZ()).replace(".", "#"); - } - - @Deprecated - public static Location parsedToLocation(String string) { - String[] values = string.split(","); - return new Location(Bukkit.getWorld(values[0]), Double.valueOf(values[1].replace("#", ".")), Double.valueOf(values[2].replace("#", ".")), Double.valueOf(values[3].replace("#", "."))); - } -} diff --git a/src/main/java/me/skymc/taboolib/message/ChatCatcher.java b/src/main/java/me/skymc/taboolib/message/ChatCatcher.java deleted file mode 100644 index c0fd373..0000000 --- a/src/main/java/me/skymc/taboolib/message/ChatCatcher.java +++ /dev/null @@ -1,77 +0,0 @@ -package me.skymc.taboolib.message; - -import me.skymc.taboolib.listener.TListener; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.PlayerQuitEvent; - -import java.util.HashMap; -import java.util.LinkedList; - -@TListener -public class ChatCatcher implements Listener { - - private static HashMap> playerdata = new HashMap<>(); - - public static HashMap> getPlayerdata() { - return playerdata; - } - - public static boolean contains(Player player) { - return playerdata.containsKey(player.getName()) && playerdata.get(player.getName()).size() > 0; - } - - public static void call(Player player, Catcher catcher) { - if (!playerdata.containsKey(player.getName())) { - playerdata.put(player.getName(), new LinkedList<>()); - } - playerdata.get(player.getName()).add(catcher.before()); - } - - @EventHandler - public void quit(PlayerQuitEvent e) { - playerdata.remove(e.getPlayer().getName()); - } - - @EventHandler - public void chat(AsyncPlayerChatEvent e) { - if (playerdata.containsKey(e.getPlayer().getName()) && playerdata.get(e.getPlayer().getName()).size() > 0) { - e.setCancelled(true); - - if ("quit()".equalsIgnoreCase(e.getMessage())) { - // 退出引导 - playerdata.get(e.getPlayer().getName()).removeFirst().cancel(); - // 清理数据 - clearData(e.getPlayer()); - } else { - Catcher catcher = playerdata.get(e.getPlayer().getName()).getFirst(); - // 如果终止引导 - if (!catcher.after(e.getMessage())) { - // 移除 - playerdata.get(e.getPlayer().getName()).removeFirst(); - // 清理 - clearData(e.getPlayer()); - } else { - catcher.before(); - } - } - } - } - - private void clearData(Player player) { - if (playerdata.containsKey(player.getName()) && playerdata.get(player.getName()).size() == 0) { - playerdata.remove(player.getName()); - } - } - - public interface Catcher { - - Catcher before(); - - boolean after(String message); - - void cancel(); - } -} diff --git a/src/main/java/me/skymc/taboolib/message/MsgUtils.java b/src/main/java/me/skymc/taboolib/message/MsgUtils.java deleted file mode 100644 index 9ed7c56..0000000 --- a/src/main/java/me/skymc/taboolib/message/MsgUtils.java +++ /dev/null @@ -1,73 +0,0 @@ -package me.skymc.taboolib.message; - -import me.skymc.taboolib.Main; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.plugin.Plugin; - -@Deprecated -public class MsgUtils { - - public static void send(CommandSender sender, String s) { - sender.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - public static void send(org.bukkit.entity.Player player, String s) { - player.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - public static void send(String s) { - Bukkit.getConsoleSender().sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - public static void warn(String s) { - warn(s, Main.getInst()); - } - - public static void send(String s, Plugin plugin) { - Bukkit.getConsoleSender().sendMessage("§8[§3" + plugin.getName() + "§8] §7" + s.replaceAll("&", "§")); - } - - public static void warn(String s, Plugin plugin) { - Bukkit.getConsoleSender().sendMessage("§4[§c" + plugin.getName() + "§4][WARN #!] §c" + s.replaceAll("&", "§")); - } - - @Deprecated - public static void Console(String s) { - Bukkit.getConsoleSender().sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - @Deprecated - public static void System(String s) { - System.out.println("[TabooLib] " + s); - } - - @Deprecated - public static void Sender(CommandSender p, String s) { - p.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - @Deprecated - public static void Player(org.bukkit.entity.Player p, String s) { - p.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - @Deprecated - public static String noPe() { - String s = Main.getInst().getConfig().getString("NO-PERMISSION-MESSAGE").replaceAll("&", "§"); - if ("".equals(s)) { - s = "§cCONFIG ERROR §8(NO-PERMISSION-MESSAGE)"; - } - return s; - } - - @Deprecated - public static String noClaim(String a) { - String s = Main.getInst().getConfig().getString("NO-CLAIM-MESSAGE").replaceAll("&", "§").replaceAll("%s%", a); - if ("".equals(s)) { - s = "§cCONFIG ERROR §8(NO-CLAIM-MESSAGE)"; - } - return s; - } - -} diff --git a/src/main/java/me/skymc/taboolib/methods/MethodsUtils.java b/src/main/java/me/skymc/taboolib/methods/MethodsUtils.java deleted file mode 100644 index 7040bf9..0000000 --- a/src/main/java/me/skymc/taboolib/methods/MethodsUtils.java +++ /dev/null @@ -1,49 +0,0 @@ -package me.skymc.taboolib.methods; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -@Deprecated -public class MethodsUtils { - - public static boolean checkUser(String packagename, String current) { - return current.substring(0, 8).equals(packagename); - } - - @SuppressWarnings("rawtypes") - public static Object[] a(T classname, String methodname, Class[] classes, Object[] objects) { - if (!checkUser(new String(new byte[]{'m', 'e', '.', 's', 'k', 'y', 'm', 'c'}), new Exception().getStackTrace()[1].getClassName())) { - throw new Error("未经允许的方法调用"); - } - - Class clazz = classname.getClass(); - Method method = null; - try { - method = clazz.getDeclaredMethod(methodname, classes); - method.setAccessible(true); - return new Object[]{method.invoke(classname, objects)}; - } catch (SecurityException | InvocationTargetException | IllegalAccessException | NoSuchMethodException | IllegalArgumentException e) { - e.printStackTrace(); - } - return null; - } - - public static Object b(T classname, String fieldname) { - if (!checkUser(new String(new byte[]{'m', 'e', '.', 's', 'k', 'y', 'm', 'c'}), new Exception().getStackTrace()[1].getClassName())) { - throw new Error("未经允许的方法调用"); - } - - Class clazz = classname.getClass(); - Field field = null; - Object object = null; - try { - field = clazz.getDeclaredField(fieldname); - field.setAccessible(true); - object = field.get(classname); - } catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException | SecurityException e) { - e.printStackTrace(); - } - return object; - } -} \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/mysql/MysqlConnection.java b/src/main/java/me/skymc/taboolib/mysql/MysqlConnection.java deleted file mode 100644 index f1ae225..0000000 --- a/src/main/java/me/skymc/taboolib/mysql/MysqlConnection.java +++ /dev/null @@ -1,329 +0,0 @@ -package me.skymc.taboolib.mysql; - -import java.sql.*; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Executors; - -@Deprecated -public class MysqlConnection { - - /** - * Create by Bkm016 - *

- * 2017-7-22 23:25:55 - */ - - private Connection connection = null; - - private Statement statement = null; - - private Boolean isConnection = false; - - public MysqlConnection(String ip, String port, String table, String user, String pass) { - try { - Class.forName("com.mysql.jdbc.Driver"); - System("载入 MYSQL 系统库成功"); - } catch (ClassNotFoundException e) { - System("载入 MYSQL 系统库失败"); - } - - // TODO STATE THE URL AND CONNECTION - String url = "jdbc:mysql://" + ip + ":" + port + "/" + table + "?characterEncoding=utf-8"; - - // TODO CONNECTION - try { - connection = DriverManager.getConnection(url, user, pass); - statement = connection.createStatement(); - - isConnection = true; - System("连接 MYSQL 数据库成功"); - - Executors.newFixedThreadPool(1).execute(() -> { - while (isConnection) { - try { - if (connection.isClosed()) { - connection = DriverManager.getConnection(url, user, pass); - System("数据库连接关闭, 正在重新连接... [Connection Closed]"); - } - - Thread.sleep(30000); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } catch (SQLException e) { - System("连接 MYSQL 数据库失败 详细信息: " + e.getLocalizedMessage()); - } - } - - public void closeConnection() { - try { - if (statement != null) { - statement.close(); - } - if (connection != null) { - connection.close(); - } - - isConnection = false; - System("结束 MYSQL 连接成功"); - } catch (SQLException e) { - System("结束 MYSQL 连接失败 详细信息: " + e.getLocalizedMessage()); - } - } - - public Connection getConnection() { - return this.connection; - } - - public Boolean isConnection() { - try { - if (statement.isClosed()) { - statement = null; - statement = connection.createStatement(); - System("数据库连接关闭, 正在重新连接... [Statement Closed]"); - } - } catch (SQLException e) { - e.printStackTrace(); - } - return isConnection; - } - - public Statement getStatement() { - return this.statement; - } - - /** - * Example: SQL_CreateTable("tablename", new String[] { "Player" }); - */ - public void SQL_CreateTable(String table, String[] list) { - if (!isConnection()) { - return; - } - - StringBuilder stringBuilder = new StringBuilder(); - - for (int i = 0; i < list.length; i++) { - if (i + 1 < list.length) { - stringBuilder.append("`").append(checkString(list[i])).append("` varchar(255), "); - } else { - stringBuilder.append("`").append(checkString(list[i])).append("` varchar(255)"); - } - } - String url = "CREATE TABLE IF NOT EXISTS `" + table + "` ( " + stringBuilder + " )"; - - try { - getStatement().execute(url); - } catch (SQLException e) { - System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage()); - System("任务: " + url); - } - } - - /** - * Example: SQL_SetValues("tablename", new String[] { "Player" }, new String[] { "BlackSKY" }); - */ - public void SQL_SetValues(String table, String[] list, String[] values) { - if (!isConnection()) { - return; - } - - StringBuilder listbuilder = new StringBuilder(); - StringBuilder valuebuilder = new StringBuilder(); - - for (int i = 0; i < list.length; i++) { - if (i + 1 < list.length) { - listbuilder.append("`").append(checkString(list[i])).append("`, "); - valuebuilder.append("'").append(checkString(values[i])).append("', "); - } else { - listbuilder.append("`").append(checkString(list[i])).append("`"); - valuebuilder.append("'").append(checkString(values[i])).append("'"); - } - } - - String url = "INSERT INTO `" + table + "` ( " + listbuilder + " ) VALUES ( " + valuebuilder + " )"; - try { - getStatement().execute(url); - } catch (SQLException e) { - System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage()); - System("任务: " + url); - for (int i = 0; i < e.getStackTrace().length && i < 5; i++) { - String name = e.getStackTrace()[i].getClassName(); - - System("(" + i + ")位置: " + name.substring(0, name.lastIndexOf("."))); - System(" 类名: " + e.getStackTrace()[i].getFileName().replaceAll(".java", "")); - System(" 行数: " + e.getStackTrace()[i].getLineNumber()); - } - } - } - - /** - * Example: SQL_GetValue("tablename", "Player", "BlackSKY", "Value"); - */ - public String SQL_GetValue(String table, String line, String linevalue, String row) { - if (!isConnection()) { - return null; - } - - String url = "SELECT * FROM " + checkString(table) + " WHERE `" + checkString(line) + "` = '" + checkString(linevalue) + "'"; - try { - ResultSet resultSet = getStatement().executeQuery(url); - while (resultSet.next()) { - return resultSet.getString(row); - } - resultSet.close(); - } catch (SQLException e) { - System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage()); - System("任务: " + url); - } - return null; - } - - /** - * Example: SQL_GetValues("tablename", "Player"); - */ - public List SQL_GetValues(String table, String row) { - if (!isConnection()) { - return null; - } - - List list = new ArrayList<>(); - - String url = "SELECT * FROM " + checkString(table); - try { - ResultSet resultSet = getStatement().executeQuery(url); - while (resultSet.next()) { - if (resultSet.getString(row) == null) { - continue; - } - list.add(resultSet.getString(row)); - } - resultSet.close(); - } catch (SQLException e) { - System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage()); - System("任务: " + url); - } - return list; - } - - /** - * Example: SQL_isExists("tablename", "Player", "BlackSKY"); - */ - public boolean SQL_isExists(String table, String row, String value) { - if (!isConnection()) { - return true; - } - - String url = "SELECT * FROM " + checkString(table) + " WHERE `" + checkString(row) + "` = '" + checkString(value) + "'"; - try { - ResultSet resultSet = getStatement().executeQuery(url); - while (resultSet.next()) { - return true; - } - resultSet.close(); - } catch (SQLException e) { - System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage()); - System("任务: " + url); - } - return false; - } - - /** - * Example: SQL_UpdateValue("tablename", "Player", "BlackSKY", "Value", "10") - */ - public void SQL_UpdateValue(String table, String line, String linevalue, String row, String value) { - if (!isConnection()) { - return; - } - - String url = "UPDATE `" + checkString(table) + "` SET `" + checkString(row) + "` = '" + checkString(value) + "' WHERE `" + checkString(line) + "` = '" + checkString(linevalue) + "'"; - try { - getStatement().execute(url); - } catch (SQLException e) { - System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage()); - System("任务: " + url); - } - } - - /** - * Example: SQL_DeleteValue("tablename", "BlackSKY"); - */ - public void SQL_DeleteValue(String table, String line, String linevalue) { - if (!isConnection()) { - return; - } - - String url = "DELETE FROM `" + checkString(table) + "` WHERE `" + checkString(line) + "` = '" + checkString(linevalue) + "'"; - try { - getStatement().execute(url); - } catch (SQLException e) { - System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage()); - System("任务: " + url); - } - } - - /** - * Example: SQL_ClearTable("tablename"); - * @deprecated 即将过期 - */ - @Deprecated - public void SQL_ClearTable(String table) { - if (!isConnection()) { - return; - } - - String url = "TRUNCATE TABLE `" + checkString(table) + "`"; - try { - getStatement().execute(url); - } catch (SQLException e) { - System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage()); - System("任务: " + url); - } - } - - public void SQL_execute(String url) { - if (!isConnection()) { - return; - } - - try { - getStatement().execute(url); - } catch (SQLException e) { - System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage()); - System("任务: " + url); - } - } - - public ResultSet SQL_executeQuery(String url) { - if (!isConnection()) { - return null; - } - - try { - return getStatement().executeQuery(url); - } catch (SQLException e) { - System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage()); - System("任务: " + url); - return null; - } - } - - public void SQL_clearTable(String table) { - SQL_execute("DELETE FROM " + checkString(table) + ";"); - } - - public void SQL_deleteTable(String table) { - SQL_execute("DROP TABLE " + checkString(table) + ";"); - } - - private void System(String string) { - System.out.println("[TabooLib - MYSQL] " + string); - } - - private String checkString(String string) { - return string.replace("`", "").replace("'", "").replace("\"", ""); - } - -} diff --git a/src/main/java/me/skymc/taboolib/mysql/MysqlUtils.java b/src/main/java/me/skymc/taboolib/mysql/MysqlUtils.java deleted file mode 100644 index e7aaf4a..0000000 --- a/src/main/java/me/skymc/taboolib/mysql/MysqlUtils.java +++ /dev/null @@ -1,50 +0,0 @@ -package me.skymc.taboolib.mysql; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.mysql.protect.MySQLConnection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.plugin.Plugin; - -import java.sql.Connection; -import java.util.concurrent.CopyOnWriteArrayList; - -public class MysqlUtils { - - public final static CopyOnWriteArrayList CONNECTIONS = new CopyOnWriteArrayList<>(); - - @Deprecated - public static MysqlConnection getMysqlConnectionFromConfiguration(FileConfiguration conf, String key) { - return new MysqlConnection(conf.getString(key + ".host"), conf.getString(key + ".port"), conf.getString(key + ".database"), conf.getString(key + ".user"), conf.getString(key + ".pass")); - } - - public static MySQLConnection getMySQLConnectionFromConfiguration(FileConfiguration conf, String key) { - return getMySQLConnectionFromConfiguration(conf, key, 60, Main.getInst()); - } - - public static MySQLConnection getMySQLConnectionFromConfiguration(FileConfiguration conf, String key, int recheck, Plugin plugin) { - MySQLConnection connection = getMySQLConnectionExists(conf, key); - if (connection == null) { - connection = new MySQLConnection(conf.getString(key + ".url"), conf.getString(key + ".user"), conf.getString(key + ".port"), conf.getString(key + ".password"), conf.getString(key + ".database"), recheck, plugin); - if (connection.isConnection()) { - CONNECTIONS.add(connection); - TLocale.Logger.info("MYSQL-CONNECTION.SUCCESS-REGISTERED", plugin.getName()); - } - } else { - TLocale.Logger.info("MYSQL-CONNECTION.SUCCESS-REGISTERED-EXISTS", plugin.getName(), connection.getPlugin().getName()); - } - return connection; - } - - private static MySQLConnection getMySQLConnectionExists(FileConfiguration conf, String key) { - return CONNECTIONS.stream().filter(connection -> isSameConnection(conf, key, connection)).findFirst().orElse(null); - } - - private static boolean isSameConnection(FileConfiguration conf, String key, MySQLConnection connection) { - return conversionHost(connection.getUrl()).equals(conversionHost(conf.getString(key + ".url", "localhost"))) && connection.getDatabase().equals(conf.getString(key + ".database")); - } - - private static String conversionHost(String host) { - return "localhost".equals(host) ? "127.0.0.1" : host; - } -} diff --git a/src/main/java/me/skymc/taboolib/mysql/protect/MySQLConnection.java b/src/main/java/me/skymc/taboolib/mysql/protect/MySQLConnection.java deleted file mode 100644 index 4ff774d..0000000 --- a/src/main/java/me/skymc/taboolib/mysql/protect/MySQLConnection.java +++ /dev/null @@ -1,773 +0,0 @@ -package me.skymc.taboolib.mysql.protect; - -import com.ilummc.tlib.resources.TLocale; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.Main; -import org.bukkit.plugin.Plugin; - -import java.sql.*; -import java.util.*; - -/** - * @author sky - */ -@Deprecated -public class MySQLConnection { - - private String url; - private String user; - private String port; - private String password; - private String database; - private String connectionUrl; - private Connection connection; - private Plugin plugin; - private boolean fallReconnection = true; - private int recheck = 10; - private Thread recheckThread; - - public MySQLConnection(String url, String user, String port, String password, String database) { - this(url, user, port, password, database, 10, Main.getInst()); - } - - public MySQLConnection(String url, String user, String port, String password, String database, int recheck, Plugin plugin) { - // 检查驱动 - if (!loadDriverMySQL()) { - TLocale.Logger.error("MYSQL-CONNECTION.FAIL-NOTFOUND-DRIVE"); - return; - } - - // 设置信息 - this.plugin = plugin; - this.recheck = recheck; - - // 设置数据 - this.url = url == null ? "localhost" : url; - this.user = user == null ? "root" : user; - this.port = port == null ? "3306" : port; - this.password = password == null ? "" : password; - this.database = database == null ? "test" : database; - this.connectionUrl = Strings.replaceWithOrder("jdbc:mysql://{0}:{1}/{2}?characterEncoding=utf-8&useSSL=false", this.url, this.port, this.database); - - // 连接数据库 - connect(); - - // 断线检测 - recheckThread = new Thread(() -> { - while (!Main.isDisable()) { - try { - Thread.sleep(getReCheckSeconds() * 1000); - - if (connection == null) { - TLocale.Logger.error("MYSQL-CONNECTION.FAIL-NOTFOUND-CONNECTION", plugin.getName()); - } else { - isExists("taboolib"); - } - } catch (Exception e) { - TLocale.Logger.error("MYSQL-CONNECTION.FAIL-COMMAND-NORMAL", e.toString()); - } - } - }); - - // 启动检测 - if (isConnection()) { - recheckThread.start(); - TLocale.Logger.info("MYSQL-CONNECTION.SUCCESS-REGISTERED-LISTENER"); - } - } - - public String getUrl() { - return url; - } - - public String getUser() { - return user; - } - - public String getPort() { - return port; - } - - public String getPassword() { - return password; - } - - public String getDatabase() { - return database; - } - - public String getConnectionUrl() { - return connectionUrl; - } - - public Connection getConnection() { - return connection; - } - - public Plugin getPlugin() { - return plugin; - } - - public void setPlugin(Plugin plugin) { - this.plugin = plugin; - } - - public boolean isFallReconnection() { - return fallReconnection; - } - - public void setFallReconnection(boolean fallReconnection) { - this.fallReconnection = fallReconnection; - } - - public int getRecheck() { - return recheck; - } - - public Thread getRecheckThread() { - return recheckThread; - } - - public int getReCheckSeconds() { - return recheck; - } - - public void setReCheckSeconds(int s) { - this.recheck = s; - } - - public boolean isConnection() { - try { - if (connection == null || connection.isClosed()) { - return false; - } - } catch (SQLException e) { - return false; - } - return true; - } - - @SuppressWarnings("deprecation") - public void closeConnection() { - try { - connection.close(); - } catch (Exception ignored) { - } - try { - recheckThread.stop(); - } catch (Exception ignored) { - } - } - - public boolean deleteTable(String name) { - return execute("drop table if exists " + name); - } - - /** - * 2018年1月17日 新增, TabooLib 版本 3.25 - */ - public boolean truncateTable(String name) { - return execute("truncate table " + name); - } - - public boolean clearTable(String name) { - return execute("delete from " + name); - } - - public boolean renameTable(String name, String newName) { - return execute(Strings.replaceWithOrder("rename table `{0}` to `{1}`", name, newName)); - } - - public boolean deleteColumn(String name, String column) { - return execute(Strings.replaceWithOrder("alter table `{0}` drop `{1}`", name, column)); - } - - public void addColumn(String name, Column... columns) { - Arrays.stream(columns).map(column -> Strings.replaceWithOrder("alter table {0} add {1}", name, column.toString())).forEach(this::execute); - } - - public boolean addColumn(String name, String column) { - if (!column.contains("/")) { - return execute(Strings.replaceWithOrder("alter table {0} add `{1}` text", name, column)); - } - return execute(Strings.replaceWithOrder("alter table {0} add `{1}` {2}", name, column.split("/")[0], column.split("/")[1])); - } - - public boolean editColumn(String name, String oldColumn, Column newColumn) { - return execute(Strings.replaceWithOrder("alter table {0} change `{1}` {2}", name, oldColumn, newColumn.toString())); - } - - public boolean editColumn(String name, String oldColumn, String newColumn) { - if (!newColumn.contains("/")) { - return execute(Strings.replaceWithOrder("alter table {0} change `{1}` `{2}` text", name, oldColumn, newColumn)); - } - return execute(Strings.replaceWithOrder("alter table {0} change `{1}` `{2}` {3}", name, oldColumn, newColumn.split("/")[0], newColumn.split("/")[1])); - } - - /** - * 删除数据 - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @return boolean - */ - public boolean deleteValue(String name, String column, Object columnValue) { - PreparedStatement preparedStatement = null; - try { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("delete from `{0}` where `{1}` = ?", name, column)); - preparedStatement.setObject(1, columnValue); - preparedStatement.executeUpdate(); - } catch (Exception e) { - printException(e); - } finally { - freeResult(null, preparedStatement); - } - return false; - } - - /** - * 写入数据 - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @param value 数据值 - * @return boolean - */ - public boolean setValue(String name, String column, Object columnValue, String valueColumn, Object value) { - return setValue(name, column, columnValue, valueColumn, value, false); - } - - /** - * 写入数据 - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @param value 数据值 - * @param append 是否追加(数据列类型必须为数字) - * @return boolean - */ - public boolean setValue(String name, String column, Object columnValue, String valueColumn, Object value, boolean append) { - PreparedStatement preparedStatement = null; - try { - if (append) { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("update `{0}` set `{1}` = `{2}` + ? where `{3}` = ?", name, valueColumn, valueColumn, column)); - } else { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("update `{0}` set `{1}` = ? where `{2}` = ?", name, valueColumn, column)); - } - preparedStatement.setObject(1, value); - preparedStatement.setObject(2, columnValue); - preparedStatement.executeUpdate(); - } catch (Exception e) { - printException(e); - } finally { - freeResult(null, preparedStatement); - } - return false; - } - - /** - * 插入数据 - * - * @param name 名称 - * @param values 值 - * @return boolean - */ - public boolean intoValue(String name, Object... values) { - StringBuilder sb = new StringBuilder(); - Arrays.stream(values).map(value -> "?, ").forEach(sb::append); - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - try { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("insert into `{0}` values(null, {1})", name, sb.substring(0, sb.length() - 2))); - for (int i = 0; i < values.length; i++) { - preparedStatement.setObject(i + 1, values[i]); - } - preparedStatement.executeUpdate(); - } catch (Exception e) { - printException(e); - } finally { - freeResult(null, preparedStatement); - } - return false; - } - - /** - * 创建数据表 - * - * @param name 名称 - * @param columns 列表 - * @return boolean - */ - public boolean createTable(String name, Column... columns) { - StringBuilder sb = new StringBuilder(); - Arrays.stream(columns).forEach(column -> sb.append(column.toString()).append(", ")); - return execute(Strings.replaceWithOrder("create table if not exists {0} (id int(1) not null primary key auto_increment, {1})", name, sb.substring(0, sb.length() - 2))); - } - - /** - * 创建数据表 - * - * @param name 名称 - * @param columns 列表 - * @return boolean - */ - public boolean createTable(String name, String... columns) { - StringBuilder sb = new StringBuilder(); - for (String column : columns) { - if (!column.contains("/")) { - sb.append("`").append(column).append("` text, "); - } else { - sb.append("`").append(column.split("/")[0]).append("` ").append(column.split("/")[1]).append(", "); - } - } - return execute(Strings.replaceWithOrder("create table if not exists {0} (id int(1) not null primary key auto_increment, {1})", name, sb.substring(0, sb.length() - 2))); - } - - /** - * 检查数据表是否存在 - * - * @param name 名称 - * @return boolean - */ - public boolean isExists(String name) { - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - try { - preparedStatement = connection.prepareStatement("select table_name FROM information_schema.TABLES where table_name = ?"); - preparedStatement.setString(1, name); - resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - return true; - } - } catch (Exception e) { - printException(e); - } finally { - freeResult(resultSet, preparedStatement); - } - return false; - } - - /** - * 检查数据是否存在 - * - * @param name 名称 - * @param column 列表名 - * @param columnValue 列表值 - * @return boolean - */ - public boolean isExists(String name, String column, Object columnValue) { - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - try { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` where `{1}` = ?", name, column)); - preparedStatement.setObject(1, columnValue); - resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - return true; - } - } catch (Exception e) { - printException(e); - } finally { - freeResult(resultSet, preparedStatement); - } - return false; - } - - /** - * 获取所有列表名称(不含主键) - * - * @param name 名称 - * @return {@link List} - */ - public List getColumns(String name) { - return getColumns(name, false); - } - - /** - * 获取所有列表名称 - * - * @param name 名称 - * @param primary 是否获取主键 - * @return {@link List} - */ - public List getColumns(String name, boolean primary) { - List list = new ArrayList<>(); - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - try { - preparedStatement = connection.prepareStatement("select column_name from information_schema.COLUMNS where table_name = ?"); - preparedStatement.setString(1, name); - resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - list.add(resultSet.getString(1)); - } - } catch (Exception e) { - printException(e); - } finally { - freeResult(resultSet, preparedStatement); - } - // 是否获取主键 - if (!primary) { - list.remove("id"); - } - return list; - } - - /** - * 获取单项数据 - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @return Object - */ - public Object getValue(String name, String column, Object columnValue, String valueColumn) { - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - try { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` where `{1}` = ? limit 1", name, column)); - preparedStatement.setObject(1, columnValue); - resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - return resultSet.getObject(valueColumn); - } - } catch (Exception e) { - printException(e); - } finally { - freeResult(resultSet, preparedStatement); - } - return null; - } - - /** - * 获取单项数据(根据主键倒叙排列后的最后一项) - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @return Object - */ - public Object getValueLast(String name, String column, Object columnValue, String valueColumn) { - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - try { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` where `{1}` = ? order by id desc limit 1", name, column)); - preparedStatement.setObject(1, columnValue); - resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - return resultSet.getObject(valueColumn); - } - } catch (Exception e) { - printException(e); - } finally { - freeResult(resultSet, preparedStatement); - } - return null; - } - - /** - * 获取多项数据(根据主键倒叙排列后的最后一项) - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @return {@link HashMap} - */ - public HashMap getValueLast(String name, String column, Object columnValue, String... valueColumn) { - HashMap map = new HashMap<>(); - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - try { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` where `{1}` = ? order by id desc limit 1", name, column)); - preparedStatement.setObject(1, columnValue); - resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - for (String _column : valueColumn) { - map.put(_column, resultSet.getObject(_column)); - } - break; - } - } catch (Exception e) { - printException(e); - } finally { - freeResult(resultSet, preparedStatement); - } - return map; - } - - /** - * 获取多项数据(单项多列) - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @return {@link HashMap} - */ - public HashMap getValue(String name, String column, Object columnValue, String... valueColumn) { - HashMap map = new HashMap<>(); - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - try { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` where `{1}` = ? limit 1", name, column)); - preparedStatement.setObject(1, columnValue); - resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - for (String _column : valueColumn) { - map.put(_column, resultSet.getObject(_column)); - } - break; - } - } catch (Exception e) { - printException(e); - } finally { - freeResult(resultSet, preparedStatement); - } - return map; - } - - /** - * 获取多项数据(单列多列) - * - * @param name 名称 - * @param column 参考列 - * @param size 获取数量(-1 为无限制) - * @return {@link List} - */ - public List getValues(String name, String column, int size) { - return getValues(name, column, size, false); - } - - /** - * 获取多项数据(单列多列) - * - * @param name 名称 - * @param column 参考列 - * @param size 获取数量(-1 位无限制) - * @param desc 是否倒序 - * @return {@link List} - */ - public List getValues(String name, String column, int size, boolean desc) { - List list = new LinkedList<>(); - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - try { - if (desc) { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}` desc {2}", name, column, size < 0 ? "" : " limit " + size)); - } else { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}` {2}", name, column, size < 0 ? "" : " limit " + size)); - } - resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - list.add(resultSet.getObject(column)); - } - } catch (Exception e) { - printException(e); - } finally { - freeResult(resultSet, preparedStatement); - } - return list; - } - - /** - * 获取多线数据(多项多列) - * - * @param name 名称 - * @param sortColumn 参考列(该列类型必须为数字) - * @param size 获取数量(-1 为无限制) - * @param valueColumn 获取数据列 - * @return {@link LinkedList} - */ - public LinkedList> getValues(String name, String sortColumn, int size, String... valueColumn) { - return getValues(name, sortColumn, size, false, valueColumn); - } - - /** - * 获取多项数据(多项多列) - * - * @param name 名称 - * @param sortColumn 参考列(该列类型必须为数字) - * @param size 获取数量(-1 为无限制) - * @param desc 是否倒序 - * @param valueColumn 获取数据列 - * @return {@link LinkedList} - */ - public LinkedList> getValues(String name, String sortColumn, int size, boolean desc, String... valueColumn) { - LinkedList> list = new LinkedList<>(); - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - try { - if (desc) { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}` desc{2}", name, sortColumn, size < 0 ? "" : " limit " + size)); - } else { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}`{2}", name, sortColumn, size < 0 ? "" : " limit " + size)); - } - resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - HashMap map = new HashMap<>(); - for (String _column : valueColumn) { - map.put(_column, resultSet.getObject(_column)); - } - list.add(map); - } - } catch (Exception e) { - printException(e); - } finally { - freeResult(resultSet, preparedStatement); - } - return list; - } - - public boolean execute(String sql) { - PreparedStatement preparedStatement = null; - try { - preparedStatement = connection.prepareStatement(sql); - preparedStatement.execute(); - return true; - } catch (SQLException e) { - printExceptionDetail(e); - return false; - } finally { - freeResult(null, preparedStatement); - } - } - - public boolean connect() { - TLocale.Logger.info("MYSQL-CONNECTION.NOTIFY-CONNECTING", connectionUrl); - try { - long time = System.currentTimeMillis(); - connection = DriverManager.getConnection(connectionUrl, this.user, this.password); - TLocale.Logger.info("MYSQL-CONNECTION.NOTIFY-CONNECTED", String.valueOf(System.currentTimeMillis() - time)); - return true; - } catch (SQLException e) { - printExceptionDetail(e); - return false; - } - } - - public void print(String message) { - System.out.println("[TabooLib - MySQL] " + message); - } - - private void printException(Exception e) { - TLocale.Logger.error("MYSQL-CONNECTION.FAIL-COMMAND-NORMAL", e.toString()); - reconnection(e); - } - - private void printExceptionDetail(SQLException e) { - TLocale.Logger.error("MYSQL-CONNECTION.FAIL-COMMAND-DETAIL", String.valueOf(e.getErrorCode()), e.toString()); - reconnection(e); - } - - private void reconnection(Exception e) { - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } - - private boolean loadDriverMySQL() { - try { - Class.forName("com.mysql.jdbc.Driver"); - return true; - } catch (ClassNotFoundException e) { - return false; - } - } - - private void freeResult(ResultSet resultSet, PreparedStatement preparedStatement) { - try { - if (resultSet != null) { - resultSet.close(); - } - } catch (Exception ignored) { - } - try { - if (preparedStatement != null) { - preparedStatement.close(); - } - } catch (Exception ignored) { - } - } - - public enum ColumnInteger { - - TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT - } - - public enum ColumnFloat { - - FLOAT, DOUBLE - } - - public enum ColumnChar { - - CHAR, VARCHAR - } - - public enum ColumnString { - - TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT - } - - public static class Column { - - private String name; - private Object type; - private int a; - private int b; - - public Column(String name) { - this.name = name; - this.type = ColumnString.TEXT; - } - - public Column(String name, ColumnInteger type) { - this(name); - this.type = type; - this.a = 12; - } - - public Column(String name, ColumnInteger type, int m) { - this(name); - this.type = type; - this.a = m; - } - - public Column(String name, ColumnFloat type, int m, int d) { - this(name); - this.type = type; - this.a = m; - this.b = d; - } - - public Column(String name, ColumnChar type, int n) { - this(name); - this.type = type; - this.a = n; - } - - public Column(String name, ColumnString type) { - this(name); - this.type = type; - } - - @Override - public String toString() { - if (type instanceof ColumnInteger || type instanceof ColumnChar) { - return Strings.replaceWithOrder("`{0}` {1}({2})", name, type.toString().toLowerCase(), a); - } else if (type instanceof ColumnFloat) { - return Strings.replaceWithOrder("`{0}` {1}({2},{3})", name, type.toString().toLowerCase(), a, b); - } else { - return Strings.replaceWithOrder("`{0}` {1}", name, type.toString().toLowerCase()); - } - } - } -} diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java b/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java deleted file mode 100644 index fcdf616..0000000 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java +++ /dev/null @@ -1,1323 +0,0 @@ -package me.skymc.taboolib.nms; - -import org.bukkit.*; -import org.bukkit.block.BlockFace; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.Vector; - -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * @author Unknown - */ -@SuppressWarnings({"rawtypes", "unchecked"}) -public class NMSUtil18 { - - protected static boolean failed = false; - - protected static String versionPrefix = ""; - - protected final static int NBT_TYPE_COMPOUND = 10; - protected final static int NBT_TYPE_INT_ARRAY = 11; - protected final static int NBT_TYPE_DOUBLE = 6; - protected final static int NBT_TYPE_FLOAT = 5; - protected final static int NBT_TYPE_STRING = 8; - - protected static int WITHER_SKULL_TYPE = 66; - protected static int FIREWORK_TYPE = 76; - - protected static Class class_ItemStack; - protected static Class class_NBTBase; - protected static Class class_NBTTagCompound; - protected static Class class_NBTTagList; - protected static Class class_NBTTagByte; - protected static Class class_NBTTagString; - protected static Class class_CraftTask; - protected static Class class_CraftInventoryCustom; - protected static Class class_CraftItemStack; - protected static Class class_CraftBlockState; - protected static Class class_CraftLivingEntity; - protected static Class class_CraftWorld; - protected static Class class_Entity; - protected static Class class_EntityCreature; - protected static Class class_EntityLiving; - protected static Class class_DataWatcher; - protected static Class class_DamageSource; - protected static Class class_EntityDamageSource; - protected static Class class_World; - protected static Class class_WorldServer; - protected static Class class_Packet; - protected static Class class_EnumSkyBlock; - protected static Class class_PacketPlayOutMapChunkBulk; - protected static Class class_EntityPainting; - protected static Class class_EntityItemFrame; - protected static Class class_EntityMinecartRideable; - protected static Class class_EntityTNTPrimed; - protected static Class class_AxisAlignedBB; - protected static Class class_PathPoint; - protected static Class class_PathEntity; - protected static Class class_EntityFirework; - protected static Class class_CraftSkull; - protected static Class class_CraftBanner; - protected static Class class_CraftMetaSkull; - protected static Class class_CraftMetaBanner; - protected static Class class_GameProfile; - protected static Class class_GameProfileProperty; - protected static Class class_BlockPosition; - protected static Class class_NBTCompressedStreamTools; - protected static Class class_TileEntity; - protected static Class class_TileEntitySign; - protected static Class class_TileEntityContainer; - protected static Class class_ChestLock; - protected static Class class_EnumDirection; - protected static Class class_EntityHorse; - protected static Class class_EntityWitherSkull; - protected static Class class_PacketPlayOutAttachEntity; - protected static Class class_PacketPlayOutEntityDestroy; - protected static Class class_PacketPlayOutSpawnEntity; - protected static Class class_PacketPlayOutSpawnEntityLiving; - protected static Class class_PacketPlayOutEntityMetadata; - protected static Class class_PacketPlayOutEntityStatus; - protected static Class class_EntityFallingBlock; - protected static Class class_EntityArmorStand; - protected static Class class_EntityPlayer; - protected static Class class_PlayerConnection; - protected static Class class_Chunk; - protected static Class class_CraftPlayer; - protected static Class class_CraftChunk; - protected static Class class_CraftEntity; - protected static Class class_EntityProjectile; - protected static Class class_EntityFireball; - protected static Class class_EntityArrow; - protected static Class class_CraftArrow; - - protected static Method class_NBTTagList_addMethod; - protected static Method class_NBTTagList_getMethod; - protected static Method class_NBTTagList_getDoubleMethod; - protected static Method class_NBTTagList_sizeMethod; - protected static Method class_NBTTagCompound_setMethod; - protected static Method class_DataWatcher_watchMethod; - protected static Method class_World_getEntitiesMethod; - protected static Method class_Entity_setSilentMethod; - protected static Method class_Entity_setYawPitchMethod; - protected static Method class_Entity_getBukkitEntityMethod; - protected static Method class_EntityLiving_damageEntityMethod; - protected static Method class_DamageSource_getMagicSourceMethod; - protected static Method class_EntityDamageSource_setThornsMethod; - protected static Method class_AxisAlignedBB_createBBMethod; - protected static Method class_World_explodeMethod; - protected static Method class_NBTTagCompound_setBooleanMethod; - protected static Method class_NBTTagCompound_setStringMethod; - protected static Method class_NBTTagCompound_setIntMethod; - protected static Method class_NBTTagCompound_removeMethod; - protected static Method class_NBTTagCompound_getStringMethod; - protected static Method class_NBTTagCompound_getIntMethod; - protected static Method class_NBTTagCompound_getByteMethod; - protected static Method class_NBTTagCompound_getMethod; - protected static Method class_NBTTagCompound_getCompoundMethod; - protected static Method class_NBTTagCompound_getShortMethod; - protected static Method class_NBTTagCompound_getByteArrayMethod; - protected static Method class_NBTTagCompound_getListMethod; - protected static Method class_TileEntity_loadMethod; - protected static Method class_TileEntity_saveMethod; - protected static Method class_TileEntity_updateMethod; - protected static Method class_World_addEntityMethod; - protected static Method class_CraftMetaBanner_getPatternsMethod; - protected static Method class_CraftMetaBanner_setPatternsMethod; - protected static Method class_CraftMetaBanner_getBaseColorMethod; - protected static Method class_CraftMetaBanner_setBaseColorMethod; - protected static Method class_CraftBanner_getPatternsMethod; - protected static Method class_CraftBanner_setPatternsMethod; - protected static Method class_CraftBanner_getBaseColorMethod; - protected static Method class_CraftBanner_setBaseColorMethod; - protected static Method class_NBTCompressedStreamTools_loadFileMethod; - protected static Method class_ItemStack_createStackMethod; - protected static Method class_CraftItemStack_asBukkitCopyMethod; - protected static Method class_CraftItemStack_copyMethod; - protected static Method class_CraftItemStack_mirrorMethod; - protected static Method class_NBTTagCompound_hasKeyMethod; - protected static Method class_CraftWorld_getTileEntityAtMethod; - protected static Method class_CraftWorld_spawnMethod; - protected static Method class_Entity_setLocationMethod; - protected static Method class_Entity_getIdMethod; - protected static Method class_Entity_getDataWatcherMethod; - protected static Method class_Server_getOnlinePlayers; - protected static Method class_Entity_getBoundingBox; - protected static Method class_TileEntityContainer_setLock; - protected static Method class_TileEntityContainer_getLock; - protected static Method class_ChestLock_isEmpty; - protected static Method class_ChestLock_getString; - protected static Method class_ArmorStand_setInvisible; - protected static Method class_ArmorStand_setMarker; - protected static Method class_ArmorStand_setGravity; - protected static Method class_ArmorStand_setSmall; - protected static Method class_CraftPlayer_getHandleMethod; - protected static Method class_CraftChunk_getHandleMethod; - protected static Method class_CraftEntity_getHandleMethod; - protected static Method class_CraftLivingEntity_getHandleMethod; - protected static Method class_CraftWorld_getHandleMethod; - protected static Method class_EntityPlayer_openSignMethod; - - protected static Constructor class_NBTTagList_consructor; - protected static Constructor class_NBTTagList_legacy_consructor; - protected static Constructor class_CraftInventoryCustom_constructor; - protected static Constructor class_NBTTagByte_constructor; - protected static Constructor class_NBTTagByte_legacy_constructor; - protected static Constructor class_EntityFireworkConstructor; - protected static Constructor class_EntityPaintingConstructor; - protected static Constructor class_EntityItemFrameConstructor; - protected static Constructor class_BlockPositionConstructor; - protected static Constructor class_PacketSpawnEntityConstructor; - protected static Constructor class_PacketSpawnLivingEntityConstructor; - protected static Constructor class_PacketPlayOutEntityMetadata_Constructor; - protected static Constructor class_PacketPlayOutEntityStatus_Constructor; - protected static Constructor class_PacketPlayOutEntityDestroy_Constructor; - protected static Constructor class_ChestLock_Constructor; - protected static Constructor class_ArmorStand_Constructor; - - protected static Field class_Entity_invulnerableField; - protected static Field class_Entity_motXField; - protected static Field class_Entity_motYField; - protected static Field class_Entity_motZField; - protected static Field class_WorldServer_entitiesByUUIDField; - protected static Field class_ItemStack_tagField; - protected static Field class_DamageSource_MagicField; - protected static Field class_Firework_ticksFlownField; - protected static Field class_Firework_expectedLifespanField; - protected static Field class_CraftSkull_profile; - protected static Field class_CraftMetaSkull_profile; - protected static Field class_GameProfile_properties; - protected static Field class_GameProfileProperty_value; - protected static Field class_ItemStack_count; - protected static Field class_EntityTNTPrimed_source; - protected static Field class_NBTTagList_list; - protected static Field class_AxisAlignedBB_minXField; - protected static Field class_AxisAlignedBB_minYField; - protected static Field class_AxisAlignedBB_minZField; - protected static Field class_AxisAlignedBB_maxXField; - protected static Field class_AxisAlignedBB_maxYField; - protected static Field class_AxisAlignedBB_maxZField; - protected static Field class_EntityFallingBlock_hurtEntitiesField; - protected static Field class_EntityFallingBlock_fallHurtMaxField; - protected static Field class_EntityFallingBlock_fallHurtAmountField; - protected static Field class_EntityArmorStand_disabledSlotsField; - protected static Field class_EntityPlayer_playerConnectionField; - protected static Field class_PlayerConnection_floatCountField; - protected static Field class_Chunk_doneField; - protected static Field class_CraftItemStack_getHandleField; - protected static Field class_EntityArrow_lifeField = null; - protected static Field class_EntityArrow_fromPlayerField; - protected static Field class_EntityArrow_damageField; - protected static Field class_CraftWorld_environmentField; - - static { - // Find classes Bukkit hides from us. :-D - // Much thanks to @DPOHVAR for sharing the PowerNBT code that powers the reflection approach. - String className = Bukkit.getServer().getClass().getName(); - String[] packages = className.split("\\."); - if (packages.length == 5) { - versionPrefix = packages[3] + "."; - } - - try { - class_Entity = fixBukkitClass("net.minecraft.server.Entity"); - class_EntityLiving = fixBukkitClass("net.minecraft.server.EntityLiving"); - class_ItemStack = fixBukkitClass("net.minecraft.server.ItemStack"); - class_DataWatcher = fixBukkitClass("net.minecraft.server.DataWatcher"); - class_NBTBase = fixBukkitClass("net.minecraft.server.NBTBase"); - class_NBTTagCompound = fixBukkitClass("net.minecraft.server.NBTTagCompound"); - class_NBTTagList = fixBukkitClass("net.minecraft.server.NBTTagList"); - class_NBTTagString = fixBukkitClass("net.minecraft.server.NBTTagString"); - class_NBTTagByte = fixBukkitClass("net.minecraft.server.NBTTagByte"); - class_CraftWorld = fixBukkitClass("org.bukkit.craftbukkit.CraftWorld"); - class_CraftInventoryCustom = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftInventoryCustom"); - class_CraftItemStack = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftItemStack"); - class_CraftBlockState = fixBukkitClass("org.bukkit.craftbukkit.block.CraftBlockState"); - class_CraftTask = fixBukkitClass("org.bukkit.craftbukkit.scheduler.CraftTask"); - class_CraftLivingEntity = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftLivingEntity"); - class_Packet = fixBukkitClass("net.minecraft.server.Packet"); - class_World = fixBukkitClass("net.minecraft.server.World"); - class_WorldServer = fixBukkitClass("net.minecraft.server.WorldServer"); - class_EnumSkyBlock = (Class) fixBukkitClass("net.minecraft.server.EnumSkyBlock"); - class_EntityPainting = fixBukkitClass("net.minecraft.server.EntityPainting"); - class_EntityCreature = fixBukkitClass("net.minecraft.server.EntityCreature"); - class_EntityItemFrame = fixBukkitClass("net.minecraft.server.EntityItemFrame"); - class_EntityMinecartRideable = fixBukkitClass("net.minecraft.server.EntityMinecartRideable"); - class_EntityTNTPrimed = fixBukkitClass("net.minecraft.server.EntityTNTPrimed"); - class_AxisAlignedBB = fixBukkitClass("net.minecraft.server.AxisAlignedBB"); - class_DamageSource = fixBukkitClass("net.minecraft.server.DamageSource"); - class_EntityDamageSource = fixBukkitClass("net.minecraft.server.EntityDamageSource"); - class_PathEntity = fixBukkitClass("net.minecraft.server.PathEntity"); - class_PathPoint = fixBukkitClass("net.minecraft.server.PathPoint"); - class_EntityFirework = fixBukkitClass("net.minecraft.server.EntityFireworks"); - class_CraftSkull = fixBukkitClass("org.bukkit.craftbukkit.block.CraftSkull"); - class_CraftMetaSkull = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftMetaSkull"); - class_NBTCompressedStreamTools = fixBukkitClass("net.minecraft.server.NBTCompressedStreamTools"); - class_TileEntity = fixBukkitClass("net.minecraft.server.TileEntity"); - class_EntityHorse = fixBukkitClass("net.minecraft.server.EntityHorse"); - class_EntityWitherSkull = fixBukkitClass("net.minecraft.server.EntityWitherSkull"); - class_PacketPlayOutAttachEntity = fixBukkitClass("net.minecraft.server.PacketPlayOutAttachEntity"); - class_PacketPlayOutEntityDestroy = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityDestroy"); - class_PacketPlayOutSpawnEntity = fixBukkitClass("net.minecraft.server.PacketPlayOutSpawnEntity"); - class_PacketPlayOutSpawnEntityLiving = fixBukkitClass("net.minecraft.server.PacketPlayOutSpawnEntityLiving"); - class_PacketPlayOutEntityMetadata = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityMetadata"); - class_PacketPlayOutEntityStatus = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityStatus"); - class_EntityFallingBlock = fixBukkitClass("net.minecraft.server.EntityFallingBlock"); - class_EntityArmorStand = fixBukkitClass("net.minecraft.server.EntityArmorStand"); - class_EntityPlayer = fixBukkitClass("net.minecraft.server.EntityPlayer"); - class_PlayerConnection = fixBukkitClass("net.minecraft.server.PlayerConnection"); - class_Chunk = fixBukkitClass("net.minecraft.server.Chunk"); - class_CraftPlayer = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftPlayer"); - class_CraftChunk = fixBukkitClass("org.bukkit.craftbukkit.CraftChunk"); - class_CraftEntity = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftEntity"); - class_TileEntitySign = fixBukkitClass("net.minecraft.server.TileEntitySign"); - - class_EntityProjectile = NMSUtil18.getBukkitClass("net.minecraft.server.EntityProjectile"); - class_EntityFireball = NMSUtil18.getBukkitClass("net.minecraft.server.EntityFireball"); - class_EntityArrow = NMSUtil18.getBukkitClass("net.minecraft.server.EntityArrow"); - class_CraftArrow = NMSUtil18.getBukkitClass("org.bukkit.craftbukkit.entity.CraftArrow"); - - class_NBTTagList_addMethod = class_NBTTagList.getMethod("add", class_NBTBase); - class_NBTTagList_getMethod = class_NBTTagList.getMethod("get", Integer.TYPE); - class_NBTTagList_getDoubleMethod = class_NBTTagList.getMethod("d", Integer.TYPE); - class_NBTTagList_sizeMethod = class_NBTTagList.getMethod("size"); - class_NBTTagCompound_setMethod = class_NBTTagCompound.getMethod("set", String.class, class_NBTBase); - class_DataWatcher_watchMethod = class_DataWatcher.getMethod("watch", Integer.TYPE, Object.class); - class_World_getEntitiesMethod = class_World.getMethod("getEntities", class_Entity, class_AxisAlignedBB); - class_CraftWorld_getTileEntityAtMethod = class_CraftWorld.getMethod("getTileEntityAt", Integer.TYPE, Integer.TYPE, Integer.TYPE); - class_CraftWorld_spawnMethod = class_CraftWorld.getMethod("spawn", Location.class, Class.class, CreatureSpawnEvent.SpawnReason.class); - class_Entity_getBukkitEntityMethod = class_Entity.getMethod("getBukkitEntity"); - class_Entity_setYawPitchMethod = class_Entity.getDeclaredMethod("setYawPitch", Float.TYPE, Float.TYPE); - class_Entity_setYawPitchMethod.setAccessible(true); - class_Entity_setSilentMethod = class_Entity.getDeclaredMethod("b", Boolean.TYPE); - class_AxisAlignedBB_createBBMethod = class_AxisAlignedBB.getMethod("a", Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE); - class_World_explodeMethod = class_World.getMethod("createExplosion", class_Entity, Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPE, Boolean.TYPE); - class_NBTTagCompound_setBooleanMethod = class_NBTTagCompound.getMethod("setBoolean", String.class, Boolean.TYPE); - class_NBTTagCompound_setStringMethod = class_NBTTagCompound.getMethod("setString", String.class, String.class); - class_NBTTagCompound_setIntMethod = class_NBTTagCompound.getMethod("setInt", String.class, Integer.TYPE); - class_NBTTagCompound_removeMethod = class_NBTTagCompound.getMethod("remove", String.class); - class_NBTTagCompound_getStringMethod = class_NBTTagCompound.getMethod("getString", String.class); - class_NBTTagCompound_getShortMethod = class_NBTTagCompound.getMethod("getShort", String.class); - class_NBTTagCompound_getIntMethod = class_NBTTagCompound.getMethod("getInt", String.class); - class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class); - class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class); - class_NBTTagCompound_getListMethod = class_NBTTagCompound.getMethod("getList", String.class, Integer.TYPE); - class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", ItemStack.class); - class_CraftItemStack_asBukkitCopyMethod = class_CraftItemStack.getMethod("asBukkitCopy", class_ItemStack); - class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack); - class_ItemStack_createStackMethod = class_ItemStack.getMethod("createStack", class_NBTTagCompound); - class_NBTTagCompound_hasKeyMethod = class_NBTTagCompound.getMethod("hasKey", String.class); - class_NBTTagCompound_getMethod = class_NBTTagCompound.getMethod("get", String.class); - class_NBTTagCompound_getCompoundMethod = class_NBTTagCompound.getMethod("getCompound", String.class); - class_EntityLiving_damageEntityMethod = class_EntityLiving.getMethod("damageEntity", class_DamageSource, Float.TYPE); - class_DamageSource_getMagicSourceMethod = class_DamageSource.getMethod("b", class_Entity, class_Entity); - class_World_addEntityMethod = class_World.getMethod("addEntity", class_Entity, CreatureSpawnEvent.SpawnReason.class); - class_NBTCompressedStreamTools_loadFileMethod = class_NBTCompressedStreamTools.getMethod("a", InputStream.class); - class_TileEntity_loadMethod = class_TileEntity.getMethod("a", class_NBTTagCompound); - class_TileEntity_saveMethod = class_TileEntity.getMethod("b", class_NBTTagCompound); - class_TileEntity_updateMethod = class_TileEntity.getMethod("update"); - class_Entity_setLocationMethod = class_Entity.getMethod("setLocation", Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Float.TYPE); - class_Entity_getIdMethod = class_Entity.getMethod("getId"); - class_Entity_getDataWatcherMethod = class_Entity.getMethod("getDataWatcher"); - class_Server_getOnlinePlayers = Server.class.getMethod("getOnlinePlayers"); - class_ArmorStand_setInvisible = class_EntityArmorStand.getDeclaredMethod("setInvisible", Boolean.TYPE); - class_ArmorStand_setGravity = class_EntityArmorStand.getDeclaredMethod("setGravity", Boolean.TYPE); - class_ArmorStand_setSmall = class_EntityArmorStand.getDeclaredMethod("setSmall", Boolean.TYPE); - class_ArmorStand_setMarker = class_EntityArmorStand.getDeclaredMethod("n", Boolean.TYPE); - class_ArmorStand_setMarker.setAccessible(true); - class_CraftPlayer_getHandleMethod = class_CraftPlayer.getMethod("getHandle"); - class_CraftChunk_getHandleMethod = class_CraftChunk.getMethod("getHandle"); - class_CraftEntity_getHandleMethod = class_CraftEntity.getMethod("getHandle"); - class_CraftLivingEntity_getHandleMethod = class_CraftLivingEntity.getMethod("getHandle"); - class_CraftWorld_getHandleMethod = class_CraftWorld.getMethod("getHandle"); - class_EntityPlayer_openSignMethod = class_EntityPlayer.getMethod("openSign", class_TileEntitySign); - - class_CraftInventoryCustom_constructor = class_CraftInventoryCustom.getConstructor(InventoryHolder.class, Integer.TYPE, String.class); - class_EntityFireworkConstructor = class_EntityFirework.getConstructor(class_World, Double.TYPE, Double.TYPE, Double.TYPE, class_ItemStack); - class_PacketSpawnEntityConstructor = class_PacketPlayOutSpawnEntity.getConstructor(class_Entity, Integer.TYPE); - class_PacketSpawnLivingEntityConstructor = class_PacketPlayOutSpawnEntityLiving.getConstructor(class_EntityLiving); - class_PacketPlayOutEntityMetadata_Constructor = class_PacketPlayOutEntityMetadata.getConstructor(Integer.TYPE, class_DataWatcher, Boolean.TYPE); - class_PacketPlayOutEntityStatus_Constructor = class_PacketPlayOutEntityStatus.getConstructor(class_Entity, Byte.TYPE); - class_PacketPlayOutEntityDestroy_Constructor = class_PacketPlayOutEntityDestroy.getConstructor(int[].class); - - class_CraftWorld_environmentField = class_CraftWorld.getDeclaredField("environment"); - class_CraftWorld_environmentField.setAccessible(true); - class_Entity_invulnerableField = class_Entity.getDeclaredField("invulnerable"); - class_Entity_invulnerableField.setAccessible(true); - class_Entity_motXField = class_Entity.getDeclaredField("motX"); - class_Entity_motXField.setAccessible(true); - class_Entity_motYField = class_Entity.getDeclaredField("motY"); - class_Entity_motYField.setAccessible(true); - class_Entity_motZField = class_Entity.getDeclaredField("motZ"); - class_Entity_motZField.setAccessible(true); - class_WorldServer_entitiesByUUIDField = class_WorldServer.getDeclaredField("entitiesByUUID"); - class_WorldServer_entitiesByUUIDField.setAccessible(true); - class_ItemStack_tagField = class_ItemStack.getDeclaredField("tag"); - class_ItemStack_tagField.setAccessible(true); - class_DamageSource_MagicField = class_DamageSource.getField("MAGIC"); - class_EntityTNTPrimed_source = class_EntityTNTPrimed.getDeclaredField("source"); - class_EntityTNTPrimed_source.setAccessible(true); - class_AxisAlignedBB_minXField = class_AxisAlignedBB.getField("a"); - class_AxisAlignedBB_minYField = class_AxisAlignedBB.getField("b"); - class_AxisAlignedBB_minZField = class_AxisAlignedBB.getField("c"); - class_AxisAlignedBB_maxXField = class_AxisAlignedBB.getField("d"); - class_AxisAlignedBB_maxYField = class_AxisAlignedBB.getField("e"); - class_AxisAlignedBB_maxZField = class_AxisAlignedBB.getField("f"); - class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bi"); - class_EntityArmorStand_disabledSlotsField.setAccessible(true); - class_EntityPlayer_playerConnectionField = class_EntityPlayer.getDeclaredField("playerConnection"); - class_PlayerConnection_floatCountField = class_PlayerConnection.getDeclaredField("g"); - class_PlayerConnection_floatCountField.setAccessible(true); - - class_Firework_ticksFlownField = class_EntityFirework.getDeclaredField("ticksFlown"); - class_Firework_ticksFlownField.setAccessible(true); - class_Firework_expectedLifespanField = class_EntityFirework.getDeclaredField("expectedLifespan"); - class_Firework_expectedLifespanField.setAccessible(true); - - class_NBTTagList_consructor = class_NBTTagString.getConstructor(String.class); - class_NBTTagByte_constructor = class_NBTTagByte.getConstructor(Byte.TYPE); - class_ItemStack_count = class_ItemStack.getDeclaredField("count"); - class_ItemStack_count.setAccessible(true); - - class_NBTTagList_list = class_NBTTagList.getDeclaredField("list"); - class_NBTTagList_list.setAccessible(true); - - class_EntityFallingBlock_hurtEntitiesField = class_EntityFallingBlock.getDeclaredField("hurtEntities"); - class_EntityFallingBlock_hurtEntitiesField.setAccessible(true); - class_EntityFallingBlock_fallHurtAmountField = class_EntityFallingBlock.getDeclaredField("fallHurtAmount"); - class_EntityFallingBlock_fallHurtAmountField.setAccessible(true); - class_EntityFallingBlock_fallHurtMaxField = class_EntityFallingBlock.getDeclaredField("fallHurtMax"); - class_EntityFallingBlock_fallHurtMaxField.setAccessible(true); - - class_Chunk_doneField = class_Chunk.getDeclaredField("done"); - class_Chunk_doneField.setAccessible(true); - class_CraftItemStack_getHandleField = class_CraftItemStack.getDeclaredField("handle"); - class_CraftItemStack_getHandleField.setAccessible(true); - - class_TileEntityContainer = fixBukkitClass("net.minecraft.server.TileEntityContainer"); - class_ChestLock = fixBukkitClass("net.minecraft.server.ChestLock"); - class_TileEntityContainer_setLock = class_TileEntityContainer.getMethod("a", class_ChestLock); - class_TileEntityContainer_getLock = class_TileEntityContainer.getMethod("i"); - class_ChestLock_isEmpty = class_ChestLock.getMethod("a"); - class_ChestLock_getString = class_ChestLock.getMethod("b"); - class_Entity_getBoundingBox = class_Entity.getMethod("getBoundingBox"); - class_GameProfile = getClass("com.mojang.authlib.GameProfile"); - class_GameProfileProperty = getClass("com.mojang.authlib.properties.Property"); - class_CraftSkull_profile = class_CraftSkull.getDeclaredField("profile"); - class_CraftSkull_profile.setAccessible(true); - class_CraftMetaSkull_profile = class_CraftMetaSkull.getDeclaredField("profile"); - class_CraftMetaSkull_profile.setAccessible(true); - class_GameProfile_properties = class_GameProfile.getDeclaredField("properties"); - class_GameProfile_properties.setAccessible(true); - class_GameProfileProperty_value = class_GameProfileProperty.getDeclaredField("value"); - class_GameProfileProperty_value.setAccessible(true); - - class_CraftMetaBanner = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftMetaBanner"); - class_CraftMetaBanner_getBaseColorMethod = class_CraftMetaBanner.getMethod("getBaseColor"); - class_CraftMetaBanner_getPatternsMethod = class_CraftMetaBanner.getMethod("getPatterns"); - class_CraftMetaBanner_setPatternsMethod = class_CraftMetaBanner.getMethod("setPatterns", List.class); - class_CraftMetaBanner_setBaseColorMethod = class_CraftMetaBanner.getMethod("setBaseColor", DyeColor.class); - - class_CraftBanner = fixBukkitClass("org.bukkit.craftbukkit.block.CraftBanner"); - class_CraftBanner_getBaseColorMethod = class_CraftBanner.getMethod("getBaseColor"); - class_CraftBanner_getPatternsMethod = class_CraftBanner.getMethod("getPatterns"); - class_CraftBanner_setPatternsMethod = class_CraftBanner.getMethod("setPatterns", List.class); - class_CraftBanner_setBaseColorMethod = class_CraftBanner.getMethod("setBaseColor", DyeColor.class); - class_EntityDamageSource_setThornsMethod = class_EntityDamageSource.getMethod("v"); - - class_BlockPosition = fixBukkitClass("net.minecraft.server.BlockPosition"); - class_EnumDirection = (Class) fixBukkitClass("net.minecraft.server.EnumDirection"); - class_BlockPositionConstructor = class_BlockPosition.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE); - class_EntityPaintingConstructor = class_EntityPainting.getConstructor(class_World, class_BlockPosition, class_EnumDirection); - class_EntityItemFrameConstructor = class_EntityItemFrame.getConstructor(class_World, class_BlockPosition, class_EnumDirection); - class_ChestLock_Constructor = class_ChestLock.getConstructor(String.class); - class_ArmorStand_Constructor = class_EntityArmorStand.getConstructor(class_World); - - class_PacketPlayOutMapChunkBulk = getVersionedBukkitClass("net.minecraft.server.PacketPlayOutMapChunkBulk", "net.minecraft.server.Packet56MapChunkBulk"); - - try { - class_EntityArrow_fromPlayerField = class_EntityArrow.getField("fromPlayer"); - class_EntityArrow_damageField = class_EntityArrow.getDeclaredField("damage"); - class_EntityArrow_damageField.setAccessible(true); - // This is kinda hacky, like fer reals :\ - try { - // 1.8.3 - class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("ar"); - } catch (Throwable ignore3) { - try { - // 1.8 - class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("ap"); - } catch (Throwable ignore2) { - try { - // 1.7 - class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("at"); - } catch (Throwable ignore) { - // Prior - class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("j"); - } - } - } - } catch (Throwable ex) { - class_EntityArrow_lifeField = null; - } - if (class_EntityArrow_lifeField != null) { - class_EntityArrow_lifeField.setAccessible(true); - } - } catch (Throwable ex) { - failed = true; - ex.printStackTrace(); - } - } - - public static boolean getFailed() { - return failed; - } - - public static Class getVersionedBukkitClass(String newVersion, String oldVersion) { - Class c = getBukkitClass(newVersion); - if (c == null) { - c = getBukkitClass(oldVersion); - if (c == null) { - Bukkit.getLogger().warning("Could not bind to " + newVersion + " or " + oldVersion); - } - } - return c; - } - - public static Class getClass(String className) { - Class result = null; - try { - result = NMSUtil18.class.getClassLoader().loadClass(className); - } catch (Exception ex) { - result = null; - } - - return result; - } - - public static Class getBukkitClass(String className) { - Class result = null; - try { - result = fixBukkitClass(className); - } catch (Exception ex) { - result = null; - } - - return result; - } - - public static Class fixBukkitClass(String className) throws ClassNotFoundException { - if (!versionPrefix.isEmpty()) { - className = className.replace("org.bukkit.craftbukkit.", "org.bukkit.craftbukkit." + versionPrefix); - className = className.replace("net.minecraft.server.", "net.minecraft.server." + versionPrefix); - } - - return NMSUtil18.class.getClassLoader().loadClass(className); - } - - public static Object getHandle(ItemStack stack) { - Object handle = null; - try { - handle = class_CraftItemStack_getHandleField.get(stack); - } catch (Throwable ex) { - handle = null; - } - return handle; - } - - public static Object getHandle(World world) { - if (world == null) { - return null; - } - Object handle = null; - try { - handle = class_CraftWorld_getHandleMethod.invoke(world); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return handle; - } - - public static Object getHandle(Entity entity) { - if (entity == null) { - return null; - } - Object handle = null; - try { - handle = class_CraftEntity_getHandleMethod.invoke(entity); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return handle; - } - - public static Object getHandle(org.bukkit.entity.LivingEntity entity) { - if (entity == null) { - return null; - } - Object handle = null; - try { - handle = class_CraftLivingEntity_getHandleMethod.invoke(entity); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return handle; - } - - public static boolean isDone(Chunk chunk) { - Object chunkHandle = getHandle(chunk); - boolean done = false; - try { - done = (Boolean) class_Chunk_doneField.get(chunkHandle); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return done; - } - - public static Object getHandle(Chunk chunk) { - Object handle = null; - try { - handle = class_CraftChunk_getHandleMethod.invoke(chunk); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return handle; - } - - public static Object getHandle(Player player) { - Object handle = null; - try { - handle = class_CraftPlayer_getHandleMethod.invoke(player); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return handle; - } - - protected static void sendPacket(Server server, Location source, Collection players, Object packet) throws Exception { - players = ((players != null && players.size() > 0) ? players : server.getOnlinePlayers()); - - int viewDistance = Bukkit.getServer().getViewDistance() * 16; - int viewDistanceSquared = viewDistance * viewDistance; - World sourceWorld = source.getWorld(); - for (Player player : players) { - Location location = player.getLocation(); - if (!location.getWorld().equals(sourceWorld)) { - continue; - } - if (location.distanceSquared(source) <= viewDistanceSquared) { - sendPacket(player, packet); - } - } - } - - protected static void sendPacket(Player player, Object packet) throws Exception { - Object playerHandle = getHandle(player); - Field connectionField = playerHandle.getClass().getField("playerConnection"); - Object connection = connectionField.get(playerHandle); - Method sendPacketMethod = connection.getClass().getMethod("sendPacket", class_Packet); - sendPacketMethod.invoke(connection, packet); - } - - public static int getFacing(BlockFace direction) { - int dir; - switch (direction) { - case SOUTH: - default: - dir = 0; - break; - case WEST: - dir = 1; - break; - case NORTH: - dir = 2; - break; - case EAST: - dir = 3; - break; - } - - return dir; - } - - public static Entity getBukkitEntity(Object entity) { - if (entity == null) { - return null; - } - try { - Method getMethod = entity.getClass().getMethod("getBukkitEntity"); - Object bukkitEntity = getMethod.invoke(entity); - if (!(bukkitEntity instanceof Entity)) { - return null; - } - return (Entity) bukkitEntity; - } catch (Throwable ex) { - ex.printStackTrace(); - } - - return null; - } - - public static Object getTag(Object mcItemStack) { - Object tag = null; - try { - tag = class_ItemStack_tagField.get(mcItemStack); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return tag; - } - - protected static Object getNMSCopy(ItemStack stack) { - Object nms = null; - try { - nms = class_CraftItemStack_copyMethod.invoke(null, stack); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return nms; - } - - public static ItemStack getCopy(ItemStack stack) { - if (stack == null) { - return null; - } - - try { - Object craft = getNMSCopy(stack); - stack = (ItemStack) class_CraftItemStack_mirrorMethod.invoke(null, craft); - } catch (Throwable ex) { - stack = null; - } - - return stack; - } - - public static ItemStack makeReal(ItemStack stack) { - if (stack == null) { - return null; - } - Object nmsStack = getHandle(stack); - if (nmsStack == null) { - stack = getCopy(stack); - nmsStack = getHandle(stack); - } - if (nmsStack == null) { - return null; - } - try { - Object tag = class_ItemStack_tagField.get(nmsStack); - if (tag == null) { - class_ItemStack_tagField.set(nmsStack, class_NBTTagCompound.newInstance()); - } - } catch (Throwable ex) { - ex.printStackTrace(); - return null; - } - - return stack; - } - - public static String getMeta(ItemStack stack, String tag, String defaultValue) { - String result = getMeta(stack, tag); - return result == null ? defaultValue : result; - } - - public static boolean hasMeta(ItemStack stack, String tag) { - return getNode(stack, tag) != null; - } - - public static Object getNode(ItemStack stack, String tag) { - if (stack == null) { - return null; - } - Object meta = null; - try { - Object craft = getHandle(stack); - if (craft == null) { - return null; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return null; - } - meta = class_NBTTagCompound_getMethod.invoke(tagObject, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static boolean containsNode(Object nbtBase, String tag) { - if (nbtBase == null) { - return false; - } - Boolean result = false; - try { - result = (Boolean) class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return result; - } - - public static Object getNode(Object nbtBase, String tag) { - if (nbtBase == null) { - return null; - } - Object meta = null; - try { - meta = class_NBTTagCompound_getMethod.invoke(nbtBase, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static Object createNode(Object nbtBase, String tag) { - if (nbtBase == null) { - return null; - } - Object meta = null; - try { - meta = class_NBTTagCompound_getCompoundMethod.invoke(nbtBase, tag); - class_NBTTagCompound_setMethod.invoke(nbtBase, tag, meta); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static Object createNode(ItemStack stack, String tag) { - if (stack == null) { - return null; - } - Object outputObject = getNode(stack, tag); - if (outputObject == null) { - try { - Object craft = getHandle(stack); - if (craft == null) { - return null; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return null; - } - outputObject = class_NBTTagCompound.newInstance(); - class_NBTTagCompound_setMethod.invoke(tagObject, tag, outputObject); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - return outputObject; - } - - public static String getMeta(Object node, String tag, String defaultValue) { - String meta = getMeta(node, tag); - return meta == null || meta.length() == 0 ? defaultValue : meta; - } - - public static String getMeta(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return null; - } - String meta = null; - try { - meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static Byte getMetaByte(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return null; - } - Byte meta = null; - try { - meta = (Byte) class_NBTTagCompound_getByteMethod.invoke(node, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static Integer getMetaInt(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return null; - } - Integer meta = null; - try { - meta = (Integer) class_NBTTagCompound_getIntMethod.invoke(node, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static void setMeta(Object node, String tag, String value) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return; - } - try { - if (value == null || value.length() == 0) { - class_NBTTagCompound_removeMethod.invoke(node, tag); - } else { - class_NBTTagCompound_setStringMethod.invoke(node, tag, value); - } - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static void removeMeta(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return; - } - try { - class_NBTTagCompound_removeMethod.invoke(node, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static void removeMeta(ItemStack stack, String tag) { - if (stack == null) { - return; - } - - try { - Object craft = getHandle(stack); - if (craft == null) { - return; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return; - } - removeMeta(tagObject, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static String getMeta(ItemStack stack, String tag) { - if (stack == null) { - return null; - } - String meta = null; - try { - Object craft = getHandle(stack); - if (craft == null) { - return null; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return null; - } - meta = (String) class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static void setMeta(ItemStack stack, String tag, String value) { - if (stack == null) { - return; - } - try { - Object craft = getHandle(stack); - if (craft == null) { - return; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return; - } - class_NBTTagCompound_setStringMethod.invoke(tagObject, tag, value); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static void addGlow(ItemStack stack) { - if (stack == null) { - return; - } - - try { - Object craft = getHandle(stack); - if (craft == null) { - return; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return; - } - final Object enchList = class_NBTTagList.newInstance(); - class_NBTTagCompound_setMethod.invoke(tagObject, "ench", enchList); - - // Testing Glow API based on ItemMetadata storage - Object bukkitData = createNode(stack, "bukkit"); - class_NBTTagCompound_setBooleanMethod.invoke(bukkitData, "glow", true); - } catch (Throwable ignored) { - - } - } - - public static void removeGlow(ItemStack stack) { - if (stack == null) { - return; - } - - Collection enchants = stack.getEnchantments().keySet(); - for (Enchantment enchant : enchants) { - stack.removeEnchantment(enchant); - } - - try { - Object craft = getHandle(stack); - if (craft == null) { - return; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return; - } - - // Testing Glow API based on ItemMetadata storage - Object bukkitData = getNode(stack, "bukkit"); - if (bukkitData != null) { - class_NBTTagCompound_setBooleanMethod.invoke(bukkitData, "glow", false); - } - } catch (Throwable ignored) { - - } - } - - public static void makeUnbreakable(ItemStack stack) { - if (stack == null) { - return; - } - - try { - Object craft = getHandle(stack); - if (craft == null) { - return; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return; - } - - Object unbreakableFlag = null; - if (class_NBTTagByte_constructor != null) { - unbreakableFlag = class_NBTTagByte_constructor.newInstance((byte) 1); - } else { - unbreakableFlag = class_NBTTagByte_legacy_constructor.newInstance("", (byte) 1); - } - class_NBTTagCompound_setMethod.invoke(tagObject, "Unbreakable", unbreakableFlag); - } catch (Throwable ignored) { - - } - } - - public static void removeUnbreakable(ItemStack stack) { - removeMeta(stack, "Unbreakable"); - } - - public static void hideFlags(ItemStack stack, byte flags) { - if (stack == null) { - return; - } - - try { - Object craft = getHandle(stack); - if (craft == null) { - return; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return; - } - - Object hideFlag = null; - if (class_NBTTagByte_constructor != null) { - hideFlag = class_NBTTagByte_constructor.newInstance(flags); - } else { - hideFlag = class_NBTTagByte_legacy_constructor.newInstance("", flags); - } - class_NBTTagCompound_setMethod.invoke(tagObject, "HideFlags", hideFlag); - } catch (Throwable ignored) { - - } - } - - public static boolean createExplosion(Entity entity, World world, double x, double y, double z, float power, boolean setFire, boolean breakBlocks) { - boolean result = false; - if (world == null) { - return false; - } - try { - Object worldHandle = getHandle(world); - if (worldHandle == null) { - return false; - } - Object entityHandle = entity == null ? null : getHandle(entity); - - Object explosion = class_World_explodeMethod.invoke(worldHandle, entityHandle, x, y, z, power, setFire, breakBlocks); - Field cancelledField = explosion.getClass().getDeclaredField("wasCanceled"); - result = (Boolean) cancelledField.get(explosion); - } catch (Throwable ex) { - ex.printStackTrace(); - result = false; - } - return result; - } - - public static void makeTemporary(ItemStack itemStack, String message) { - setMeta(itemStack, "temporary", message); - } - - public static boolean isTemporary(ItemStack itemStack) { - return hasMeta(itemStack, "temporary"); - } - - public static void makeUnplaceable(ItemStack itemStack) { - setMeta(itemStack, "unplaceable", "true"); - } - - public static boolean isUnplaceable(ItemStack itemStack) { - return hasMeta(itemStack, "unplaceable"); - } - - public static String getTemporaryMessage(ItemStack itemStack) { - return getMeta(itemStack, "temporary"); - } - - public static void setReplacement(ItemStack itemStack, ItemStack replacement) { - YamlConfiguration configuration = new YamlConfiguration(); - configuration.set("item", replacement); - setMeta(itemStack, "replacement", configuration.saveToString()); - } - - public static ItemStack getReplacement(ItemStack itemStack) { - String serialized = getMeta(itemStack, "replacement"); - if (serialized == null || serialized.isEmpty()) { - return null; - } - YamlConfiguration configuration = new YamlConfiguration(); - ItemStack replacement = null; - try { - configuration.loadFromString(serialized); - replacement = configuration.getItemStack("item"); - } catch (Exception ex) { - ex.printStackTrace(); - } - return replacement; - } - - protected static Object getTagString(String value) { - try { - if (class_NBTTagList_legacy_consructor != null) { - return class_NBTTagList_legacy_consructor.newInstance("", value); - } - return class_NBTTagList_consructor.newInstance(value); - } catch (Exception ex) { - ex.printStackTrace(); - - } - return null; - } - - public static Object setStringList(Object nbtBase, String tag, Collection values) { - if (nbtBase == null) { - return null; - } - Object listMeta = null; - try { - listMeta = class_NBTTagList.newInstance(); - - for (String value : values) { - Object nbtString = getTagString(value); - class_NBTTagList_addMethod.invoke(listMeta, nbtString); - } - - class_NBTTagCompound_setMethod.invoke(nbtBase, tag, listMeta); - } catch (Throwable ex) { - ex.printStackTrace(); - return null; - } - return listMeta; - } - - public static ItemStack getItem(Object itemTag) { - if (itemTag == null) { - return null; - } - ItemStack item = null; - try { - Object nmsStack = class_ItemStack_createStackMethod.invoke(null, itemTag); - item = (ItemStack) class_CraftItemStack_mirrorMethod.invoke(null, nmsStack); - } catch (Exception ex) { - ex.printStackTrace(); - } - return item; - } - - public static ItemStack[] getItems(Object rootTag, String tagName) { - try { - Object itemList = class_NBTTagCompound_getListMethod.invoke(rootTag, tagName, NBT_TYPE_COMPOUND); - Integer size = (Integer) class_NBTTagList_sizeMethod.invoke(itemList); - ItemStack[] items = new ItemStack[size]; - for (int i = 0; i < size; i++) { - try { - Object itemData = class_NBTTagList_getMethod.invoke(itemList, i); - if (itemData != null) { - items[i] = getItem(itemData); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - return items; - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static Object getTileEntityData(Location location) { - Object data = null; - try { - World world = location.getWorld(); - Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (tileEntity != null) { - data = class_NBTTagCompound.newInstance(); - class_TileEntity_saveMethod.invoke(tileEntity, data); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return data; - } - - public static Object getTileEntity(Location location) { - Object tileEntity = null; - try { - World world = location.getWorld(); - tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } catch (Exception ex) { - ex.printStackTrace(); - } - return tileEntity; - } - - public static void clearItems(Location location) { - if (location == null) { - return; - } - try { - World world = location.getWorld(); - if (world == null) { - return; - } - - Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (tileEntity != null) { - Object entityData = class_NBTTagCompound.newInstance(); - class_TileEntity_saveMethod.invoke(tileEntity, entityData); - Object itemList = class_NBTTagCompound_getListMethod.invoke(entityData, "Items", NBT_TYPE_COMPOUND); - if (itemList != null) { - List items = (List) class_NBTTagList_list.get(itemList); - items.clear(); - class_TileEntity_loadMethod.invoke(tileEntity, entityData); - class_TileEntity_updateMethod.invoke(tileEntity); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static void setTileEntityData(Location location, Object data) { - if (location == null || data == null) { - return; - } - try { - World world = location.getWorld(); - if (world == null) { - return; - } - - Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (tileEntity == null) { - return; - } - - class_NBTTagCompound_setIntMethod.invoke(data, "x", location.getBlockX()); - class_NBTTagCompound_setIntMethod.invoke(data, "y", location.getBlockY()); - class_NBTTagCompound_setIntMethod.invoke(data, "z", location.getBlockZ()); - - class_TileEntity_loadMethod.invoke(tileEntity, data); - class_TileEntity_updateMethod.invoke(tileEntity); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Vector getPosition(Object entityData, String tag) { - try { - Object posList = class_NBTTagCompound_getListMethod.invoke(entityData, tag, NBT_TYPE_DOUBLE); - Double x = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 0); - Double y = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 1); - Double z = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 2); - if (x != null && y != null && z != null) { - return new Vector(x, y, z); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static Entity getEntity(World world, UUID uuid) { - try { - Object worldHandle = getHandle(world); - final Map entityMap = (Map) class_WorldServer_entitiesByUUIDField.get(worldHandle); - if (entityMap != null) { - Object nmsEntity = entityMap.get(uuid); - if (nmsEntity != null) { - return getBukkitEntity(nmsEntity); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setEnvironment(World world, World.Environment environment) { - try { - class_CraftWorld_environmentField.set(world, environment); - } catch (Exception ex) { - ex.printStackTrace(); - } - } -} diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java deleted file mode 100644 index 5a59bf6..0000000 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java +++ /dev/null @@ -1,1963 +0,0 @@ -package me.skymc.taboolib.nms; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.*; -import org.bukkit.block.BlockFace; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.MemorySection; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.util.Vector; - -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.*; -import java.util.logging.Level; - -/** - * @author Unknown - */ -@SuppressWarnings({"rawtypes", "unchecked"}) -public class NMSUtil19 { - - protected static boolean failed = false; - protected static boolean legacy = false; - - protected static String versionPrefix = ""; - - protected final static int NBT_TYPE_COMPOUND = 10; - protected final static int NBT_TYPE_INT_ARRAY = 11; - protected final static int NBT_TYPE_DOUBLE = 6; - protected final static int NBT_TYPE_FLOAT = 5; - protected final static int NBT_TYPE_STRING = 8; - - protected static int WITHER_SKULL_TYPE = 66; - protected static int FIREWORK_TYPE = 76; - - public static Class class_Block; - public static Class class_ItemStack; - public static Class class_NBTBase; - public static Class class_NBTTagCompound; - public static Class class_NBTTagList; - public static Class class_NBTTagByte; - public static Class class_NBTTagDouble; - public static Class class_NBTTagFloat; - public static Class class_NBTTagInt; - public static Class class_NBTTagLong; - public static Class class_NBTTagShort; - public static Class class_NBTTagString; - public static Class class_CraftTask; - public static Class class_CraftInventoryCustom; - public static Class class_CraftItemStack; - public static Class class_CraftBlockState; - public static Class class_CraftLivingEntity; - public static Class class_CraftWorld; - public static Class class_Consumer; - public static Class class_Entity; - public static Class class_EntityCreature; - public static Class class_EntityLiving; - public static Class class_EntityHuman; - public static Class class_DataWatcher; - public static Class class_DamageSource; - public static Class class_EntityDamageSource; - public static Class class_World; - public static Class class_WorldServer; - public static Class class_Packet; - protected static Class class_EnumSkyBlock; - public static Class class_EntityPainting; - public static Class class_EntityItemFrame; - public static Class class_EntityMinecartRideable; - public static Class class_EntityTNTPrimed; - public static Class class_AxisAlignedBB; - public static Class class_PathPoint; - public static Class class_PathEntity; - public static Class class_EntityFirework; - public static Class class_CraftSkull; - public static Class class_CraftBanner; - public static Class class_CraftMetaSkull; - public static Class class_CraftMetaBanner; - public static Class class_GameProfile; - public static Class class_GameProfileProperty; - public static Class class_BlockPosition; - public static Class class_NBTCompressedStreamTools; - public static Class class_TileEntity; - public static Class class_TileEntitySign; - public static Class class_TileEntityContainer; - public static Class class_ChestLock; - protected static Class class_EnumDirection; - public static Class class_EntityHorse; - public static Class class_EntityWitherSkull; - public static Class class_PacketPlayOutAttachEntity; - public static Class class_PacketPlayOutEntityDestroy; - public static Class class_PacketPlayOutSpawnEntity; - public static Class class_PacketPlayOutSpawnEntityLiving; - public static Class class_PacketPlayOutEntityMetadata; - public static Class class_PacketPlayOutEntityStatus; - public static Class class_PacketPlayOutCustomSoundEffect; - public static Class class_PacketPlayOutExperience; - public static Class class_PacketPlayOutAnimation; - public static Class class_PacketPlayOutBlockBreakAnimation; - protected static Enum enum_SoundCategory_PLAYERS; - protected static Class class_EnumSoundCategory; - public static Class class_EntityFallingBlock; - public static Class class_EntityArmorStand; - public static Class class_EntityPlayer; - public static Class class_PlayerConnection; - public static Class class_Chunk; - public static Class class_CraftPlayer; - public static Class class_CraftChunk; - public static Class class_CraftEntity; - public static Class class_EntityProjectile; - public static Class class_EntityFireball; - public static Class class_EntityArrow; - public static Class class_CraftArrow; - public static Class class_MinecraftServer; - public static Class class_CraftServer; - public static Class class_DataWatcherObject; - public static Class class_PacketPlayOutChat; - protected static Class class_ChatMessageType; - protected static Enum enum_ChatMessageType_GAME_INFO; - public static Class class_ChatComponentText; - public static Class class_IChatBaseComponent; - - protected static Method class_NBTTagList_addMethod; - protected static Method class_NBTTagList_getMethod; - protected static Method class_NBTTagList_getDoubleMethod; - protected static Method class_NBTTagList_sizeMethod; - protected static Method class_NBTTagList_removeMethod; - protected static Method class_NBTTagCompound_getKeysMethod; - protected static Method class_NBTTagCompound_setMethod; - protected static Method class_World_getEntitiesMethod; - protected static Method class_Entity_setSilentMethod; - protected static Method class_Entity_isSilentMethod; - protected static Method class_Entity_setYawPitchMethod; - protected static Method class_Entity_getBukkitEntityMethod; - protected static Method class_EntityLiving_damageEntityMethod; - protected static Method class_DamageSource_getMagicSourceMethod; - protected static Method class_EntityDamageSource_setThornsMethod; - protected static Method class_World_explodeMethod; - protected static Method class_NBTTagCompound_setBooleanMethod; - protected static Method class_NBTTagCompound_setStringMethod; - protected static Method class_NBTTagCompound_setDoubleMethod; - protected static Method class_NBTTagCompound_setLongMethod; - protected static Method class_NBTTagCompound_setIntMethod; - protected static Method class_NBTTagCompound_removeMethod; - protected static Method class_NBTTagCompound_getStringMethod; - protected static Method class_NBTTagCompound_getBooleanMethod; - protected static Method class_NBTTagCompound_getIntMethod; - protected static Method class_NBTTagCompound_getByteMethod; - protected static Method class_NBTTagCompound_getMethod; - protected static Method class_NBTTagCompound_getCompoundMethod; - protected static Method class_NBTTagCompound_getShortMethod; - protected static Method class_NBTTagCompound_getByteArrayMethod; - protected static Method class_NBTTagCompound_getListMethod; - protected static Method class_Entity_saveMethod; - protected static Method class_Entity_getTypeMethod; - protected static Method class_TileEntity_loadMethod; - protected static Method class_TileEntity_saveMethod; - protected static Method class_TileEntity_updateMethod; - protected static Method class_World_addEntityMethod; - protected static Method class_CraftMetaBanner_getPatternsMethod; - protected static Method class_CraftMetaBanner_setPatternsMethod; - protected static Method class_CraftMetaBanner_getBaseColorMethod; - protected static Method class_CraftMetaBanner_setBaseColorMethod; - protected static Method class_CraftBanner_getPatternsMethod; - protected static Method class_CraftBanner_setPatternsMethod; - protected static Method class_CraftBanner_getBaseColorMethod; - protected static Method class_CraftBanner_setBaseColorMethod; - protected static Method class_NBTCompressedStreamTools_loadFileMethod; - protected static Method class_CraftItemStack_asBukkitCopyMethod; - protected static Method class_CraftItemStack_copyMethod; - protected static Method class_CraftItemStack_mirrorMethod; - protected static Method class_NBTTagCompound_hasKeyMethod; - protected static Method class_CraftWorld_getTileEntityAtMethod; - protected static Method class_CraftWorld_createEntityMethod; - protected static Method class_CraftWorld_spawnMethod; - protected static boolean class_CraftWorld_spawnMethod_isLegacy; - protected static Method class_Entity_setLocationMethod; - protected static Method class_Entity_getIdMethod; - protected static Method class_Entity_getDataWatcherMethod; - protected static Method class_Entity_getBoundingBox; - protected static Method class_TileEntityContainer_setLock; - protected static Method class_TileEntityContainer_getLock; - protected static Method class_ChestLock_isEmpty; - protected static Method class_ChestLock_getString; - protected static Method class_ArmorStand_setInvisible; - protected static Method class_ArmorStand_setGravity; - protected static Method class_Entity_setNoGravity; - protected static Method class_CraftPlayer_getHandleMethod; - protected static Method class_CraftChunk_getHandleMethod; - protected static Method class_CraftEntity_getHandleMethod; - protected static Method class_CraftLivingEntity_getHandleMethod; - protected static Method class_CraftWorld_getHandleMethod; - protected static Method class_EntityPlayer_openSignMethod; - protected static Method class_EntityPlayer_setResourcePackMethod; - protected static Method class_CraftServer_getServerMethod; - protected static Method class_MinecraftServer_getResourcePackMethod; - protected static Method class_ItemStack_isEmptyMethod; - protected static Method class_ItemStack_createStackMethod; - protected static Method class_CraftMagicNumbers_getBlockMethod; - - protected static Constructor class_CraftInventoryCustom_constructor; - protected static Constructor class_EntityFireworkConstructor; - protected static Constructor class_EntityPaintingConstructor; - protected static Constructor class_EntityItemFrameConstructor; - protected static Constructor class_BlockPosition_Constructor; - protected static Constructor class_PacketSpawnEntityConstructor; - protected static Constructor class_PacketSpawnLivingEntityConstructor; - protected static Constructor class_PacketPlayOutEntityMetadata_Constructor; - protected static Constructor class_PacketPlayOutEntityStatus_Constructor; - protected static Constructor class_PacketPlayOutEntityDestroy_Constructor; - protected static Constructor class_PacketPlayOutCustomSoundEffect_Constructor; - protected static Constructor class_PacketPlayOutExperience_Constructor; - protected static Constructor class_PacketPlayOutAnimation_Constructor; - protected static Constructor class_PacketPlayOutBlockBreakAnimation_Constructor; - protected static Constructor class_ChestLock_Constructor; - protected static Constructor class_AxisAlignedBB_Constructor; - protected static Constructor class_ItemStack_consructor; - protected static Constructor class_NBTTagString_consructor; - protected static Constructor class_NBTTagByte_constructor; - protected static Constructor class_NBTTagDouble_constructor; - protected static Constructor class_NBTTagInt_constructor; - protected static Constructor class_NBTTagFloat_constructor; - protected static Constructor class_NBTTagLong_constructor; - protected static Constructor class_PacketPlayOutChat_constructor; - protected static Constructor class_ChatComponentText_constructor; - - protected static Field class_Entity_invulnerableField; - protected static Field class_Entity_motXField; - protected static Field class_Entity_motYField; - protected static Field class_Entity_motZField; - protected static Field class_WorldServer_entitiesByUUIDField; - protected static Field class_ItemStack_tagField; - protected static Field class_DamageSource_MagicField; - protected static Field class_Firework_ticksFlownField; - protected static Field class_Firework_expectedLifespanField; - protected static Field class_CraftSkull_profile; - protected static Field class_CraftMetaSkull_profile; - protected static Field class_GameProfile_properties; - protected static Field class_GameProfileProperty_value; - protected static Field class_EntityTNTPrimed_source; - protected static Field class_NBTTagList_list; - protected static Field class_AxisAlignedBB_minXField; - protected static Field class_AxisAlignedBB_minYField; - protected static Field class_AxisAlignedBB_minZField; - protected static Field class_AxisAlignedBB_maxXField; - protected static Field class_AxisAlignedBB_maxYField; - protected static Field class_AxisAlignedBB_maxZField; - protected static Field class_EntityFallingBlock_hurtEntitiesField; - protected static Field class_EntityFallingBlock_fallHurtMaxField; - protected static Field class_EntityFallingBlock_fallHurtAmountField; - protected static Field class_EntityArmorStand_disabledSlotsField; - protected static Field class_EntityPlayer_playerConnectionField; - protected static Field class_PlayerConnection_floatCountField; - protected static Field class_Chunk_doneField; - protected static Field class_CraftItemStack_getHandleField; - protected static Field class_EntityArrow_lifeField = null; - protected static Field class_EntityArrow_damageField; - protected static Field class_CraftWorld_environmentField; - protected static Field class_MemorySection_mapField; - protected static Field class_NBTTagByte_dataField; - protected static Field class_NBTTagDouble_dataField; - protected static Field class_NBTTagFloat_dataField; - protected static Field class_NBTTagInt_dataField; - protected static Field class_NBTTagLong_dataField; - protected static Field class_NBTTagShort_dataField; - protected static Field class_NBTTagString_dataField; - protected static Field class_Block_durabilityField; - protected static Field class_Entity_jumpingField; - protected static Field class_Entity_moveStrafingField; - protected static Field class_Entity_moveForwardField; - - static { - // Find classes Bukkit hides from us. :-D - // Much thanks to @DPOHVAR for sharing the PowerNBT code that powers the reflection approach. - String className = Bukkit.getServer().getClass().getName(); - String[] packages = StringUtils.split(className, '.'); - if (packages.length == 5) { - versionPrefix = packages[3] + "."; - } - - try { - class_Block = fixBukkitClass("net.minecraft.server.Block"); - class_Entity = fixBukkitClass("net.minecraft.server.Entity"); - class_EntityLiving = fixBukkitClass("net.minecraft.server.EntityLiving"); - class_EntityHuman = fixBukkitClass("net.minecraft.server.EntityHuman"); - class_ItemStack = fixBukkitClass("net.minecraft.server.ItemStack"); - class_DataWatcher = fixBukkitClass("net.minecraft.server.DataWatcher"); - class_DataWatcherObject = fixBukkitClass("net.minecraft.server.DataWatcherObject"); - class_NBTBase = fixBukkitClass("net.minecraft.server.NBTBase"); - class_NBTTagCompound = fixBukkitClass("net.minecraft.server.NBTTagCompound"); - class_NBTTagList = fixBukkitClass("net.minecraft.server.NBTTagList"); - class_NBTTagString = fixBukkitClass("net.minecraft.server.NBTTagString"); - class_NBTTagByte = fixBukkitClass("net.minecraft.server.NBTTagByte"); - class_NBTTagDouble = fixBukkitClass("net.minecraft.server.NBTTagDouble"); - class_NBTTagFloat = fixBukkitClass("net.minecraft.server.NBTTagFloat"); - class_NBTTagInt = fixBukkitClass("net.minecraft.server.NBTTagInt"); - class_NBTTagLong = fixBukkitClass("net.minecraft.server.NBTTagLong"); - class_NBTTagShort = fixBukkitClass("net.minecraft.server.NBTTagShort"); - class_CraftWorld = fixBukkitClass("org.bukkit.craftbukkit.CraftWorld"); - class_CraftInventoryCustom = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftInventoryCustom"); - class_CraftItemStack = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftItemStack"); - class_CraftBlockState = fixBukkitClass("org.bukkit.craftbukkit.block.CraftBlockState"); - class_CraftTask = fixBukkitClass("org.bukkit.craftbukkit.scheduler.CraftTask"); - class_CraftLivingEntity = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftLivingEntity"); - class_Packet = fixBukkitClass("net.minecraft.server.Packet"); - class_World = fixBukkitClass("net.minecraft.server.World"); - class_WorldServer = fixBukkitClass("net.minecraft.server.WorldServer"); - class_EnumSkyBlock = (Class) fixBukkitClass("net.minecraft.server.EnumSkyBlock"); - class_EnumSoundCategory = (Class) fixBukkitClass("net.minecraft.server.SoundCategory"); - enum_SoundCategory_PLAYERS = NMSUtils.getEnumSilent(class_EnumSoundCategory, "PLAYERS"); - class_EntityPainting = fixBukkitClass("net.minecraft.server.EntityPainting"); - class_EntityCreature = fixBukkitClass("net.minecraft.server.EntityCreature"); - class_EntityItemFrame = fixBukkitClass("net.minecraft.server.EntityItemFrame"); - class_EntityMinecartRideable = fixBukkitClass("net.minecraft.server.EntityMinecartRideable"); - class_EntityTNTPrimed = fixBukkitClass("net.minecraft.server.EntityTNTPrimed"); - class_AxisAlignedBB = fixBukkitClass("net.minecraft.server.AxisAlignedBB"); - class_DamageSource = fixBukkitClass("net.minecraft.server.DamageSource"); - class_EntityDamageSource = fixBukkitClass("net.minecraft.server.EntityDamageSource"); - class_PathEntity = fixBukkitClass("net.minecraft.server.PathEntity"); - class_PathPoint = fixBukkitClass("net.minecraft.server.PathPoint"); - class_EntityFirework = fixBukkitClass("net.minecraft.server.EntityFireworks"); - class_CraftSkull = fixBukkitClass("org.bukkit.craftbukkit.block.CraftSkull"); - class_CraftMetaSkull = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftMetaSkull"); - class_NBTCompressedStreamTools = fixBukkitClass("net.minecraft.server.NBTCompressedStreamTools"); - class_TileEntity = fixBukkitClass("net.minecraft.server.TileEntity"); - class_EntityHorse = fixBukkitClass("net.minecraft.server.EntityHorse"); - class_EntityWitherSkull = fixBukkitClass("net.minecraft.server.EntityWitherSkull"); - class_PacketPlayOutAttachEntity = fixBukkitClass("net.minecraft.server.PacketPlayOutAttachEntity"); - class_PacketPlayOutEntityDestroy = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityDestroy"); - class_PacketPlayOutSpawnEntity = fixBukkitClass("net.minecraft.server.PacketPlayOutSpawnEntity"); - class_PacketPlayOutSpawnEntityLiving = fixBukkitClass("net.minecraft.server.PacketPlayOutSpawnEntityLiving"); - class_PacketPlayOutEntityMetadata = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityMetadata"); - class_PacketPlayOutEntityStatus = fixBukkitClass("net.minecraft.server.PacketPlayOutEntityStatus"); - class_PacketPlayOutCustomSoundEffect = fixBukkitClass("net.minecraft.server.PacketPlayOutCustomSoundEffect"); - class_PacketPlayOutExperience = fixBukkitClass("net.minecraft.server.PacketPlayOutExperience"); - class_PacketPlayOutAnimation = fixBukkitClass("net.minecraft.server.PacketPlayOutAnimation"); - class_PacketPlayOutBlockBreakAnimation = fixBukkitClass("net.minecraft.server.PacketPlayOutBlockBreakAnimation"); - class_EntityFallingBlock = fixBukkitClass("net.minecraft.server.EntityFallingBlock"); - class_EntityArmorStand = fixBukkitClass("net.minecraft.server.EntityArmorStand"); - class_EntityPlayer = fixBukkitClass("net.minecraft.server.EntityPlayer"); - class_PlayerConnection = fixBukkitClass("net.minecraft.server.PlayerConnection"); - class_Chunk = fixBukkitClass("net.minecraft.server.Chunk"); - class_CraftPlayer = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftPlayer"); - class_CraftChunk = fixBukkitClass("org.bukkit.craftbukkit.CraftChunk"); - class_CraftEntity = fixBukkitClass("org.bukkit.craftbukkit.entity.CraftEntity"); - class_TileEntitySign = fixBukkitClass("net.minecraft.server.TileEntitySign"); - class_CraftServer = fixBukkitClass("org.bukkit.craftbukkit.CraftServer"); - class_MinecraftServer = fixBukkitClass("net.minecraft.server.MinecraftServer"); - class_BlockPosition = fixBukkitClass("net.minecraft.server.BlockPosition"); - - class_EntityProjectile = NMSUtil19.getBukkitClass("net.minecraft.server.EntityProjectile"); - class_EntityFireball = NMSUtil19.getBukkitClass("net.minecraft.server.EntityFireball"); - class_EntityArrow = NMSUtil19.getBukkitClass("net.minecraft.server.EntityArrow"); - class_CraftArrow = NMSUtil19.getBukkitClass("org.bukkit.craftbukkit.entity.CraftArrow"); - - class_Entity_getBukkitEntityMethod = class_Entity.getMethod("getBukkitEntity"); - class_Entity_setYawPitchMethod = class_Entity.getDeclaredMethod("setYawPitch", Float.TYPE, Float.TYPE); - class_Entity_setYawPitchMethod.setAccessible(true); - class_World_explodeMethod = class_World.getMethod("createExplosion", class_Entity, Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPE, Boolean.TYPE); - class_NBTTagCompound_setBooleanMethod = class_NBTTagCompound.getMethod("setBoolean", String.class, Boolean.TYPE); - class_NBTTagCompound_setStringMethod = class_NBTTagCompound.getMethod("setString", String.class, String.class); - class_NBTTagCompound_setDoubleMethod = class_NBTTagCompound.getMethod("setDouble", String.class, Double.TYPE); - class_NBTTagCompound_setLongMethod = class_NBTTagCompound.getMethod("setLong", String.class, Long.TYPE); - class_NBTTagCompound_setIntMethod = class_NBTTagCompound.getMethod("setInt", String.class, Integer.TYPE); - class_NBTTagCompound_removeMethod = class_NBTTagCompound.getMethod("remove", String.class); - class_NBTTagCompound_getStringMethod = class_NBTTagCompound.getMethod("getString", String.class); - class_NBTTagCompound_getShortMethod = class_NBTTagCompound.getMethod("getShort", String.class); - class_NBTTagCompound_getIntMethod = class_NBTTagCompound.getMethod("getInt", String.class); - class_NBTTagCompound_getBooleanMethod = class_NBTTagCompound.getMethod("getBoolean", String.class); - class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class); - class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class); - class_NBTTagCompound_getListMethod = class_NBTTagCompound.getMethod("getList", String.class, Integer.TYPE); - class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", ItemStack.class); - class_CraftItemStack_asBukkitCopyMethod = class_CraftItemStack.getMethod("asBukkitCopy", class_ItemStack); - class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack); - class_World_addEntityMethod = class_World.getMethod("addEntity", class_Entity, CreatureSpawnEvent.SpawnReason.class); - class_Entity_setLocationMethod = class_Entity.getMethod("setLocation", Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Float.TYPE); - class_Entity_getIdMethod = class_Entity.getMethod("getId"); - class_Entity_getDataWatcherMethod = class_Entity.getMethod("getDataWatcher"); - class_ArmorStand_setInvisible = class_EntityArmorStand.getDeclaredMethod("setInvisible", Boolean.TYPE); - class_CraftPlayer_getHandleMethod = class_CraftPlayer.getMethod("getHandle"); - class_CraftChunk_getHandleMethod = class_CraftChunk.getMethod("getHandle"); - class_CraftEntity_getHandleMethod = class_CraftEntity.getMethod("getHandle"); - class_CraftLivingEntity_getHandleMethod = class_CraftLivingEntity.getMethod("getHandle"); - class_CraftWorld_getHandleMethod = class_CraftWorld.getMethod("getHandle"); - class_EntityPlayer_openSignMethod = class_EntityPlayer.getMethod("openSign", class_TileEntitySign); - class_EntityPlayer_setResourcePackMethod = class_EntityPlayer.getMethod("setResourcePack", String.class, String.class); - class_CraftServer_getServerMethod = class_CraftServer.getMethod("getServer"); - class_MinecraftServer_getResourcePackMethod = class_MinecraftServer.getMethod("getResourcePack"); - - class_CraftInventoryCustom_constructor = class_CraftInventoryCustom.getConstructor(InventoryHolder.class, Integer.TYPE, String.class); - class_EntityFireworkConstructor = class_EntityFirework.getConstructor(class_World, Double.TYPE, Double.TYPE, Double.TYPE, class_ItemStack); - class_PacketSpawnEntityConstructor = class_PacketPlayOutSpawnEntity.getConstructor(class_Entity, Integer.TYPE); - class_PacketSpawnLivingEntityConstructor = class_PacketPlayOutSpawnEntityLiving.getConstructor(class_EntityLiving); - class_PacketPlayOutEntityMetadata_Constructor = class_PacketPlayOutEntityMetadata.getConstructor(Integer.TYPE, class_DataWatcher, Boolean.TYPE); - class_PacketPlayOutEntityStatus_Constructor = class_PacketPlayOutEntityStatus.getConstructor(class_Entity, Byte.TYPE); - class_PacketPlayOutEntityDestroy_Constructor = class_PacketPlayOutEntityDestroy.getConstructor(int[].class); - class_PacketPlayOutCustomSoundEffect_Constructor = class_PacketPlayOutCustomSoundEffect.getConstructor(String.class, class_EnumSoundCategory, Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Float.TYPE); - class_PacketPlayOutExperience_Constructor = class_PacketPlayOutExperience.getConstructor(Float.TYPE, Integer.TYPE, Integer.TYPE); - class_PacketPlayOutAnimation_Constructor = class_PacketPlayOutAnimation.getConstructor(class_Entity, Integer.TYPE); - class_PacketPlayOutBlockBreakAnimation_Constructor = class_PacketPlayOutBlockBreakAnimation.getConstructor(Integer.TYPE, class_BlockPosition, Integer.TYPE); - - class_CraftWorld_environmentField = class_CraftWorld.getDeclaredField("environment"); - class_CraftWorld_environmentField.setAccessible(true); - class_Entity_invulnerableField = class_Entity.getDeclaredField("invulnerable"); - class_Entity_invulnerableField.setAccessible(true); - class_Entity_motXField = class_Entity.getDeclaredField("motX"); - class_Entity_motXField.setAccessible(true); - class_Entity_motYField = class_Entity.getDeclaredField("motY"); - class_Entity_motYField.setAccessible(true); - class_Entity_motZField = class_Entity.getDeclaredField("motZ"); - class_Entity_motZField.setAccessible(true); - class_ItemStack_tagField = class_ItemStack.getDeclaredField("tag"); - class_ItemStack_tagField.setAccessible(true); - class_EntityTNTPrimed_source = class_EntityTNTPrimed.getDeclaredField("source"); - class_EntityTNTPrimed_source.setAccessible(true); - class_AxisAlignedBB_minXField = class_AxisAlignedBB.getField("a"); - class_AxisAlignedBB_minYField = class_AxisAlignedBB.getField("b"); - class_AxisAlignedBB_minZField = class_AxisAlignedBB.getField("c"); - class_AxisAlignedBB_maxXField = class_AxisAlignedBB.getField("d"); - class_AxisAlignedBB_maxYField = class_AxisAlignedBB.getField("e"); - class_AxisAlignedBB_maxZField = class_AxisAlignedBB.getField("f"); - class_EntityPlayer_playerConnectionField = class_EntityPlayer.getDeclaredField("playerConnection"); - - class_Firework_ticksFlownField = class_EntityFirework.getDeclaredField("ticksFlown"); - class_Firework_ticksFlownField.setAccessible(true); - class_Firework_expectedLifespanField = class_EntityFirework.getDeclaredField("expectedLifespan"); - class_Firework_expectedLifespanField.setAccessible(true); - - class_NBTTagString_consructor = class_NBTTagString.getConstructor(String.class); - class_NBTTagByte_constructor = class_NBTTagByte.getConstructor(Byte.TYPE); - class_NBTTagDouble_constructor = class_NBTTagDouble.getConstructor(Double.TYPE); - class_NBTTagInt_constructor = class_NBTTagInt.getConstructor(Integer.TYPE); - class_NBTTagFloat_constructor = class_NBTTagFloat.getConstructor(Float.TYPE); - class_NBTTagLong_constructor = class_NBTTagLong.getConstructor(Long.TYPE); - - class_NBTTagList_list = class_NBTTagList.getDeclaredField("list"); - class_NBTTagList_list.setAccessible(true); - class_NBTTagByte_dataField = class_NBTTagByte.getDeclaredField("data"); - class_NBTTagByte_dataField.setAccessible(true); - class_NBTTagDouble_dataField = class_NBTTagDouble.getDeclaredField("data"); - class_NBTTagDouble_dataField.setAccessible(true); - class_NBTTagFloat_dataField = class_NBTTagFloat.getDeclaredField("data"); - class_NBTTagFloat_dataField.setAccessible(true); - class_NBTTagInt_dataField = class_NBTTagInt.getDeclaredField("data"); - class_NBTTagInt_dataField.setAccessible(true); - class_NBTTagLong_dataField = class_NBTTagLong.getDeclaredField("data"); - class_NBTTagLong_dataField.setAccessible(true); - class_NBTTagShort_dataField = class_NBTTagShort.getDeclaredField("data"); - class_NBTTagShort_dataField.setAccessible(true); - class_NBTTagString_dataField = class_NBTTagString.getDeclaredField("data"); - class_NBTTagString_dataField.setAccessible(true); - class_NBTTagCompound_getKeysMethod = class_NBTTagCompound.getMethod("c"); - class_NBTTagList_addMethod = class_NBTTagList.getMethod("add", class_NBTBase); - class_NBTTagList_getMethod = class_NBTTagList.getMethod("get", Integer.TYPE); - class_NBTTagList_sizeMethod = class_NBTTagList.getMethod("size"); - class_NBTTagList_removeMethod = class_NBTTagList.getMethod("remove", Integer.TYPE); - class_NBTTagCompound_setMethod = class_NBTTagCompound.getMethod("set", String.class, class_NBTBase); - class_NBTTagCompound_hasKeyMethod = class_NBTTagCompound.getMethod("hasKey", String.class); - class_NBTTagCompound_getMethod = class_NBTTagCompound.getMethod("get", String.class); - class_NBTTagCompound_getCompoundMethod = class_NBTTagCompound.getMethod("getCompound", String.class); - - class_EntityFallingBlock_hurtEntitiesField = class_EntityFallingBlock.getDeclaredField("hurtEntities"); - class_EntityFallingBlock_hurtEntitiesField.setAccessible(true); - class_EntityFallingBlock_fallHurtAmountField = class_EntityFallingBlock.getDeclaredField("fallHurtAmount"); - class_EntityFallingBlock_fallHurtAmountField.setAccessible(true); - class_EntityFallingBlock_fallHurtMaxField = class_EntityFallingBlock.getDeclaredField("fallHurtMax"); - class_EntityFallingBlock_fallHurtMaxField.setAccessible(true); - - class_Chunk_doneField = class_Chunk.getDeclaredField("done"); - class_Chunk_doneField.setAccessible(true); - class_CraftItemStack_getHandleField = class_CraftItemStack.getDeclaredField("handle"); - class_CraftItemStack_getHandleField.setAccessible(true); - - class_MemorySection_mapField = MemorySection.class.getDeclaredField("map"); - class_MemorySection_mapField.setAccessible(true); - - class_TileEntityContainer = fixBukkitClass("net.minecraft.server.TileEntityContainer"); - class_ChestLock = fixBukkitClass("net.minecraft.server.ChestLock"); - class_Entity_getBoundingBox = class_Entity.getMethod("getBoundingBox"); - class_GameProfile = getClass("com.mojang.authlib.GameProfile"); - class_GameProfileProperty = getClass("com.mojang.authlib.properties.Property"); - class_CraftSkull_profile = class_CraftSkull.getDeclaredField("profile"); - class_CraftSkull_profile.setAccessible(true); - class_CraftMetaSkull_profile = class_CraftMetaSkull.getDeclaredField("profile"); - class_CraftMetaSkull_profile.setAccessible(true); - class_GameProfile_properties = class_GameProfile.getDeclaredField("properties"); - class_GameProfile_properties.setAccessible(true); - class_GameProfileProperty_value = class_GameProfileProperty.getDeclaredField("value"); - class_GameProfileProperty_value.setAccessible(true); - - class_CraftMetaBanner = fixBukkitClass("org.bukkit.craftbukkit.inventory.CraftMetaBanner"); - class_CraftMetaBanner_getBaseColorMethod = class_CraftMetaBanner.getMethod("getBaseColor"); - class_CraftMetaBanner_getPatternsMethod = class_CraftMetaBanner.getMethod("getPatterns"); - class_CraftMetaBanner_setPatternsMethod = class_CraftMetaBanner.getMethod("setPatterns", List.class); - class_CraftMetaBanner_setBaseColorMethod = class_CraftMetaBanner.getMethod("setBaseColor", DyeColor.class); - - class_CraftBanner = fixBukkitClass("org.bukkit.craftbukkit.block.CraftBanner"); - class_CraftBanner_getBaseColorMethod = class_CraftBanner.getMethod("getBaseColor"); - class_CraftBanner_getPatternsMethod = class_CraftBanner.getMethod("getPatterns"); - class_CraftBanner_setPatternsMethod = class_CraftBanner.getMethod("setPatterns", List.class); - class_CraftBanner_setBaseColorMethod = class_CraftBanner.getMethod("setBaseColor", DyeColor.class); - - class_EnumDirection = (Class) fixBukkitClass("net.minecraft.server.EnumDirection"); - class_BlockPosition_Constructor = class_BlockPosition.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE); - class_EntityPaintingConstructor = class_EntityPainting.getConstructor(class_World, class_BlockPosition, class_EnumDirection); - class_EntityItemFrameConstructor = class_EntityItemFrame.getConstructor(class_World, class_BlockPosition, class_EnumDirection); - - // TODO: Server.getEntity(UUID) in 1.11+ - class_WorldServer_entitiesByUUIDField = class_WorldServer.getDeclaredField("entitiesByUUID"); - class_WorldServer_entitiesByUUIDField.setAccessible(true); - - // TODO: World.getNearbyEntities in 1.11+ - class_AxisAlignedBB_Constructor = class_AxisAlignedBB.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE, Double.TYPE); - class_World_getEntitiesMethod = class_World.getMethod("getEntities", class_Entity, class_AxisAlignedBB); - - // We don't want to consider new-ish builds as "legacy" and print a warning, so keep a separate flag - boolean current = true; - - // Particularly volatile methods that we can live without - try { - try { - // 1.12 - class_NBTTagList_getDoubleMethod = class_NBTTagList.getMethod("f", Integer.TYPE); - if (class_NBTTagList_getDoubleMethod.getReturnType() != Double.TYPE) { - throw new Exception("Not 1.12"); - } - } catch (Throwable not12) { - // 1.11 and lower - current = false; - class_NBTTagList_getDoubleMethod = class_NBTTagList.getMethod("e", Integer.TYPE); - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred while registering NBTTagList.getDouble, loading entities from schematics will not work"); - class_NBTTagList_getDoubleMethod = null; - } - - try { - // 1.12 - try { - if (!current) { - throw new Exception("Not 1.12"); - } - class_Entity_jumpingField = class_EntityLiving.getDeclaredField("bd"); - class_Entity_jumpingField.setAccessible(true); - class_Entity_moveStrafingField = class_EntityLiving.getDeclaredField("be"); - class_Entity_moveForwardField = class_EntityLiving.getDeclaredField("bg"); - } catch (Throwable not12) { - // 1.11 - current = false; - try { - class_Entity_jumpingField = class_EntityLiving.getDeclaredField("bd"); - class_Entity_jumpingField.setAccessible(true); - class_Entity_moveStrafingField = class_EntityLiving.getDeclaredField("be"); - class_Entity_moveForwardField = class_EntityLiving.getDeclaredField("bf"); - } catch (Throwable not11) { - // 1.10 - try { - class_Entity_jumpingField = class_EntityLiving.getDeclaredField("be"); - class_Entity_jumpingField.setAccessible(true); - class_Entity_moveStrafingField = class_EntityLiving.getDeclaredField("bf"); - class_Entity_moveForwardField = class_EntityLiving.getDeclaredField("bg"); - } catch (Throwable not10) { - class_Entity_jumpingField = class_EntityLiving.getDeclaredField("bc"); - class_Entity_jumpingField.setAccessible(true); - class_Entity_moveStrafingField = class_EntityLiving.getDeclaredField("bd"); - class_Entity_moveForwardField = class_EntityLiving.getDeclaredField("be"); - } - } - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred while registering entity movement accessors, vehicle control will not work"); - class_Entity_jumpingField = null; - class_Entity_moveStrafingField = null; - class_Entity_moveForwardField = null; - } - - try { - class_Block_durabilityField = class_Block.getDeclaredField("durability"); - class_Block_durabilityField.setAccessible(true); - Class craftMagicNumbers = fixBukkitClass("org.bukkit.craftbukkit.util.CraftMagicNumbers"); - class_CraftMagicNumbers_getBlockMethod = craftMagicNumbers.getMethod("getBlock", Material.class); - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred while registering block durability accessor, durability-based block checks will not work"); - class_Block_durabilityField = null; - class_CraftMagicNumbers_getBlockMethod = null; - } - - try { - // 1.12 - try { - // Common to 1.12 and below - class_PacketPlayOutChat = fixBukkitClass("net.minecraft.server.PacketPlayOutChat"); - class_ChatComponentText = fixBukkitClass("net.minecraft.server.ChatComponentText"); - class_IChatBaseComponent = fixBukkitClass("net.minecraft.server.IChatBaseComponent"); - class_ChatComponentText_constructor = class_ChatComponentText.getConstructor(String.class); - - // 1.12 specific - class_ChatMessageType = (Class) fixBukkitClass("net.minecraft.server.ChatMessageType"); - enum_ChatMessageType_GAME_INFO = Enum.valueOf(class_ChatMessageType, "GAME_INFO"); - class_PacketPlayOutChat_constructor = class_PacketPlayOutChat.getConstructor(class_IChatBaseComponent, class_ChatMessageType); - - } catch (Throwable ex) { - // 1.11 fallback - current = false; - class_PacketPlayOutChat_constructor = class_PacketPlayOutChat.getConstructor(class_IChatBaseComponent, Byte.TYPE); - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred while registering action bar methods, action bar messages will not work"); - class_PacketPlayOutChat = null; - } - - try { - try { - // 1.11 - class_CraftWorld_createEntityMethod = class_CraftWorld.getMethod("createEntity", Location.class, Class.class); - class_Consumer = fixBukkitClass("org.bukkit.util.Consumer"); - class_CraftWorld_spawnMethod = class_CraftWorld.getMethod("spawn", Location.class, Class.class, class_Consumer, CreatureSpawnEvent.SpawnReason.class); - class_CraftWorld_spawnMethod_isLegacy = false; - } catch (Throwable ignore) { - legacy = true; - class_CraftWorld_spawnMethod_isLegacy = true; - class_CraftWorld_spawnMethod = class_CraftWorld.getMethod("spawn", Location.class, Class.class, CreatureSpawnEvent.SpawnReason.class); - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred while registering custom spawn method, spawn reasons will not work"); - class_CraftWorld_spawnMethod = null; - class_Consumer = null; - } - - try { - class_CraftWorld_getTileEntityAtMethod = class_CraftWorld.getMethod("getTileEntityAt", Integer.TYPE, Integer.TYPE, Integer.TYPE); - class_TileEntity_loadMethod = class_TileEntity.getMethod("a", class_NBTTagCompound); - class_TileEntity_updateMethod = class_TileEntity.getMethod("update"); - class_TileEntity_saveMethod = class_TileEntity.getMethod("save", class_NBTTagCompound); - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, handling of tile entities may not work well"); - class_TileEntity_loadMethod = null; - class_TileEntity_updateMethod = null; - class_TileEntity_saveMethod = null; - } - - try { - class_NBTCompressedStreamTools_loadFileMethod = class_NBTCompressedStreamTools.getMethod("a", InputStream.class); - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, schematics will not load"); - } - - try { - class_EntityLiving_damageEntityMethod = class_EntityLiving.getMethod("damageEntity", class_DamageSource, Float.TYPE); - class_DamageSource_getMagicSourceMethod = class_DamageSource.getMethod("b", class_Entity, class_Entity); - class_DamageSource_MagicField = class_DamageSource.getField("MAGIC"); - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, magic damage will not work, using normal damage instead"); - class_EntityLiving_damageEntityMethod = null; - class_DamageSource_getMagicSourceMethod = null; - class_DamageSource_MagicField = null; - } - - try { - try { - // 1.12, same as 1.10 - class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bB"); - if (class_EntityArmorStand_disabledSlotsField.getType() != Integer.TYPE) { - throw new Exception("Looks like 1.11, maybe"); - } - } catch (Throwable not12) { - try { - // 1.11 - class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bA"); - if (class_EntityArmorStand_disabledSlotsField.getType() != Integer.TYPE) { - throw new Exception("Looks like 1.10"); - } - } catch (Throwable ignore) { - // 1.10 and earlier - legacy = true; - try { - class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bB"); - if (class_EntityArmorStand_disabledSlotsField.getType() != Integer.TYPE) { - throw new Exception("Looks like 1.9"); - } - } catch (Throwable ignore2) { - try { - // 1.9.4 - class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bA"); - } catch (Throwable ignore3) { - // 1.9.2 - class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bz"); - } - } - } - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, armor stand slots cannot be locked"); - class_EntityArmorStand_disabledSlotsField = null; - } - if (class_EntityArmorStand_disabledSlotsField != null) { - class_EntityArmorStand_disabledSlotsField.setAccessible(true); - } - - // TODO: Lockable API in 1.11+ - try { - try { - // Common - class_ChestLock_Constructor = class_ChestLock.getConstructor(String.class); - class_ChestLock_isEmpty = class_ChestLock.getMethod("a"); - class_TileEntityContainer_getLock = class_TileEntityContainer.getMethod("getLock"); - - // 1.12 only - class_ChestLock_getString = class_ChestLock.getMethod("getKey"); - class_TileEntityContainer_setLock = class_TileEntityContainer.getMethod("setLock", class_ChestLock); - } catch (Throwable not12) { - try { - // 1.11 - class_ChestLock_getString = class_ChestLock.getMethod("b"); - class_TileEntityContainer_setLock = class_TileEntityContainer.getMethod("a", class_ChestLock); - } catch (Throwable ignore) { - // 1.10 and earlier - legacy = true; - class_TileEntityContainer_setLock = class_TileEntityContainer.getMethod("a", class_ChestLock); - class_TileEntityContainer_getLock = class_TileEntityContainer.getMethod("y_"); - } - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, chest locking and unlocking will not work"); - class_TileEntityContainer_setLock = null; - class_TileEntityContainer_getLock = null; - } - - try { - try { - // 1.10 and 1.11 - class_PlayerConnection_floatCountField = class_PlayerConnection.getDeclaredField("C"); - if (class_PlayerConnection_floatCountField.getType() != Integer.TYPE) { - throw new Exception("Looks like 1.9"); - } - class_PlayerConnection_floatCountField.setAccessible(true); - } catch (Throwable ignore) { - // 1.9 and earlier - legacy = true; - class_PlayerConnection_floatCountField = class_PlayerConnection.getDeclaredField("g"); - class_PlayerConnection_floatCountField.setAccessible(true); - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, player flight exemption will not work"); - class_PlayerConnection_floatCountField = null; - } - - try { - try { - // 1.11 - class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("ax"); - } catch (Throwable ignore5) { - try { - // 1.10 - class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("ay"); // ayyyyy lmao - } catch (Throwable ignore4) { - legacy = true; - // 1.8.3 - class_EntityArrow_lifeField = class_EntityArrow.getDeclaredField("ar"); - } - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, setting arrow lifespan will not work"); - class_EntityArrow_lifeField = null; - } - if (class_EntityArrow_lifeField != null) { - class_EntityArrow_lifeField.setAccessible(true); - } - - try { - // 1.9 and up - class_EntityDamageSource_setThornsMethod = class_EntityDamageSource.getMethod("w"); - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, thorn damage override to hurt ender dragon will not work"); - class_EntityDamageSource_setThornsMethod = null; - } - - try { - try { - // 1.12 - class_Entity_getTypeMethod = class_Entity.getDeclaredMethod("getSaveID"); - class_Entity_saveMethod = class_Entity.getMethod("save", class_NBTTagCompound); - } catch (Throwable not12) { - try { - // 1.10 and 1.11 - class_Entity_getTypeMethod = class_Entity.getDeclaredMethod("at"); - } catch (Throwable ignore) { - // 1.9 and earlier - legacy = true; - class_Entity_getTypeMethod = class_Entity.getDeclaredMethod("as"); - } - class_Entity_saveMethod = class_Entity.getMethod("e", class_NBTTagCompound); - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, saving entities to spawn eggs will not work"); - class_Entity_getTypeMethod = null; - class_Entity_saveMethod = null; - } - if (class_Entity_getTypeMethod != null) { - class_Entity_getTypeMethod.setAccessible(true); - } - - try { - try { - // 1.11 - class_ItemStack_consructor = class_ItemStack.getConstructor(class_NBTTagCompound); - } catch (Throwable ignore) { - // 1.10 and earlier - legacy = true; - class_ItemStack_createStackMethod = class_ItemStack.getMethod("createStack", class_NBTTagCompound); - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, restoring inventories from schematics will not work"); - class_ItemStack_createStackMethod = null; - } - - try { - class_EntityArrow_damageField = class_EntityArrow.getDeclaredField("damage"); - class_EntityArrow_damageField.setAccessible(true); - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, setting arrow damage will not work"); - class_EntityArrow_damageField = null; - } - - // TODO: setSilent API in 1.11+ - try { - try { - // 1.10 and 1.11 - class_Entity_setSilentMethod = class_Entity.getDeclaredMethod("setSilent", Boolean.TYPE); - class_Entity_isSilentMethod = class_Entity.getDeclaredMethod("isSilent"); - } catch (Throwable ignore) { - // 1.9 and earlier - legacy = true; - class_Entity_setSilentMethod = class_Entity.getDeclaredMethod("c", Boolean.TYPE); - class_Entity_isSilentMethod = class_Entity.getDeclaredMethod("ad"); - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, silent entities will not work"); - class_Entity_setSilentMethod = null; - class_Entity_isSilentMethod = null; - } - - // TODO: ArmorStand.setGravity in 1.11+ - // Different behavior, but less hacky. - try { - try { - // 1.10 and 1.11 - class_Entity_setNoGravity = class_Entity.getDeclaredMethod("setNoGravity", Boolean.TYPE); - } catch (Throwable ignore) { - // 1.9 and earlier - legacy = true; - class_ArmorStand_setGravity = class_EntityArmorStand.getDeclaredMethod("setGravity", Boolean.TYPE); - } - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.WARNING, "An error occurred, hacky no-gravity armor stands won't work"); - class_Entity_setNoGravity = null; - class_ArmorStand_setGravity = null; - } - - // TODO ItemStack.isEmpty in 1.11+ - try { - // 1.11 - class_ItemStack_isEmptyMethod = class_ItemStack.getMethod("isEmpty"); - } catch (Throwable ignore) { - // 1.10 and earlier - legacy = true; - } - } catch (Throwable ex) { - failed = true; - Bukkit.getLogger().log(Level.SEVERE, "An unexpected error occurred initializing Magic"); - } - } - - public static boolean getFailed() { - return failed; - } - - public static boolean isLegacy() { - return legacy; - } - - public static Class getVersionedBukkitClass(String newVersion, String oldVersion) { - Class c = getBukkitClass(newVersion); - if (c == null) { - c = getBukkitClass(oldVersion); - if (c == null) { - Bukkit.getLogger().warning("Could not bind to " + newVersion + " or " + oldVersion); - } - } - return c; - } - - public static Class getClass(String className) { - Class result = null; - try { - result = NMSUtils.class.getClassLoader().loadClass(className); - } catch (Exception ex) { - result = null; - } - - return result; - } - - public static Class getBukkitClass(String className) { - Class result; - try { - result = fixBukkitClass(className); - } catch (Exception ex) { - result = null; - } - - return result; - } - - public static Class fixBukkitClass(String className) { - if (!versionPrefix.isEmpty()) { - className = className.replace("org.bukkit.craftbukkit.", "org.bukkit.craftbukkit." + versionPrefix); - className = className.replace("net.minecraft.server.", "net.minecraft.server." + versionPrefix); - } - - try { - return NMSUtils.class.getClassLoader().loadClass(className); - } catch (ClassNotFoundException ignored) { - return null; - } - } - - public static Object getHandle(Server server) { - Object handle = null; - try { - handle = class_CraftServer_getServerMethod.invoke(server); - } catch (Throwable ex) { - handle = null; - } - return handle; - } - - public static Object getHandle(ItemStack stack) { - Object handle = null; - try { - handle = class_CraftItemStack_getHandleField.get(stack); - } catch (Throwable ex) { - handle = null; - } - return handle; - } - - public static Object getHandle(World world) { - if (world == null) { - return null; - } - Object handle = null; - try { - handle = class_CraftWorld_getHandleMethod.invoke(world); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return handle; - } - - public static Object getHandle(Entity entity) { - if (entity == null) { - return null; - } - Object handle = null; - try { - handle = class_CraftEntity_getHandleMethod.invoke(entity); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return handle; - } - - public static Object getHandle(org.bukkit.entity.LivingEntity entity) { - if (entity == null) { - return null; - } - Object handle = null; - try { - handle = class_CraftLivingEntity_getHandleMethod.invoke(entity); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return handle; - } - - public static boolean isDone(Chunk chunk) { - Object chunkHandle = getHandle(chunk); - boolean done = false; - try { - done = (Boolean) class_Chunk_doneField.get(chunkHandle); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return done; - } - - public static Object getHandle(Chunk chunk) { - Object handle = null; - try { - handle = class_CraftChunk_getHandleMethod.invoke(chunk); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return handle; - } - - public static Object getHandle(Player player) { - Object handle = null; - try { - handle = class_CraftPlayer_getHandleMethod.invoke(player); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return handle; - } - - protected static void sendPacket(Server server, Location source, Collection players, Object packet) throws Exception { - players = ((players != null && players.size() > 0) ? players : server.getOnlinePlayers()); - - int viewDistance = Bukkit.getServer().getViewDistance() * 16; - int viewDistanceSquared = viewDistance * viewDistance; - World sourceWorld = source.getWorld(); - for (Player player : players) { - Location location = player.getLocation(); - if (!location.getWorld().equals(sourceWorld)) { - continue; - } - if (location.distanceSquared(source) <= viewDistanceSquared) { - sendPacket(player, packet); - } - } - } - - protected static void sendPacket(Player player, Object packet) throws Exception { - Object playerHandle = getHandle(player); - Field connectionField = playerHandle.getClass().getField("playerConnection"); - Object connection = connectionField.get(playerHandle); - Method sendPacketMethod = connection.getClass().getMethod("sendPacket", class_Packet); - sendPacketMethod.invoke(connection, packet); - } - - public static int getFacing(BlockFace direction) { - int dir; - switch (direction) { - case SOUTH: - default: - dir = 0; - break; - case WEST: - dir = 1; - break; - case NORTH: - dir = 2; - break; - case EAST: - dir = 3; - break; - } - - return dir; - } - - public static Entity getBukkitEntity(Object entity) { - if (entity == null) { - return null; - } - try { - Method getMethod = entity.getClass().getMethod("getBukkitEntity"); - Object bukkitEntity = getMethod.invoke(entity); - if (!(bukkitEntity instanceof Entity)) { - return null; - } - return (Entity) bukkitEntity; - } catch (Throwable ex) { - ex.printStackTrace(); - } - - return null; - } - - public static Object getTag(Object mcItemStack) { - Object tag = null; - try { - tag = class_ItemStack_tagField.get(mcItemStack); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return tag; - } - - public static Object getNMSCopy(ItemStack stack) { - Object nms = null; - try { - nms = class_CraftItemStack_copyMethod.invoke(null, stack); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return nms; - } - - public static ItemStack getCopy(ItemStack stack) { - if (stack == null) { - return null; - } - - try { - Object craft = getNMSCopy(stack); - stack = (ItemStack) class_CraftItemStack_mirrorMethod.invoke(null, craft); - } catch (Throwable ex) { - stack = null; - } - - return stack; - } - - public static ItemStack makeReal(ItemStack stack) { - if (stack == null) { - return null; - } - Object nmsStack = getHandle(stack); - if (nmsStack == null) { - stack = getCopy(stack); - nmsStack = getHandle(stack); - } - if (nmsStack == null) { - return null; - } - try { - Object tag = class_ItemStack_tagField.get(nmsStack); - if (tag == null) { - class_ItemStack_tagField.set(nmsStack, class_NBTTagCompound.newInstance()); - } - } catch (Throwable ex) { - ex.printStackTrace(); - return null; - } - - return stack; - } - - public static String getMetaString(ItemStack stack, String tag, String defaultValue) { - String result = getMetaString(stack, tag); - return result == null ? defaultValue : result; - } - - public static boolean hasMeta(ItemStack stack, String tag) { - return !NMSUtil19.isEmpty(stack) && getNode(stack, tag) != null; - } - - public static Object getTag(ItemStack itemStack) { - Object tag = null; - try { - Object mcItemStack = getHandle(itemStack); - if (mcItemStack == null) { - return null; - } - tag = class_ItemStack_tagField.get(mcItemStack); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return tag; - } - - public static Object getNode(ItemStack stack, String tag) { - if (NMSUtil19.isEmpty(stack)) { - return null; - } - Object meta = null; - try { - Object craft = getHandle(stack); - if (craft == null) { - return null; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return null; - } - meta = class_NBTTagCompound_getMethod.invoke(tagObject, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static boolean containsNode(Object nbtBase, String tag) { - if (nbtBase == null) { - return false; - } - Boolean result = false; - try { - result = (Boolean) class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return result; - } - - public static Object getNode(Object nbtBase, String tag) { - if (nbtBase == null) { - return null; - } - Object meta = null; - try { - meta = class_NBTTagCompound_getMethod.invoke(nbtBase, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static Object createNode(Object nbtBase, String tag) { - if (nbtBase == null) { - return null; - } - Object meta = null; - try { - meta = class_NBTTagCompound_getCompoundMethod.invoke(nbtBase, tag); - class_NBTTagCompound_setMethod.invoke(nbtBase, tag, meta); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static Object createNode(ItemStack stack, String tag) { - if (NMSUtil19.isEmpty(stack)) { - return null; - } - Object outputObject = getNode(stack, tag); - if (outputObject == null) { - try { - Object craft = getHandle(stack); - if (craft == null) { - return null; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - tagObject = class_NBTTagCompound.newInstance(); - class_ItemStack_tagField.set(craft, tagObject); - } - outputObject = class_NBTTagCompound.newInstance(); - class_NBTTagCompound_setMethod.invoke(tagObject, tag, outputObject); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - return outputObject; - } - - public static String getMetaString(Object node, String tag, String defaultValue) { - String meta = getMetaString(node, tag); - return meta == null || meta.length() == 0 ? defaultValue : meta; - } - - public static String getMetaString(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return null; - } - String meta = null; - try { - meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static String getMeta(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return null; - } - String meta = null; - try { - meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static Byte getMetaByte(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return null; - } - Byte meta = null; - try { - meta = (Byte) class_NBTTagCompound_getByteMethod.invoke(node, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static Integer getMetaInt(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return null; - } - Integer meta = null; - try { - meta = (Integer) class_NBTTagCompound_getIntMethod.invoke(node, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static Boolean getMetaBoolean(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return null; - } - Boolean meta = null; - try { - meta = (Boolean) class_NBTTagCompound_getBooleanMethod.invoke(node, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static void setMeta(Object node, String tag, String value) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return; - } - try { - if (value == null || value.length() == 0) { - class_NBTTagCompound_removeMethod.invoke(node, tag); - } else { - class_NBTTagCompound_setStringMethod.invoke(node, tag, value); - } - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static void setMetaLong(Object node, String tag, long value) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return; - } - try { - class_NBTTagCompound_setLongMethod.invoke(node, tag, value); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static void setMetaBoolean(Object node, String tag, boolean value) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return; - } - try { - class_NBTTagCompound_setBooleanMethod.invoke(node, tag, value); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static void setMetaDouble(Object node, String tag, double value) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return; - } - try { - class_NBTTagCompound_setDoubleMethod.invoke(node, tag, value); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static void setMetaInt(Object node, String tag, int value) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return; - } - try { - class_NBTTagCompound_setIntMethod.invoke(node, tag, value); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static void removeMeta(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return; - } - try { - class_NBTTagCompound_removeMethod.invoke(node, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static void removeMeta(ItemStack stack, String tag) { - if (NMSUtil19.isEmpty(stack)) { - return; - } - - try { - Object craft = getHandle(stack); - if (craft == null) { - return; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return; - } - removeMeta(tagObject, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static void setMetaNode(Object node, String tag, Object child) { - if (node == null || !class_NBTTagCompound.isInstance(node)) { - return; - } - try { - if (child == null) { - class_NBTTagCompound_removeMethod.invoke(node, tag); - } else { - class_NBTTagCompound_setMethod.invoke(node, tag, child); - } - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static boolean setMetaNode(ItemStack stack, String tag, Object child) { - if (NMSUtil19.isEmpty(stack)) { - return false; - } - try { - Object craft = getHandle(stack); - if (craft == null) { - return false; - } - Object node = getTag(craft); - if (node == null) { - return false; - } - if (child == null) { - class_NBTTagCompound_removeMethod.invoke(node, tag); - } else { - class_NBTTagCompound_setMethod.invoke(node, tag, child); - } - } catch (Throwable ex) { - ex.printStackTrace(); - return false; - } - - return true; - } - - public static String getMetaString(ItemStack stack, String tag) { - if (NMSUtil19.isEmpty(stack)) { - return null; - } - String meta = null; - try { - Object craft = getHandle(stack); - if (craft == null) { - return null; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return null; - } - meta = (String) class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return meta; - } - - public static void setMeta(ItemStack stack, String tag, String value) { - if (NMSUtil19.isEmpty(stack)) { - return; - } - try { - Object craft = getHandle(stack); - if (craft == null) { - return; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return; - } - class_NBTTagCompound_setStringMethod.invoke(tagObject, tag, value); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static void setMetaBoolean(ItemStack stack, String tag, boolean value) { - if (NMSUtil19.isEmpty(stack)) { - return; - } - try { - Object craft = getHandle(stack); - if (craft == null) { - return; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return; - } - setMetaBoolean(tagObject, tag, value); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - - public static boolean getMetaBoolean(ItemStack stack, String tag, boolean defaultValue) { - if (NMSUtil19.isEmpty(stack)) { - return defaultValue; - } - boolean result = defaultValue; - try { - Object craft = getHandle(stack); - if (craft == null) { - return defaultValue; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return defaultValue; - } - Boolean value = getMetaBoolean(tagObject, tag); - result = value == null ? defaultValue : value; - } catch (Throwable ex) { - ex.printStackTrace(); - } - return result; - } - - public static void addGlow(ItemStack stack) { - if (NMSUtil19.isEmpty(stack)) { - return; - } - - ItemMeta meta = stack.getItemMeta(); - meta.addEnchant(Enchantment.LUCK, 1, true); - stack.setItemMeta(meta); - } - - public static void removeGlow(ItemStack stack) { - if (NMSUtil19.isEmpty(stack)) { - return; - } - - ItemMeta meta = stack.getItemMeta(); - if (meta.hasEnchant(Enchantment.LUCK)) { - meta.removeEnchant(Enchantment.LUCK); - stack.setItemMeta(meta); - } - } - - public static boolean isUnbreakable(ItemStack stack) { - if (NMSUtil19.isEmpty(stack)) { - return false; - } - Boolean unbreakableFlag = null; - try { - Object craft = getHandle(stack); - if (craft == null) { - return false; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return false; - } - unbreakableFlag = getMetaBoolean(tagObject, "Unbreakable"); - } catch (Throwable ignored) { - - } - - return unbreakableFlag != null && unbreakableFlag; - } - - public static void makeUnbreakable(ItemStack stack) { - if (NMSUtil19.isEmpty(stack)) { - return; - } - - try { - Object craft = getHandle(stack); - if (craft == null) { - return; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return; - } - - Object unbreakableFlag = null; - unbreakableFlag = class_NBTTagByte_constructor.newInstance((byte) 1); - class_NBTTagCompound_setMethod.invoke(tagObject, "Unbreakable", unbreakableFlag); - } catch (Throwable ignored) { - - } - } - - public static void removeUnbreakable(ItemStack stack) { - removeMeta(stack, "Unbreakable"); - } - - public static void hideFlags(ItemStack stack, byte flags) { - if (NMSUtil19.isEmpty(stack)) { - return; - } - - try { - Object craft = getHandle(stack); - if (craft == null) { - return; - } - Object tagObject = getTag(craft); - if (tagObject == null) { - return; - } - - Object hideFlag = null; - hideFlag = class_NBTTagByte_constructor.newInstance(flags); - class_NBTTagCompound_setMethod.invoke(tagObject, "HideFlags", hideFlag); - } catch (Throwable ignored) { - - } - } - - public static boolean createExplosion(Entity entity, World world, double x, double y, double z, float power, boolean setFire, boolean breakBlocks) { - boolean result = false; - if (world == null) { - return false; - } - try { - Object worldHandle = getHandle(world); - if (worldHandle == null) { - return false; - } - Object entityHandle = entity == null ? null : getHandle(entity); - - Object explosion = class_World_explodeMethod.invoke(worldHandle, entityHandle, x, y, z, power, setFire, breakBlocks); - Field cancelledField = explosion.getClass().getDeclaredField("wasCanceled"); - result = (Boolean) cancelledField.get(explosion); - } catch (Throwable ex) { - ex.printStackTrace(); - result = false; - } - return result; - } - - public static void makeTemporary(ItemStack itemStack, String message) { - setMeta(itemStack, "temporary", message); - } - - public static boolean isTemporary(ItemStack itemStack) { - return hasMeta(itemStack, "temporary"); - } - - public static void makeUnplaceable(ItemStack itemStack) { - setMeta(itemStack, "unplaceable", "true"); - } - - public static void removeUnplaceable(ItemStack itemStack) { - removeMeta(itemStack, "unplaceable"); - } - - public static boolean isUnplaceable(ItemStack itemStack) { - return hasMeta(itemStack, "unplaceable"); - } - - public static String getTemporaryMessage(ItemStack itemStack) { - return getMetaString(itemStack, "temporary"); - } - - public static void setReplacement(ItemStack itemStack, ItemStack replacement) { - YamlConfiguration configuration = new YamlConfiguration(); - configuration.set("item", replacement); - setMeta(itemStack, "replacement", configuration.saveToString()); - } - - public static ItemStack getReplacement(ItemStack itemStack) { - String serialized = getMetaString(itemStack, "replacement"); - if (serialized == null || serialized.isEmpty()) { - return null; - } - YamlConfiguration configuration = new YamlConfiguration(); - ItemStack replacement = null; - try { - configuration.loadFromString(serialized); - replacement = configuration.getItemStack("item"); - } catch (Exception ex) { - ex.printStackTrace(); - } - return replacement; - } - - protected static Object getTagString(String value) { - try { - return class_NBTTagString_consructor.newInstance(value); - } catch (Exception ex) { - ex.printStackTrace(); - - } - return null; - } - - public static Object setStringList(Object nbtBase, String tag, Collection values) { - if (nbtBase == null) { - return null; - } - Object listMeta = null; - try { - listMeta = class_NBTTagList.newInstance(); - - for (String value : values) { - Object nbtString = getTagString(value); - class_NBTTagList_addMethod.invoke(listMeta, nbtString); - } - - class_NBTTagCompound_setMethod.invoke(nbtBase, tag, listMeta); - } catch (Throwable ex) { - ex.printStackTrace(); - return null; - } - return listMeta; - } - - public static ItemStack getItem(Object itemTag) { - if (itemTag == null) { - return null; - } - ItemStack item = null; - try { - Object nmsStack = null; - if (class_ItemStack_consructor != null) { - nmsStack = class_ItemStack_consructor.newInstance(itemTag); - } else { - nmsStack = class_ItemStack_createStackMethod.invoke(null, itemTag); - } - item = (ItemStack) class_CraftItemStack_mirrorMethod.invoke(null, nmsStack); - } catch (Exception ex) { - ex.printStackTrace(); - } - return item; - } - - public static ItemStack[] getItems(Object rootTag, String tagName) { - try { - Object itemList = class_NBTTagCompound_getListMethod.invoke(rootTag, tagName, NBT_TYPE_COMPOUND); - Integer size = (Integer) class_NBTTagList_sizeMethod.invoke(itemList); - ItemStack[] items = new ItemStack[size]; - for (int i = 0; i < size; i++) { - try { - Object itemData = class_NBTTagList_getMethod.invoke(itemList, i); - if (itemData != null) { - items[i] = getItem(itemData); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - return items; - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static Object getTileEntityData(Location location) { - if (class_CraftWorld_getTileEntityAtMethod == null || class_TileEntity_saveMethod == null) { - return null; - } - Object data = null; - try { - World world = location.getWorld(); - Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (tileEntity != null) { - data = class_NBTTagCompound.newInstance(); - class_TileEntity_saveMethod.invoke(tileEntity, data); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return data; - } - - public static Object getTileEntity(Location location) { - if (class_CraftWorld_getTileEntityAtMethod == null) { - return null; - } - Object tileEntity = null; - try { - World world = location.getWorld(); - tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } catch (Exception ex) { - ex.printStackTrace(); - } - return tileEntity; - } - - public static void clearItems(Location location) { - if (class_TileEntity_loadMethod == null || class_TileEntity_updateMethod == null || class_CraftWorld_getTileEntityAtMethod == null || class_TileEntity_saveMethod == null) { - return; - } - if (location == null) { - return; - } - try { - World world = location.getWorld(); - if (world == null) { - return; - } - - Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (tileEntity != null) { - Object entityData = class_NBTTagCompound.newInstance(); - class_TileEntity_saveMethod.invoke(tileEntity, entityData); - Object itemList = class_NBTTagCompound_getListMethod.invoke(entityData, "Items", NBT_TYPE_COMPOUND); - if (itemList != null) { - List items = (List) class_NBTTagList_list.get(itemList); - items.clear(); - } - class_NBTTagCompound_removeMethod.invoke(entityData, "Item"); - class_TileEntity_loadMethod.invoke(tileEntity, entityData); - class_TileEntity_updateMethod.invoke(tileEntity); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static void setTileEntityData(Location location, Object data) { - if (class_TileEntity_loadMethod == null || class_TileEntity_updateMethod == null || class_CraftWorld_getTileEntityAtMethod == null) { - return; - } - - if (location == null || data == null) { - return; - } - try { - World world = location.getWorld(); - if (world == null) { - return; - } - - Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (tileEntity == null) { - return; - } - - class_NBTTagCompound_setIntMethod.invoke(data, "x", location.getBlockX()); - class_NBTTagCompound_setIntMethod.invoke(data, "y", location.getBlockY()); - class_NBTTagCompound_setIntMethod.invoke(data, "z", location.getBlockZ()); - - class_TileEntity_loadMethod.invoke(tileEntity, data); - class_TileEntity_updateMethod.invoke(tileEntity); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Vector getPosition(Object entityData, String tag) { - if (class_NBTTagList_getDoubleMethod == null) { - return null; - } - try { - Object posList = class_NBTTagCompound_getListMethod.invoke(entityData, tag, NBT_TYPE_DOUBLE); - Double x = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 0); - Double y = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 1); - Double z = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 2); - if (x != null && y != null && z != null) { - return new Vector(x, y, z); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static Entity getEntity(World world, UUID uuid) { - try { - Object worldHandle = getHandle(world); - final Map entityMap = (Map) class_WorldServer_entitiesByUUIDField.get(worldHandle); - if (entityMap != null) { - Object nmsEntity = entityMap.get(uuid); - if (nmsEntity != null) { - return getBukkitEntity(nmsEntity); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setEnvironment(World world, World.Environment environment) { - try { - class_CraftWorld_environmentField.set(world, environment); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static void playCustomSound(Player player, Location location, String sound, float volume, float pitch) { - try { - Object packet = class_PacketPlayOutCustomSoundEffect_Constructor.newInstance(sound, enum_SoundCategory_PLAYERS, location.getX(), location.getY(), location.getZ(), volume, pitch); - sendPacket(player, packet); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Map getMap(ConfigurationSection section) { - if (section == null) { - return null; - } - if (section instanceof MemorySection) { - try { - Object mapObject = class_MemorySection_mapField.get(section); - if (mapObject instanceof Map) { - return (Map) mapObject; - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - // Do it the slow way - Map map = new HashMap<>(); - Set keys = section.getKeys(false); - for (String key : keys) { - map.put(key, section.get(key)); - } - - return map; - } - - public static boolean isEmpty(ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) { - return true; - } - if (class_ItemStack_isEmptyMethod == null) { - return false; - } - try { - Object handle = getHandle(itemStack); - if (handle == null) { - return false; - } - return (Boolean) class_ItemStack_isEmptyMethod.invoke(handle); - } catch (Throwable ex) { - ex.printStackTrace(); - } - return false; - } -} diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtils.java b/src/main/java/me/skymc/taboolib/nms/NMSUtils.java deleted file mode 100644 index 9bddbaa..0000000 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtils.java +++ /dev/null @@ -1,379 +0,0 @@ -package me.skymc.taboolib.nms; - -import org.bukkit.Bukkit; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.stream.IntStream; - -/** - * @author Unknown - */ -public class NMSUtils { - - public static Class c = getOBCClass("block.CraftBlock"); - public static Method m = getMethodSilent(c, "getNMSBlock"); - - public static String getVersion() { - String name = Bukkit.getServer().getClass().getPackage().getName(); - return name.substring(name.lastIndexOf('.') + 1) + "."; - } - - public static > T getEnumSilent(Class enumType, String str) { - try { - return Enum.valueOf(enumType, str); - } catch (Exception ignored) { - return null; - } - } - - public static Class getClassWithException(String name) throws Exception { - return Class.forName(name); - } - - public static Class getClass(String name) { - try { - return getClassWithException(name); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Class getClass(String... strings) { - for (String s : strings) { - try { - return getClassWithException(s); - } catch (Exception ignored) { - } - } - return null; - } - - public static Class getClassSilent(String name) { - try { - return getClassWithException(name); - } catch (Exception ignored) { - } - return null; - } - - public static Class getNMSClassWithException(String className) throws Exception { - return Class.forName("net.minecraft.server." + getVersion() + className); - } - - public static Class getNMSClass(String className) { - try { - return getNMSClassWithException(className); - } catch (Exception ignored) { - } - return null; - } - - public static Class getNMSClassSilent(String className) { - try { - return getNMSClassWithException(className); - } catch (Exception ignored) { - } - return null; - } - - public static Class getNMSClass(String className, String embedded) { - try { - return getNMSClassWithException(className); - } catch (Exception e) { - return getInnerClassSilent(getNMSClassSilent(embedded), className); - } - } - - public static Class getNMSClassSilent(String className, String embedded) { - try { - return getNMSClassWithException(className); - } catch (Exception e) { - return getInnerClassSilent(getNMSClassSilent(embedded), className); - } - } - - public static Class getOBCClassWithException(String className) throws Exception { - return Class.forName("org.bukkit.craftbukkit." + getVersion() + className); - } - - public static Class getOBCClass(String className) { - try { - return getOBCClassWithException(className); - } catch (Exception ignored) { - } - return null; - } - - public static Class getOBCClassSilent(String className) { - try { - return getOBCClassWithException(className); - } catch (Exception ignored) { - } - return null; - } - - public static Object getHandle(Object obj) { - try { - return getMethodWithException(obj.getClass(), "getHandle").invoke(obj); - } catch (Exception ignored) { - return null; - } - } - - public static Object getHandleSilent(Object obj) { - try { - return getMethodWithException(obj.getClass(), "getHandle").invoke(obj); - } catch (Exception e) { - return null; - } - } - - public static Object getBlockHandleWithException(Object obj) throws Exception { - return m.invoke(obj); - } - - public static Object getBlockHandle(Object obj) { - try { - return m.invoke(obj); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public static Object getBlockHandleSilent(Object obj) { - try { - return m.invoke(obj); - } catch (Exception e) { - return null; - } - } - - public static Field getFieldWithException(Class clazz, String name) throws Exception { - for (Field field : clazz.getDeclaredFields()) { - if (field.getName().equals(name)) { - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - } - for (Field field : clazz.getFields()) { - if (field.getName().equals(name)) { - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - } - throw new Exception("Field Not Found"); - } - - public static Field getFieldSilent(Class clazz, String... names) { - for (String name : names) { - try { - return getFieldWithException(clazz, name); - } catch (Exception ignored) { - } - } - return null; - } - - public static Field getFieldSilent(Class clazz, String name) { - try { - return getFieldWithException(clazz, name); - } catch (Exception ignored) { - } - return null; - } - - public static Field getField(Class clazz, String... names) { - for (String name : names) { - try { - return getFieldWithException(clazz, name); - } catch (Exception ignored) { - } - } - return null; - } - - public static Field getFieldOfTypeWithException(Class clazz, Class type, String name) throws Exception { - for (Field field : clazz.getDeclaredFields()) { - if (field.getName().equals(name) && field.getType().equals(type)) { - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - } - for (Field field : clazz.getFields()) { - if (field.getName().equals(name) && field.getType().equals(type)) { - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - } - throw new Exception("Field Not Found"); - } - - public static Field getFieldOfType(Class clazz, Class type, String name) { - try { - return getFieldOfTypeWithException(clazz, type, name); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Field getFirstFieldOfTypeWithException(Class clazz, Class type) throws Exception { - for (Field field : clazz.getDeclaredFields()) { - if (field.getType().equals(type)) { - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - } - throw new Exception("Field Not Found"); - } - - public static Field getFirstFieldOfType(Class clazz, Class type) { - try { - return getFirstFieldOfTypeWithException(clazz, type); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Field getLastFieldOfTypeWithException(Class clazz, Class type) throws Exception { - Field field = null; - for (Field f : clazz.getDeclaredFields()) { - if (f.getType().equals(type)) { - field = f; - } - } - if (field == null) { - throw new Exception("Field Not Found"); - } - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - - public static Field getLastFieldOfType(Class clazz, Class type) { - try { - return getLastFieldOfTypeWithException(clazz, type); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Method getMethodWithException(Class clazz, String name, Class... args) throws Exception { - for (Method m : clazz.getDeclaredMethods()) { - if (m.getName().equals(name) && (args.length == 0 && m.getParameterTypes().length == 0 || classListEqual(args, m.getParameterTypes()))) { - m.setAccessible(true); - return m; - } - } - for (Method m : clazz.getMethods()) { - if (m.getName().equals(name) && (args.length == 0 && m.getParameterTypes().length == 0 || classListEqual(args, m.getParameterTypes()))) { - m.setAccessible(true); - return m; - } - } - throw new Exception("Method Not Found"); - } - - public static Method getMethodSilent(Class clazz, String name, Class... args) { - try { - return getMethodWithException(clazz, name, args); - } catch (Exception ignored) { - } - return null; - } - - public static boolean classListEqual(Class[] l1, Class[] l2) { - return l1.length == l2.length && IntStream.range(0, l1.length).noneMatch(i -> l1[i] != l2[i]); - } - - public static Class getInnerClassWithException(Class c, String className) throws Exception { - for (Class cl : c.getDeclaredClasses()) { - if (cl.getSimpleName().equals(className)) { - return cl; - } - } - throw new Exception("Inner Class Not Found"); - } - - public static Class getInnerClass(Class c, String className) { - try { - return getInnerClassWithException(c, className); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Class getInnerClassSilent(Class c, String className) { - try { - return getInnerClassWithException(c, className); - } catch (Exception ignored) { - } - return null; - } - - public static Constructor getConstructor(Class clazz, Class... args) throws Exception { - for (Constructor c : clazz.getDeclaredConstructors()) { - if (args.length == 0 && c.getParameterTypes().length == 0 || classListEqual(args, c.getParameterTypes())) { - c.setAccessible(true); - return c; - } - } - for (Constructor c : clazz.getConstructors()) { - if (args.length == 0 && c.getParameterTypes().length == 0 || classListEqual(args, c.getParameterTypes())) { - c.setAccessible(true); - return c; - } - } - throw new Exception("Constructor Not Found"); - } - - public static Constructor getConstructorSilent(Class clazz, Class... args) { - try { - return getConstructor(clazz, args); - } catch (Exception ignored) { - } - return null; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - public static Enum getEnum(final String value, final Class enumClass) { - return Enum.valueOf(enumClass, value); - } -} diff --git a/src/main/java/me/skymc/taboolib/nms/item/DabItemUtils.java b/src/main/java/me/skymc/taboolib/nms/item/DabItemUtils.java deleted file mode 100644 index dad63d1..0000000 --- a/src/main/java/me/skymc/taboolib/nms/item/DabItemUtils.java +++ /dev/null @@ -1,453 +0,0 @@ -package me.skymc.taboolib.nms.item; - -import me.skymc.taboolib.Main; -import me.skymc.taboolib.json.JSONArray; -import me.skymc.taboolib.json.JSONObject; -import me.skymc.taboolib.message.MsgUtils; -import me.skymc.taboolib.nms.item.impl._164ItemUtils; -import me.skymc.taboolib.nms.item.impl._1710ItemUtils; -import me.skymc.taboolib.nms.item.impl._194ItemUtils; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.lang.reflect.Method; -import java.util.List; -import java.util.Map; - -public class DabItemUtils { - - private static IDabItemUtils inst = load(); - - private static IDabItemUtils load(){ - ItemStack is = new ItemStack(Material.DIAMOND_SWORD); - ItemMeta im = is.getItemMeta(); - im.addEnchant(Enchantment.KNOCKBACK, 20, true); - is.setItemMeta(im); - try{ - IDabItemUtils inst = new _194ItemUtils(); - inst.convertItemStackToJSON(is); - MsgUtils.send("载入 1.9.4 Spigot 物品工具成功!"); - return inst; - } catch (Exception ignored) { - } - try{ - _1710ItemUtils inst = new _1710ItemUtils(); - inst.convertItemStackToJSON(is); - MsgUtils.send("载入 1.7.10 Cauldron 物品工具成功!"); - return inst; - } catch (Exception ignored) { - } - try{ - IDabItemUtils inst = new _164ItemUtils(); - inst.convertItemStackToJSON(is); - MsgUtils.send("载入 1.6.4 Cauldron 物品工具成功!"); - return inst; - } catch (Exception ignored) { - } - MsgUtils.send("&4物品工具载入失败, 插件已关闭!"); - Bukkit.getPluginManager().disablePlugin(Main.getInst()); - return null; - } - - public static IDabItemUtils getInstance(){ - return inst; - } - - @Deprecated - public static boolean hasBanner(){ - return inst.hasBanner(); - } - - @Deprecated - public static Object getNMSCopy(ItemStack is) throws Exception{ - return inst.getNMSCopy(is); - } - - @Deprecated - public static boolean hasTag(Object is) throws Exception{ - return inst.hasTag(is); - } - - @Deprecated - public static ItemStack asCraftMirror(Object nis) throws Exception{ - return inst.asCraftMirror(nis); - } - - @Deprecated - public static ItemStack asBukkitCopy(Object nmis) throws Exception{ - return inst.asBukkitCopy(nmis); - } - - @Deprecated - public static String getName(ItemStack is){ - return inst.getName(is); - } - - @Deprecated - public static Object getItem(Object nis) throws Exception{ - return inst.getItem(nis); - } - - @Deprecated - public static Method getA(){ - return inst.getA(); - } - - @Deprecated - public static String getRawName(ItemStack is){ - return inst.getRawName(is); - } - - @Deprecated - public static String getItemName(ItemStack is){ - return inst.getItemName(is); - } - - @Deprecated - public static Object getRegistry(){ - return inst.getRegistry(); - } - - @Deprecated - public static String getMinecraftName(ItemStack is){ - return inst.getMinecraftName(is); - } - - @Deprecated - public static Object getTag(Object is) throws Exception{ - return inst.getTag(is); - } - - @Deprecated - public static void setTag(Object is, Object tag1) throws Exception{ - inst.setTag(is, tag1); - } - - @Deprecated - public static boolean isEmpty(Object tag) throws Exception{ - return inst.isEmpty(tag); - } - - @Deprecated - public static Object getMap(Object tag) throws Exception{ - return inst.getMap(tag); - } - - @Deprecated - public static void set(Object tag, String key, Object value) throws Exception{ - inst.set(tag, key, value); - } - - @Deprecated - public static void setString(Object tag, String key, String value) throws Exception{ - inst.setString(tag, key, value); - } - - @Deprecated - public static void setShort(Object tag, String key, short value) throws Exception{ - inst.setShort(tag, key, value); - } - - @Deprecated - public static void setInt(Object tag, String key, int i) throws Exception{ - inst.setInt(tag, key, i); - } - - @Deprecated - public static void setDouble(Object tag, String key, double d) throws Exception{ - inst.setDouble(tag, key, d); - } - - @Deprecated - public static void setLong(Object tag, String key, long l) throws Exception{ - inst.setLong(tag, key, l); - } - - @Deprecated - public static boolean hasKey(Object tag, String key) throws Exception{ - return inst.hasKey(tag, key); - } - - @Deprecated - public static Object get(Object tag, String key) throws Exception{ - return inst.get(tag, key); - } - - @Deprecated - public static String getString(Object tag, String key) throws Exception{ - return inst.getString(tag, key); - } - - @Deprecated - public static int getInt(Object tag, String key) throws Exception{ - return inst.getInt(tag, key); - } - - @Deprecated - public static double getDouble(Object tag, String key) throws Exception{ - return inst.getDouble(tag, key); - } - - @Deprecated - public static long getLong(Object tag, String key) throws Exception{ - return inst.getLong(tag, key); - } - - @Deprecated - public static short getShort(Object tag, String key) throws Exception{ - return inst.getShort(tag, key); - } - - @Deprecated - public static Object getNewNBTTagCompound() throws Exception{ - return inst.getNewNBTTagCompound(); - } - - @Deprecated - public static boolean hasAttributeModifiersKey(Object tag) throws Exception{ - return inst.hasAttributeModifiersKey(tag); - } - - @Deprecated - public static Object getList(Object tag) throws Exception{ - return inst.getList(tag); - } - - @Deprecated - public static Object getList(Object tag, String name, int id) throws Exception{ - return inst.getList(tag, name, id); - } - - @Deprecated - public static boolean getUnbreakable(Object tag) throws Exception{ - return inst.getUnbreakable(tag); - } - - @Deprecated - public static void setUnbreakable(Object tag, boolean value) throws Exception{ - inst.setUnbreakable(tag, value); - } - - @Deprecated - public static Object getNewNBTTagList() throws Exception{ - return inst.getNewNBTTagList(); - } - - @Deprecated - public static void addToList(Object taglist, Object nbt) throws Exception{ - inst.addToList(taglist, nbt); - } - - @Deprecated - public static int getSize(Object list) throws Exception{ - return inst.getSize(list); - } - - @Deprecated - public static Object get(Object tlist, int i) throws Exception{ - return inst.get(tlist, i); - } - - @Deprecated - public static Object getNewNBTTagByte(byte value) throws Exception{ - return inst.getNewNBTTagByte(value); - } - - @Deprecated - public static Object getNewNBTTagByteArray(byte[] value) throws Exception{ - return inst.getNewNBTTagByteArray(value); - } - - @Deprecated - public static Object getData(Object nbt) throws Exception{ - return inst.getData(nbt); - } - - @Deprecated - public static Object createData(Object value) throws Exception{ - return inst.createData(value); - } - - @Deprecated - public static Map convertCompoundTagToValueMap(Object nbt) throws Exception{ - return inst.convertCompoundTagToValueMap(nbt); - } - - @Deprecated - public static List convertListTagToValueList(Object nbttl) throws Exception{ - return inst.convertListTagToValueList(nbttl); - } - - @Deprecated - public static Object convertValueMapToCompoundTag(Map map) throws Exception{ - return inst.convertValueMapToCompoundTag(map); - } - - @Deprecated - public static Object convertValueListToListTag(List list) throws Exception{ - return inst.convertValueListToListTag(list); - } - - @Deprecated - public static void convertListTagToJSON(Object nbttl, JSONArray ja, JSONArray helper) throws Exception{ - inst.convertListTagToJSON(nbttl, ja, helper); - } - - @Deprecated - public static void convertListTagToJSON(Object nbttl, JSONArray ja) throws Exception{ - inst.convertListTagToJSON(nbttl, ja); - } - - @Deprecated - public static void convertCompoundTagToJSON(Object nbt, JSONObject jo, JSONObject helper) throws Exception{ - inst.convertCompoundTagToJSON(nbt, jo, helper); - } - - @Deprecated - public static void convertCompoundTagToJSON(Object nbt, JSONObject jo) throws Exception{ - inst.convertCompoundTagToJSON(nbt, jo); - } - - @Deprecated - public static Object convertJSONToCompoundTag(JSONObject jo, JSONObject helper) throws Exception{ - return inst.convertJSONToCompoundTag(jo, helper); - } - - @Deprecated - public static Object convertJSONToCompoundTag(JSONObject jo) throws Exception{ - return inst.convertJSONToCompoundTag(jo); - } - - @Deprecated - public static Object convertJSONToListTag(JSONArray ja, JSONArray helper) throws Exception{ - return inst.convertJSONToListTag(ja, helper); - } - - @Deprecated - public static Object convertJSONToListTag(JSONArray ja) throws Exception{ - return inst.convertJSONToListTag(ja); - } - - @Deprecated - public static Object getDataJSON(String key, Object nbt, JSONObject jo, JSONObject helper) throws Exception{ - return inst.getDataJSON(key, nbt, jo, helper); - } - - @Deprecated - public static JSONArray getDataJSON(Object nbt) throws Exception{ - return inst.getDataJSON(nbt); - } - - @Deprecated - public static Object getDataJSON(Object nbt, JSONArray ja, JSONArray helper) throws Exception{ - return inst.getDataJSON(nbt, ja, helper); - } - - @Deprecated - public static Object createDataJSON(String key, JSONObject jo, JSONObject helper) throws Exception{ - return inst.createDataJSON(key, jo, helper); - } - - @Deprecated - public static Object createDataJSON(String key, JSONObject jo) throws Exception{ - return inst.createDataJSON(key, jo); - } - - @Deprecated - public static byte getByte(Object o){ - return inst.getByte(o); - } - - @Deprecated - public static short getShort(Object o){ - return inst.getShort(o); - } - - @Deprecated - public static int getInt(Object o){ - return inst.getInt(o); - } - - @Deprecated - public static double getDouble(Object o){ - return inst.getDouble(o); - } - - @Deprecated - public static float getFloat(Object o){ - return inst.getFloat(o); - } - - @Deprecated - public static long getLong(Object o){ - return inst.getLong(o); - } - - @Deprecated - public static Object createDataJSON(int key, JSONArray jo, JSONArray helper) throws Exception{ - return inst.createDataJSON(key, jo, helper); - } - - @Deprecated - public static Object createDataJSON(int key, JSONArray jo) throws Exception{ - return inst.createDataJSON(key, jo); - } - - @Deprecated - public static boolean compareBaseTag(Object tag, Object tag1) throws Exception{ - return inst.compareBaseTag(tag, tag1); - } - - @Deprecated - public static boolean compareCompoundTag(Object tag, Object tag1) throws Exception{ - return inst.compareCompoundTag(tag, tag1); - } - - @Deprecated - public static boolean compareListTag(Object tag, Object tag1) throws Exception{ - return inst.compareListTag(tag, tag1); - } - - @Deprecated - public static boolean compare(ItemStack is1, ItemStack is2){ - return inst.compare(is1, is2); - } - - @Deprecated - public static boolean canMerge(ItemStack add, ItemStack to){ - return compare(add, to); - } - - @Deprecated - public static boolean isModified(ItemStack is){ - return inst.isModified(is); - } - - @Deprecated - public static void sortByMaterial(List items){ - inst.sortByMaterial(items); - } - - @Deprecated - public static void sortByName(List items){ - inst.sortByName(items); - } - - @Deprecated - public static void sortByAmount(List items){ - inst.sortByAmount(items); - } - - @Deprecated - public static ItemStack convertJSONToItemStack(JSONObject jo) throws Exception{ - return inst.convertJSONToItemStack(jo); - } - - @Deprecated - public static JSONObject convertItemStackToJSON(ItemStack is) throws Exception{ - return inst.convertItemStackToJSON(is); - } -} diff --git a/src/main/java/me/skymc/taboolib/nms/item/IDabItemUtils.java b/src/main/java/me/skymc/taboolib/nms/item/IDabItemUtils.java deleted file mode 100644 index c24b652..0000000 --- a/src/main/java/me/skymc/taboolib/nms/item/IDabItemUtils.java +++ /dev/null @@ -1,171 +0,0 @@ -package me.skymc.taboolib.nms.item; - -import me.skymc.taboolib.json.JSONArray; -import me.skymc.taboolib.json.JSONObject; -import org.bukkit.inventory.ItemStack; - -import java.lang.reflect.Method; -import java.util.List; -import java.util.Map; - -public interface IDabItemUtils{ - - //@formatter:off - boolean hasBanner(); - - Object getNMSCopy(ItemStack is) throws Exception; - - boolean hasTag(Object is) throws Exception; - - ItemStack asCraftMirror(Object nis) throws Exception; - - ItemStack asBukkitCopy(Object nmis) throws Exception; - - String getName(ItemStack is); - - Object getItem(Object nis) throws Exception; - - Method getA(); - - String getRawName(ItemStack is); - - String getItemName(ItemStack is); - - Object getRegistry(); - - String getMinecraftName(ItemStack is); - - Object getTag(Object is) throws Exception; - - void setTag(Object is, Object tag1) throws Exception; - - boolean isEmpty(Object tag) throws Exception; - - Object getMap(Object tag) throws Exception; - - void set(Object tag, String key, Object value) throws Exception; - - void setString(Object tag, String key, String value) throws Exception; - - void setShort(Object tag, String key, short value) throws Exception; - - void setInt(Object tag, String key, int i) throws Exception; - - void setDouble(Object tag, String key, double d) throws Exception; - - void setLong(Object tag, String key, long l) throws Exception; - - boolean hasKey(Object tag, String key) throws Exception; - - Object get(Object tag, String key) throws Exception; - - String getString(Object tag, String key) throws Exception; - - int getInt(Object tag, String key) throws Exception; - - double getDouble(Object tag, String key) throws Exception; - - long getLong(Object tag, String key) throws Exception; - - short getShort(Object tag, String key) throws Exception; - - Object getNewNBTTagCompound() throws Exception; - - boolean hasAttributeModifiersKey(Object tag) throws Exception; - - Object getList(Object tag) throws Exception; - - Object getList(Object tag, String name, int id) throws Exception; - - boolean getUnbreakable(Object tag) throws Exception; - - void setUnbreakable(Object tag, boolean value) throws Exception; - - Object getNewNBTTagList() throws Exception; - - void addToList(Object taglist, Object nbt) throws Exception; - - int getSize(Object list) throws Exception; - - Object get(Object tlist, int i) throws Exception; - - Object getNewNBTTagByte(byte value) throws Exception; - - Object getNewNBTTagByteArray(byte[] value) throws Exception; - - Object getData(Object nbt) throws Exception; - - Object createData(Object value) throws Exception; - - Map convertCompoundTagToValueMap(Object nbt) throws Exception; - - List convertListTagToValueList(Object nbttl) throws Exception; - - Object convertValueMapToCompoundTag(Map map) throws Exception; - - Object convertValueListToListTag(List list) throws Exception; - @Deprecated - void convertListTagToJSON(Object nbttl, JSONArray ja, JSONArray helper) throws Exception; - - void convertListTagToJSON(Object nbttl, JSONArray ja) throws Exception; - @Deprecated - void convertCompoundTagToJSON(Object nbt, JSONObject jo, JSONObject helper) throws Exception; - - void convertCompoundTagToJSON(Object nbt, JSONObject jo) throws Exception; - @Deprecated - Object convertJSONToCompoundTag(JSONObject jo, JSONObject helper) throws Exception; - - Object convertJSONToCompoundTag(JSONObject jo) throws Exception; - @Deprecated - Object convertJSONToListTag(JSONArray ja, JSONArray helper) throws Exception; - - Object convertJSONToListTag(JSONArray ja) throws Exception; - @Deprecated - Object getDataJSON(String key, Object nbt, JSONObject jo, JSONObject helper) throws Exception; - - JSONArray getDataJSON(Object nbt) throws Exception; - @Deprecated - Object getDataJSON(Object nbt, JSONArray ja, JSONArray helper) throws Exception; - @Deprecated - Object createDataJSON(String key, JSONObject jo, JSONObject helper) throws Exception; - - Object createDataJSON(String key, JSONObject jo) throws Exception; - - byte getByte(Object o); - - short getShort(Object o); - - int getInt(Object o); - - double getDouble(Object o); - - float getFloat(Object o); - - long getLong(Object o); - @Deprecated - Object createDataJSON(int key, JSONArray jo, JSONArray helper) throws Exception; - - Object createDataJSON(int key, JSONArray jo) throws Exception; - - boolean compareBaseTag(Object tag, Object tag1) throws Exception; - - boolean compareCompoundTag(Object tag, Object tag1) throws Exception; - - boolean compareListTag(Object tag, Object tag1) throws Exception; - - boolean compare(ItemStack is1, ItemStack is2); - - boolean canMerge(ItemStack add, ItemStack to); - - boolean isModified(ItemStack is); - - void sortByMaterial(List items); - - void sortByName(List items); - - void sortByAmount(List items); - - ItemStack convertJSONToItemStack(JSONObject jo) throws Exception; - - JSONObject convertItemStackToJSON(ItemStack is) throws Exception; -} diff --git a/src/main/java/me/skymc/taboolib/nms/item/impl/_164ItemUtils.java b/src/main/java/me/skymc/taboolib/nms/item/impl/_164ItemUtils.java deleted file mode 100644 index 1353ae8..0000000 --- a/src/main/java/me/skymc/taboolib/nms/item/impl/_164ItemUtils.java +++ /dev/null @@ -1,1308 +0,0 @@ -package me.skymc.taboolib.nms.item.impl; - -import me.skymc.taboolib.json.JSONArray; -import me.skymc.taboolib.json.JSONObject; -import me.skymc.taboolib.nms.NMSUtils; -import me.skymc.taboolib.nms.item.IDabItemUtils; -import me.skymc.taboolib.nms.nbt.NBTConstants; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.*; -import java.util.Map.Entry; - -public class _164ItemUtils implements IDabItemUtils { - - public boolean banner = getBanner(); - - public boolean getBanner() { - try { - Material m = Material.valueOf("BANNER"); - return true; - } catch (Exception ignored) { - } - return false; - } - - @Override - public boolean hasBanner() { - return banner; - } - - public Class nmis = NMSUtils.getClass("net.minecraft.item.ItemStack"), cis = NMSUtils.getOBCClass("inventory.CraftItemStack"); - public Method nmscopy = NMSUtils.getMethodSilent(cis, "asNMSCopy", ItemStack.class); - - @Override - public Object getNMSCopy(ItemStack is) throws Exception { - return nmscopy.invoke(null, is); - } - - public Method hastag = NMSUtils.getMethodSilent(nmis, "func_77978_p"); - - @Override - public boolean hasTag(Object is) throws Exception { - return (boolean) hastag.invoke(is); - } - - public Method acm = NMSUtils.getMethodSilent(cis, "asCraftMirror", nmis); - - @Override - public ItemStack asCraftMirror(Object nis) throws Exception { - return (ItemStack) acm.invoke(null, nis); - } - - public Class ni = NMSUtils.getClass("net.minecraft.item.Item"); - - public Method abc = NMSUtils.getMethodSilent(cis, "asBukkitCopy", nmis); - - @Override - public ItemStack asBukkitCopy(Object nmis) throws Exception { - return (ItemStack) abc.invoke(null, nmis); - } - - public Method gn = NMSUtils.getMethodSilent(nmis, "func_77977_a"); - - @Override - public String getName(ItemStack is) { - try { - return (String) gn.invoke(getNMSCopy(is)); - } catch (Exception e) { - return null; - } - } - - public Method gi = NMSUtils.getMethodSilent(nmis, "func_77973_b"), ia = getA(); - - @Override - public Object getItem(Object nis) throws Exception { - return gi.invoke(nis); - } - - @Override - public Method getA() { - return NMSUtils.getMethodSilent(ni, "func_77658_a", nmis); - } - - @Override - public String getRawName(ItemStack is) { - try { - Object nis = getNMSCopy(is); - return (String) ia.invoke(gi.invoke(nis), nis); - } catch (Exception e) { - return null; - } - } - - public Method gin = NMSUtils.getMethodSilent(ni, "getLabel"); - - @Override - public String getItemName(ItemStack is) { - try { - return (String) gin.invoke(gi.invoke(getNMSCopy(is))); - } catch (Exception e) { - return null; - } - } - - public Object registry = getRegistry(); - - @Override - public Object getRegistry() { - try { - return NMSUtils.getFieldSilent(ni, "REGISTRY", "field_150901_e").get(null); - } catch (Exception ignored) { - } - return null; - } - - public Class nmrs = NMSUtils.getClass("net.minecraft.util.registry.RegistrySimple", "net.minecraft.util.RegistrySimple"); - - public Field nmrsc = NMSUtils.getFieldSilent(nmrs, "field_82596_a"); - - @Override - public String getMinecraftName(ItemStack is) { - String name = getItemName(is); - if (nmrs == null) { - return name; - } - try { - Map m = (Map) nmrsc.get(registry); - for (Entry e : m.entrySet()) { - Object item = e.getValue(); - String s = (String) gin.invoke(item); - if (name.equals(s)) { - return e.getKey().toString(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public Class nbttc = NMSUtils.getClass("net.minecraft.nbt.NBTTagCompound"); - public Field tag = NMSUtils.getField(nmis, "field_77990_d"); - - @Override - public Object getTag(Object is) throws Exception { - return tag.get(is); - } - - @Override - public void setTag(Object is, Object tag1) throws Exception { - tag.set(is, tag1); - } - - public Method nbtcie = NMSUtils.getMethodSilent(nbttc, "func_82582_d"); - - @Override - public boolean isEmpty(Object tag) throws Exception { - return (boolean) nbtcie.invoke(tag); - } - - public Field nbttcm = NMSUtils.getField(nbttc, "field_74784_a"); - - @Override - public Object getMap(Object tag) throws Exception { - return nbttcm.get(tag); - } - - public Class nbtb = NMSUtils.getClass("net.minecraft.nbt.NBTBase"); - public Method nbttcs = NMSUtils.getMethodSilent(nbttc, "func_74782_a", String.class, nbtb); - public Method nbttcss = NMSUtils.getMethodSilent(nbttc, "func_74778_a", String.class, String.class); - public Method nbttcsi = NMSUtils.getMethodSilent(nbttc, "func_74768_a", String.class, int.class); - public Method nbttcsd = NMSUtils.getMethodSilent(nbttc, "func_74780_a", String.class, double.class); - public Method nbttcsl = NMSUtils.getMethodSilent(nbttc, "func_74772_a", String.class, long.class); - public Method nbttcss1 = NMSUtils.getMethodSilent(nbttc, "func_74777_a", String.class, short.class); - - @Override - public void set(Object tag, String key, Object value) throws Exception { - nbttcs.invoke(tag, key, value); - } - - @Override - public void setString(Object tag, String key, String value) throws Exception { - nbttcss.invoke(tag, key, value); - } - - @Override - public void setShort(Object tag, String key, short value) throws Exception { - nbttcss1.invoke(tag, key, value); - } - - @Override - public void setInt(Object tag, String key, int i) throws Exception { - nbttcsi.invoke(tag, key, i); - } - - @Override - public void setDouble(Object tag, String key, double d) throws Exception { - nbttcsd.invoke(tag, key, d); - } - - @Override - public void setLong(Object tag, String key, long l) throws Exception { - nbttcsl.invoke(tag, key, l); - } - - public Method nbttchk = NMSUtils.getMethodSilent(nbttc, "func_74764_b", String.class); - - @Override - public boolean hasKey(Object tag, String key) throws Exception { - return (boolean) nbttchk.invoke(tag, key); - } - - public Method nbttcg = NMSUtils.getMethodSilent(nbttc, "func_74775_l", String.class); - public Method nbttcgs = NMSUtils.getMethodSilent(nbttc, "func_74779_i", String.class); - public Method nbttcgi = NMSUtils.getMethodSilent(nbttc, "func_74762_e", String.class); - public Method nbttcgd = NMSUtils.getMethodSilent(nbttc, "func_74769_h", String.class); - public Method nbttcgl = NMSUtils.getMethodSilent(nbttc, "func_74763_f", String.class); - public Method nbttcgs1 = NMSUtils.getMethodSilent(nbttc, "func_74765_d", String.class); - - @Override - public Object get(Object tag, String key) throws Exception { - return nbttcg.invoke(tag, key); - } - - @Override - public String getString(Object tag, String key) throws Exception { - return (String) nbttcgs.invoke(tag, key); - } - - @Override - public int getInt(Object tag, String key) throws Exception { - return (int) nbttcgi.invoke(tag, key); - } - - @Override - public double getDouble(Object tag, String key) throws Exception { - return (double) nbttcgd.invoke(tag, key); - } - - @Override - public long getLong(Object tag, String key) throws Exception { - return (long) nbttcgl.invoke(tag, key); - } - - @Override - public short getShort(Object tag, String key) throws Exception { - return (short) nbttcgs1.invoke(tag, key); - } - - public Constructor nbttcc = NMSUtils.getConstructorSilent(nbttc); - - @Override - public Object getNewNBTTagCompound() throws Exception { - return nbttcc.newInstance(); - } - - public Method hkot = NMSUtils.getMethodSilent(nbttc, "func_150297_b", String.class, int.class); - - @Override - public boolean hasAttributeModifiersKey(Object tag) throws Exception { - return (boolean) hkot.invoke(tag, "AttributeModifiers", 9); - } - - public Class nbttl = NMSUtils.getClass("net.minecraft.nbt.NBTTagList"); - public Method gl = NMSUtils.getMethodSilent(nbttc, "func_150295_c", String.class, int.class); - public Method gb = NMSUtils.getMethodSilent(nbttc, "func_74767_n", String.class); - public Method sb = NMSUtils.getMethodSilent(nbttc, "func_74757_a", String.class, boolean.class); - public Method nbttla = NMSUtils.getMethodSilent(nbttl, "func_74742_a", nbtb); - public Constructor nbttlc = NMSUtils.getConstructorSilent(nbttl); - - @Override - public Object getList(Object tag) throws Exception { - return gl.invoke(tag, "AttributeModifiers", 9); - } - - @Override - public Object getList(Object tag, String name, int id) throws Exception { - return gl.invoke(tag, name, id); - } - - @Override - public boolean getUnbreakable(Object tag) throws Exception { - return (boolean) gb.invoke(tag, "Unbreakable"); - } - - @Override - public void setUnbreakable(Object tag, boolean value) throws Exception { - sb.invoke(tag, "Unbreakable", value); - } - - @Override - public Object getNewNBTTagList() throws Exception { - return nbttlc.newInstance(); - } - - @Override - public void addToList(Object taglist, Object nbt) throws Exception { - nbttla.invoke(taglist, nbt); - } - - public Method gs = NMSUtils.getMethodSilent(nbttl, "func_74745_c"); - - @Override - public int getSize(Object list) throws Exception { - return (int) gs.invoke(list); - } - - public Method g = NMSUtils.getMethodSilent(nbttl, "func_150305_b", int.class); - - @Override - public Object get(Object tlist, int i) throws Exception { - return g.invoke(tlist, i); - } - - public Class am = NMSUtils.getClass("net.minecraft.entity.ai.attributes.AttributeModifier"), ga = NMSUtils.getClass("net.minecraft.entity.SharedMonsterAttributes"); - public Method a = NMSUtils.getMethodSilent(ga, "func_111259_a", nbttc), ama = NMSUtils.getMethodSilent(am, "func_111167_a"); - - public Method gti = NMSUtils.getMethodSilent(nbtb, "func_74732_a"); - - public Class nbtby = NMSUtils.getClass("net.minecraft.nbt.NBTTagByte"); - public Class nbtba = NMSUtils.getClass("net.minecraft.nbt.NBTTagByteArray"); - public Class nbtd = NMSUtils.getClass("net.minecraft.nbt.NBTTagDouble"); - public Class nbtf = NMSUtils.getClass("net.minecraft.nbt.NBTTagFloat"); - public Class nbti = NMSUtils.getClass("net.minecraft.nbt.NBTTagInt"); - public Class nbtia = NMSUtils.getClass("net.minecraft.nbt.NBTTagIntArray"); - public Class nbtl = NMSUtils.getClass("net.minecraft.nbt.NBTTagList"); - public Class nbtlo = NMSUtils.getClass("net.minecraft.nbt.NBTTagLong"); - public Class nbts = NMSUtils.getClass("net.minecraft.nbt.NBTTagShort"); - public Class nbtst = NMSUtils.getClass("net.minecraft.nbt.NBTTagString"); - - public Constructor nbtbc = NMSUtils.getConstructorSilent(nbtby, String.class, byte.class); - public Constructor nbtbac = NMSUtils.getConstructorSilent(nbtba, String.class, byte[].class); - public Constructor nbtdc = NMSUtils.getConstructorSilent(nbtd, String.class, double.class); - public Constructor nbtfc = NMSUtils.getConstructorSilent(nbtf, String.class, float.class); - public Constructor nbtic = NMSUtils.getConstructorSilent(nbti, String.class, int.class); - public Constructor nbtiac = NMSUtils.getConstructorSilent(nbtia, String.class, int[].class); - public Constructor nbtlc = NMSUtils.getConstructorSilent(nbtl); - public Constructor nbtloc = NMSUtils.getConstructorSilent(nbtlo, String.class, long.class); - public Constructor nbtsc = NMSUtils.getConstructorSilent(nbts, String.class, short.class); - public Constructor nbtstc = NMSUtils.getConstructorSilent(nbtst, String.class, String.class); - - public Field nbtbd = NMSUtils.getField(nbtby, "field_74756_a"); - public Field nbtbad = NMSUtils.getField(nbtba, "field_74754_a"); - public Field nbtdd = NMSUtils.getField(nbtd, "field_74755_a"); - public Field nbtfd = NMSUtils.getField(nbtf, "field_74750_a"); - public Field nbtid = NMSUtils.getField(nbti, "field_74748_a"); - public Field nbtiad = NMSUtils.getField(nbtia, "field_74749_a"); - public Field nbtld = NMSUtils.getField(nbtl, "field_74747_a"); - public Field nbtlt = NMSUtils.getField(nbtl, "field_74746_b"); - public Field nbtlod = NMSUtils.getField(nbtlo, "field_74753_a"); - public Field nbtsd = NMSUtils.getField(nbts, "field_74752_a"); - public Field nbtstd = NMSUtils.getField(nbtst, "field_74751_a"); - - @Override - public Object getNewNBTTagByte(byte value) throws Exception { - return nbtbc.newInstance(value); - } - - @Override - public Object getNewNBTTagByteArray(byte[] value) throws Exception { - return nbtbac.newInstance(value); - } - - @Override - public Object getData(Object nbt) throws Exception { - int i = ((byte) gti.invoke(nbt)); - switch (i) { - case NBTConstants.TYPE_BYTE: - return nbtbd.get(nbt); - case NBTConstants.TYPE_SHORT: - return nbtsd.get(nbt); - case NBTConstants.TYPE_INT: - return nbtid.get(nbt); - case NBTConstants.TYPE_LONG: - return nbtlod.get(nbt); - case NBTConstants.TYPE_FLOAT: - return nbtfd.get(nbt); - case NBTConstants.TYPE_DOUBLE: - return nbtdd.get(nbt); - case NBTConstants.TYPE_BYTE_ARRAY: - return nbtbad.get(nbt); - case NBTConstants.TYPE_STRING: - return nbtstd.get(nbt); - case NBTConstants.TYPE_LIST: - return convertListTagToValueList(nbt); - case NBTConstants.TYPE_COMPOUND: - return convertCompoundTagToValueMap(nbt); - case NBTConstants.TYPE_INT_ARRAY: - return nbtiad.get(nbt); - } - return null; - } - - @Override - @SuppressWarnings("unchecked") - public Object createData(Object value) throws Exception { - if (value.getClass().equals(byte.class)) { - return nbtbc.newInstance(value); - } - if (value.getClass().equals(byte[].class)) { - return nbtbac.newInstance(value); - } - if (value.getClass().isAssignableFrom(Map.class)) { - return convertValueMapToCompoundTag((Map) value); - } - if (value.getClass().equals(double.class)) { - return nbtdc.newInstance(value); - } - if (value.getClass().equals(float.class)) { - return nbtfc.newInstance(value); - } - if (value.getClass().equals(int.class)) { - return nbtic.newInstance(value); - } - if (value.getClass().equals(int[].class)) { - return nbtiac.newInstance(value); - } - if (value.getClass().isAssignableFrom(List.class)) { - return convertValueListToListTag((List) value); - } - if (value.getClass().equals(long.class)) { - return nbtloc.newInstance(value); - } - if (value.getClass().equals(short.class)) { - return nbtsc.newInstance(value); - } - if (value.getClass().equals(String.class)) { - return nbtstc.newInstance(value); - } - return null; - } - - @Override - @SuppressWarnings({"unchecked"}) - public Map convertCompoundTagToValueMap(Object nbt) throws Exception { - Map ret = new HashMap<>(); - Map map = (Map) getMap(nbt); - for (Entry e : map.entrySet()) { - Object nbti = e.getValue(); - Object data = getData(nbti); - if (data != null) { - ret.put(e.getKey(), data); - } - } - return ret; - } - - @Override - @SuppressWarnings("unchecked") - public List convertListTagToValueList(Object nbttl) throws Exception { - List ret = new ArrayList<>(); - List list = (List) nbtld.get(nbttl); - for (Object e : list) { - Object data = getData(e); - if (data != null) { - ret.add(data); - } - } - return ret; - } - - @Override - public Object convertValueMapToCompoundTag(Map map) throws Exception { - Map value = new HashMap<>(); - for (Entry e : map.entrySet()) { - value.put(e.getKey(), createData(e.getValue())); - } - Object ret = getNewNBTTagCompound(); - nbttcm.set(ret, value); - return ret; - } - - @Override - public Object convertValueListToListTag(List list) throws Exception { - List value = new ArrayList<>(); - for (Object e : list) { - value.add(createData(e)); - } - Object ret = getNewNBTTagList(); - nbttcm.set(ret, value); - if (value.size() > 0) { - nbtlt.set(ret, gti.invoke(value.get(0))); - } - return ret; - } - - @Override - @Deprecated - @SuppressWarnings("unchecked") - public void convertListTagToJSON(Object nbttl, JSONArray ja, JSONArray helper) throws Exception { - List list = (List) nbtld.get(nbttl); - for (Object e : list) { - Object data = getDataJSON(e, ja, helper); - if (data != null) { - ja.put(data); - } - } - } - - @Override - @SuppressWarnings("unchecked") - public void convertListTagToJSON(Object nbttl, JSONArray ja) throws Exception { - List list = (List) nbtld.get(nbttl); - for (Object e : list) { - Object data = getDataJSON(e); - if (data != null) { - ja.put(data); - } - } - } - - @Override - @Deprecated - @SuppressWarnings("unchecked") - public void convertCompoundTagToJSON(Object nbt, JSONObject jo, JSONObject helper) throws Exception { - Map map = (Map) getMap(nbt); - for (Entry e : map.entrySet()) { - Object nbti = e.getValue(); - Object data = getDataJSON(e.getKey(), nbti, jo, helper); - if (data != null) { - jo.put(e.getKey(), data); - } - } - } - - @Override - @SuppressWarnings("unchecked") - public void convertCompoundTagToJSON(Object nbt, JSONObject jo) throws Exception { - Map map = (Map) getMap(nbt); - for (Entry e : map.entrySet()) { - Object nbti = e.getValue(); - Object data = getDataJSON(nbti); - if (data != null) { - jo.put(e.getKey(), data); - } - } - } - - @Override - @Deprecated - @SuppressWarnings("unchecked") - public Object convertJSONToCompoundTag(JSONObject jo, JSONObject helper) throws Exception { - Map value = new HashMap<>(); - Iterator it = jo.keys(); - while (it.hasNext()) { - String e = it.next(); - value.put(e, createDataJSON(e, jo, helper)); - } - Object ret = getNewNBTTagCompound(); - nbttcm.set(ret, value); - return ret; - } - - @Override - @SuppressWarnings("unchecked") - public Object convertJSONToCompoundTag(JSONObject jo) throws Exception { - Map value = new HashMap<>(); - Iterator it = jo.keys(); - while (it.hasNext()) { - String e = it.next(); - value.put(e, createDataJSON(e, jo)); - } - Object ret = getNewNBTTagCompound(); - nbttcm.set(ret, value); - return ret; - } - - @Override - @Deprecated - @SuppressWarnings({"rawtypes", "unchecked"}) - public Object convertJSONToListTag(JSONArray ja, JSONArray helper) throws Exception { - List value = new ArrayList(); - for (int i = 0; i < ja.length(); i++) { - value.add(createDataJSON(i, ja, helper)); - } - Object ret = getNewNBTTagList(); - nbtld.set(ret, value); - if (value.size() > 0) { - nbtlt.set(ret, gti.invoke(value.get(0))); - } - return ret; - } - - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - public Object convertJSONToListTag(JSONArray ja) throws Exception { - List value = new ArrayList(); - for (int i = 0; i < ja.length(); i++) { - value.add(createDataJSON(i, ja)); - } - Object ret = getNewNBTTagList(); - nbtld.set(ret, value); - if (value.size() > 0) { - nbtlt.set(ret, gti.invoke(value.get(0))); - } - return ret; - } - - @Override - @Deprecated - public Object getDataJSON(String key, Object nbt, JSONObject jo, JSONObject helper) throws Exception { - int i = ((byte) gti.invoke(nbt)); - Object ret = null; - Object help = i; - switch (i) { - case NBTConstants.TYPE_BYTE: - ret = nbtbd.get(nbt); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsd.get(nbt); - break; - case NBTConstants.TYPE_INT: - ret = nbtid.get(nbt); - break; - case NBTConstants.TYPE_LONG: - ret = nbtlod.get(nbt); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfd.get(nbt); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdd.get(nbt); - break; - case NBTConstants.TYPE_BYTE_ARRAY: - ret = nbtbad.get(nbt); - break; - case NBTConstants.TYPE_STRING: - ret = nbtstd.get(nbt); - break; - case NBTConstants.TYPE_LIST: { - JSONArray ja1 = new JSONArray(); - JSONArray helper1 = new JSONArray(); - convertListTagToJSON(nbt, ja1, helper1); - ret = ja1; - help = helper1; - break; - } - case NBTConstants.TYPE_COMPOUND: - JSONObject jo1 = new JSONObject(); - JSONObject helper1 = new JSONObject(); - convertCompoundTagToJSON(nbt, jo1, helper1); - ret = jo1; - help = helper1; - break; - case NBTConstants.TYPE_INT_ARRAY: - ret = nbtiad.get(nbt); - break; - } - if (ret != null) { - helper.put(key, help); - } - return ret; - } - - @Override - public JSONArray getDataJSON(Object nbt) throws Exception { - int i = ((byte) gti.invoke(nbt)); - Object ret = null; - switch (i) { - case NBTConstants.TYPE_BYTE: - ret = nbtbd.get(nbt); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsd.get(nbt); - break; - case NBTConstants.TYPE_INT: - ret = nbtid.get(nbt); - break; - case NBTConstants.TYPE_LONG: - ret = nbtlod.get(nbt); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfd.get(nbt); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdd.get(nbt); - break; - case NBTConstants.TYPE_BYTE_ARRAY: - ret = nbtbad.get(nbt); - break; - case NBTConstants.TYPE_STRING: - ret = nbtstd.get(nbt); - break; - case NBTConstants.TYPE_LIST: { - JSONArray ja1 = new JSONArray(); - convertListTagToJSON(nbt, ja1); - ret = ja1; - break; - } - case NBTConstants.TYPE_COMPOUND: - JSONObject jo1 = new JSONObject(); - convertCompoundTagToJSON(nbt, jo1); - ret = jo1; - break; - case NBTConstants.TYPE_INT_ARRAY: - ret = nbtiad.get(nbt); - break; - } - if (ret == null) { - return null; - } - return new JSONArray(new Object[]{i, ret}); - } - - @Override - public Object getDataJSON(Object nbt, JSONArray ja, JSONArray helper) throws Exception { - int i = ((byte) gti.invoke(nbt)); - Object ret = null; - Object help = i; - switch (i) { - case NBTConstants.TYPE_BYTE: - ret = nbtbd.get(nbt); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsd.get(nbt); - break; - case NBTConstants.TYPE_INT: - ret = nbtid.get(nbt); - break; - case NBTConstants.TYPE_LONG: - ret = nbtlod.get(nbt); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfd.get(nbt); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdd.get(nbt); - break; - case NBTConstants.TYPE_BYTE_ARRAY: - ret = nbtbad.get(nbt); - break; - case NBTConstants.TYPE_STRING: - ret = nbtstd.get(nbt); - break; - case NBTConstants.TYPE_LIST: { - JSONArray ja1 = new JSONArray(); - JSONArray helper1 = new JSONArray(); - convertListTagToJSON(nbt, ja1, helper1); - ret = ja1; - break; - } - case NBTConstants.TYPE_COMPOUND: - JSONObject jo1 = new JSONObject(); - JSONObject helper1 = new JSONObject(); - convertCompoundTagToJSON(nbt, jo1, helper1); - ret = jo1; - help = helper1; - break; - case NBTConstants.TYPE_INT_ARRAY: - ret = nbtiad.get(nbt); - break; - } - if (ret != null) { - helper.put(help); - } - return ret; - } - - @Override - public Object createDataJSON(String key, JSONObject jo, JSONObject helper) throws Exception { - Object help = helper.get(key); - Object ret = null; - if (help instanceof JSONObject) { - JSONObject jo1 = jo.getJSONObject(key); - JSONObject helper1 = (JSONObject) help; - ret = convertJSONToCompoundTag(jo1, helper1); - } else if (help instanceof JSONArray) { - JSONArray ja1 = jo.getJSONArray(key); - JSONArray helper1 = (JSONArray) help; - ret = convertJSONToListTag(ja1, helper1); - } else { - int i = (int) help; - switch (i) { - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance(getByte(jo.get(key))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance(getShort(jo.get(key))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance(getInt(jo.get(key))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtloc.newInstance(getLong(jo.get(key))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance(getFloat(jo.get(key))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance(getDouble(jo.get(key))); - break; - case NBTConstants.TYPE_BYTE_ARRAY: { - JSONArray ja = jo.getJSONArray(key); - byte[] b = new byte[ja.length()]; - for (int a = 0; a < ja.length(); a++) { - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance(b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance((String) jo.get(key)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for (int a = 0; a < ja.length(); a++) { - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance(b); - } - } - return ret; - } - - @Override - public Object createDataJSON(String key, JSONObject jo) throws Exception { - JSONArray j = jo.getJSONArray(key); - Object ret = null; - int i = j.getInt(0); - switch (i) { - case NBTConstants.TYPE_COMPOUND: - ret = convertJSONToCompoundTag(j.getJSONObject(1)); - break; - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance("", getByte(j.get(1))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance("", getShort(j.get(1))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance("", getInt(j.get(1))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtloc.newInstance("", getLong(j.get(1))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance("", getFloat(j.get(1))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance("", getDouble(j.get(1))); - break; - case NBTConstants.TYPE_BYTE_ARRAY: { - JSONArray ja = j.getJSONArray(1); - byte[] b = new byte[ja.length()]; - for (int a = 0; a < ja.length(); a++) { - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance("", b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance("", j.get(1)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for (int a = 0; a < ja.length(); a++) { - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance("", b); - case NBTConstants.TYPE_LIST: - ret = convertJSONToListTag(j.getJSONArray(1)); - break; - } - return ret; - } - - @Override - public byte getByte(Object o) { - if (o.getClass().equals(Integer.class)) { - return (byte) (int) o; - } - if (o.getClass().equals(Short.class)) { - return (byte) (short) o; - } - if (o.getClass().equals(Integer.class)) { - return (byte) (int) o; - } - return (byte) o; - } - - @Override - public short getShort(Object o) { - if (o.getClass().equals(Integer.class)) { - return (short) (int) o; - } - if (o.getClass().equals(Byte.class)) { - return (byte) o; - } - if (o.getClass().equals(Integer.class)) { - return (short) (int) o; - } - return (short) o; - } - - @Override - public int getInt(Object o) { - if (o.getClass().equals(Short.class)) { - return (short) o; - } - if (o.getClass().equals(Byte.class)) { - return (byte) o; - } - return (int) o; - } - - @Override - public double getDouble(Object o) { - if (o.getClass().equals(Float.class)) { - return (float) o; - } - if (o.getClass().equals(Long.class)) { - return (long) o; - } - if (o.getClass().equals(Integer.class)) { - return (int) o; - } - return (double) o; - } - - @Override - public float getFloat(Object o) { - if (o.getClass().equals(Double.class)) { - return (float) (double) o; - } - if (o.getClass().equals(Long.class)) { - return (long) o; - } - if (o.getClass().equals(Integer.class)) { - return (int) o; - } - return (float) o; - } - - @Override - public long getLong(Object o) { - if (o.getClass().equals(Float.class)) { - return (long) (float) o; - } - if (o.getClass().equals(Double.class)) { - return (long) (double) o; - } - if (o.getClass().equals(Integer.class)) { - return (int) o; - } - return (long) o; - } - - @Override - public Object createDataJSON(int key, JSONArray jo, JSONArray helper) throws Exception { - Object help = helper.get(key); - Object ret = null; - if (help instanceof JSONObject) { - JSONObject jo1 = jo.getJSONObject(key); - JSONObject helper1 = (JSONObject) help; - return convertJSONToCompoundTag(jo1, helper1); - } else if (help instanceof JSONArray) { - JSONArray ja1 = jo.getJSONArray(key); - JSONArray helper1 = (JSONArray) help; - return convertJSONToListTag(ja1, helper1); - } else { - int i = (int) help; - switch (i) { - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance(getByte(jo.get(key))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance(getShort(jo.get(key))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance(getInt(jo.get(key))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtlc.newInstance(getLong(jo.get(key))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance(getFloat(jo.get(key))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance(getDouble(jo.get(key))); - break; - case NBTConstants.TYPE_BYTE_ARRAY: { - JSONArray ja = jo.getJSONArray(key); - byte[] b = new byte[ja.length()]; - for (int a = 0; a < ja.length(); a++) { - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance(b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance((String) jo.get(key)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for (int a = 0; a < ja.length(); a++) { - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance(b); - } - } - return ret; - } - - @Override - public Object createDataJSON(int key, JSONArray jo) throws Exception { - JSONArray j = jo.getJSONArray(key); - Object ret = null; - int i = j.getInt(0); - switch (i) { - case NBTConstants.TYPE_COMPOUND: - ret = convertJSONToCompoundTag(j.getJSONObject(1)); - break; - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance("", getByte(j.get(1))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance("", getShort(j.get(1))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance("", getInt(j.get(1))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtloc.newInstance("", getLong(j.get(1))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance("", getFloat(j.get(1))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance("", getDouble(j.get(1))); - break; - case NBTConstants.TYPE_BYTE_ARRAY: { - JSONArray ja = j.getJSONArray(1); - byte[] b = new byte[ja.length()]; - for (int a = 0; a < ja.length(); a++) { - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance("", b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance("", j.get(1)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for (int a = 0; a < ja.length(); a++) { - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance("", b); - case NBTConstants.TYPE_LIST: - ret = convertJSONToListTag(j.getJSONArray(1)); - break; - } - return ret; - } - - @Override - public boolean compareBaseTag(Object tag, Object tag1) throws Exception { - int i = ((byte) gti.invoke(tag)); - int i1 = ((byte) gti.invoke(tag1)); - if (i != i1) { - return false; - } - switch (i) { - case NBTConstants.TYPE_BYTE: - Byte b = (byte) nbtbd.get(tag); - Byte b1 = (byte) nbtbd.get(tag1); - return b.equals(b1); - case NBTConstants.TYPE_SHORT: - Short s = (short) nbtsd.get(tag); - Short s1 = (short) nbtsd.get(tag1); - return s.equals(s1); - case NBTConstants.TYPE_INT: - Integer a = (int) nbtid.get(tag); - Integer a1 = (int) nbtid.get(tag1); - return a.equals(a1); - case NBTConstants.TYPE_LONG: - Long l = (long) nbtlod.get(tag); - Long l1 = (long) nbtlod.get(tag1); - return l.equals(l1); - case NBTConstants.TYPE_FLOAT: - Float f = (float) nbtfd.get(tag); - Float f1 = (float) nbtfd.get(tag1); - return f.equals(f1); - case NBTConstants.TYPE_DOUBLE: - Double d = (double) nbtdd.get(tag); - Double d1 = (double) nbtdd.get(tag1); - return d.equals(d1); - case NBTConstants.TYPE_BYTE_ARRAY: - byte[] ba = (byte[]) nbtbad.get(tag); - byte[] ba1 = (byte[]) nbtbad.get(tag1); - return Arrays.equals(ba, ba1); - case NBTConstants.TYPE_STRING: - String st = (String) nbtstd.get(tag); - String st1 = (String) nbtstd.get(tag1); - return st.equals(st1); - case NBTConstants.TYPE_LIST: { - return compareListTag(tag, tag1); - } - case NBTConstants.TYPE_COMPOUND: - return compareCompoundTag(tag, tag1); - case NBTConstants.TYPE_INT_ARRAY: - int[] ia = (int[]) nbtiad.get(tag); - int[] ia1 = (int[]) nbtiad.get(tag); - return Arrays.equals(ia, ia1); - } - return false; - } - - @Override - @SuppressWarnings("unchecked") - public boolean compareCompoundTag(Object tag, Object tag1) throws Exception { - Map map = (Map) getMap(tag); - Map map1 = (Map) getMap(tag1); - if (map.size() != map1.size()) { - return false; - } - if (!map.keySet().containsAll(map1.keySet())) { - return false; - } - for (Entry e : map.entrySet()) { - Object o = e.getValue(); - Object o1 = map1.get(e.getKey()); - if (!compareBaseTag(o, o1)) { - return false; - } - } - return true; - } - - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - public boolean compareListTag(Object tag, Object tag1) throws Exception { - List list = (List) nbtld.get(tag); - List list1 = (List) nbtld.get(tag1); - if (list.size() != list1.size()) { - return false; - } - if (list.isEmpty() && list1.isEmpty()) { - return true; - } - List copy = new ArrayList(list); - List copy1 = new ArrayList(list1); - Iterator it = copy.iterator(); - while (it.hasNext()) { - Object o = it.next(); - Iterator it1 = copy1.iterator(); - boolean cont = false; - while (it1.hasNext()) { - Object o1 = it1.next(); - if (compareBaseTag(o, o1)) { - it1.remove(); - it.remove(); - cont = true; - break; - } - } - if (!cont) { - return false; - } - } - return copy.isEmpty() && copy1.isEmpty(); - } - - public Object getAttribute(Object compound) throws Exception { - return a.invoke(null, compound); - } - - public Map getAttributes(Object attribs) throws Exception { - Map r = new HashMap<>(); - for (int i = 0; i < getSize(attribs); i++) { - Object compound = g.invoke(attribs, i); - Object attrib = a.invoke(null, compound); - if (attrib != null) { - UUID uuid = (UUID) ama.invoke(attrib); - if (uuid.getLeastSignificantBits() != 0L && uuid.getMostSignificantBits() != 0L) { - r.put(i, attrib); - } - } - } - return r; - } - - @Override - public boolean compare(ItemStack is1, ItemStack is2) { - if (is1.getType().equals(is2.getType())) { - if (is1.getDurability() == is2.getDurability()) { - try { - Object nis1 = getNMSCopy(is1); - Object nis2 = getNMSCopy(is2); - Object tis1 = getTag(nis1); - Object tis2 = getTag(nis2); - if (tis1 != null && tis2 == null) { - return isEmpty(tis1); - } - if (tis1 == null && tis2 != null) { - return isEmpty(tis2); - } - return tis1 == null && tis2 == null || compareCompoundTag(tis1, tis2); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - return false; - } - - @Override - public boolean canMerge(ItemStack add, ItemStack to) { - return compare(add, to); - } - - @Override - public boolean isModified(ItemStack is) { - ItemStack is1 = is.clone(); - is1.setAmount(1); - ItemStack is2 = new ItemStack(is.getType(), 1, is.getDurability()); - return !is1.equals(is2); - } - - @Override - public void sortByMaterial(List items) { - items.sort(new MaterialComparator()); - } - - public class MaterialComparator implements Comparator { - @Override - public int compare(ItemStack arg0, ItemStack arg1) { - return arg0.getType().name().compareTo(arg1.getType().name()); - } - } - - @Override - public void sortByName(List items) { - items.sort(new NameComparator()); - } - - public class NameComparator implements Comparator { - @Override - public int compare(ItemStack arg0, ItemStack arg1) { - int i = 0; - try { - i = ChatColor.stripColor(getName(arg0)).compareTo(ChatColor.stripColor(getName(arg1))); - } catch (Exception e) { - e.printStackTrace(); - } - return i; - } - } - - @Override - public void sortByAmount(List items) { - items.sort(new AmountComparator()); - } - - public class AmountComparator implements Comparator { - @Override - public int compare(ItemStack arg0, ItemStack arg1) { - int i = arg1.getAmount() - arg0.getAmount(); - if (i == 0) { - try { - i = ChatColor.stripColor(getName(arg0)).compareTo(ChatColor.stripColor(getName(arg1))); - } catch (Exception e) { - e.printStackTrace(); - } - } - return i; - } - } - - @Override - public ItemStack convertJSONToItemStack(JSONObject jo) throws Exception { - Material material = Material.valueOf(jo.getString("material")); - int amount = jo.getInt("amount"); - int durability = jo.getInt("durability"); - ItemStack is = new ItemStack(material, amount, (short) durability); - JSONObject jo1 = jo.getJSONObject("tag"); - if (jo1.length() == 0) { - return is; - } - Object tag = convertJSONToCompoundTag(jo1); - Object nmis = getNMSCopy(is); - setTag(nmis, tag); - is = asBukkitCopy(nmis); - return is; - } - - @Override - public JSONObject convertItemStackToJSON(ItemStack is) throws Exception { - JSONObject jo = new JSONObject(); - jo.put("material", is.getType().name()); - jo.put("amount", is.getAmount()); - jo.put("durability", is.getDurability()); - JSONObject jo2 = new JSONObject(); - Object nmis = getNMSCopy(is); - Object tag = getTag(nmis); - if (tag != null) { - convertCompoundTagToJSON(tag, jo2); - } - jo.put("tag", jo2); - return jo; - } -} diff --git a/src/main/java/me/skymc/taboolib/nms/item/impl/_1710ItemUtils.java b/src/main/java/me/skymc/taboolib/nms/item/impl/_1710ItemUtils.java deleted file mode 100644 index d55bc26..0000000 --- a/src/main/java/me/skymc/taboolib/nms/item/impl/_1710ItemUtils.java +++ /dev/null @@ -1,1218 +0,0 @@ -package me.skymc.taboolib.nms.item.impl; - -import me.skymc.taboolib.json.JSONArray; -import me.skymc.taboolib.json.JSONObject; -import me.skymc.taboolib.nms.NMSUtils; -import me.skymc.taboolib.nms.item.IDabItemUtils; -import me.skymc.taboolib.nms.nbt.NBTConstants; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.*; -import java.util.Map.Entry; - -public class _1710ItemUtils implements IDabItemUtils{ - - public boolean banner = getBanner(); - - public boolean getBanner(){ - try{ - Material m = Material.valueOf("BANNER"); - return true; - } catch (Exception ignored) { - } - return false; - } - - @Override - public boolean hasBanner(){ - return banner; - } - - public Class nmis = NMSUtils.getClass("net.minecraft.item.ItemStack"), cis = NMSUtils.getOBCClass("inventory.CraftItemStack"); - public Method nmscopy = NMSUtils.getMethodSilent(cis, "asNMSCopy", ItemStack.class); - - @Override - public Object getNMSCopy(ItemStack is) throws Exception{ - return nmscopy.invoke(null, is); - } - - public Method hastag = NMSUtils.getMethodSilent(nmis, "func_77942_o"); - - @Override - public boolean hasTag(Object is) throws Exception{ - return (boolean)hastag.invoke(is); - } - - public Method acm = NMSUtils.getMethodSilent(cis, "asCraftMirror", nmis); - - @Override - public ItemStack asCraftMirror(Object nis) throws Exception{ - return (ItemStack)acm.invoke(null, nis); - } - - public Class ni = NMSUtils.getClass("net.minecraft.item.Item"); - - public Method abc = NMSUtils.getMethodSilent(cis, "asBukkitCopy", nmis); - - @Override - public ItemStack asBukkitCopy(Object nmis) throws Exception{ - return (ItemStack)abc.invoke(null, nmis); - } - - public Method gn = NMSUtils.getMethodSilent(nmis, "func_82833_r"); - - @Override - public String getName(ItemStack is){ - try{ - return (String)gn.invoke(getNMSCopy(is)); - }catch(Exception e){ - return null; - } - } - - public Method gi = NMSUtils.getMethodSilent(nmis, "func_77973_b"), ia = getA(); - - @Override - public Object getItem(Object nis) throws Exception{ - return gi.invoke(nis); - } - - @Override - public Method getA(){ - return NMSUtils.getMethodSilent(ni, "func_77653_i", nmis); - } - - @Override - public String getRawName(ItemStack is){ - try{ - Object nis = getNMSCopy(is); - return (String)ia.invoke(gi.invoke(nis), nis); - }catch(Exception e){ - return null; - } - } - - public Method gin = NMSUtils.getMethodSilent(ni, "getLabel"); - - @Override - public String getItemName(ItemStack is){ - try{ - return (String)gin.invoke(gi.invoke(getNMSCopy(is))); - }catch(Exception e){ - return null; - } - } - - public Object registry = getRegistry(); - - @Override - public Object getRegistry(){ - try{ - return NMSUtils.getFieldSilent(ni, "REGISTRY", "field_150901_e").get(null); - } catch (Exception ignored) { - } - return null; - } - - public Class nmrs = NMSUtils.getClass("net.minecraft.util.registry.RegistrySimple", "net.minecraft.util.RegistrySimple"); - - public Field nmrsc = NMSUtils.getField(nmrs, "field_82596_a"); - - @Override - public String getMinecraftName(ItemStack is){ - String name = getItemName(is); - try{ - Map m = (Map)nmrsc.get(registry); - for(Entry e : m.entrySet()){ - Object item = e.getValue(); - String s = (String)gin.invoke(item); - if(name.equals(s)){ return e.getKey().toString(); } - } - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - public Class nbttc = NMSUtils.getClass("net.minecraft.nbt.NBTTagCompound"); - public Field tag = NMSUtils.getField(nmis, "field_77990_d"); - - @Override - public Object getTag(Object is) throws Exception{ - return tag.get(is); - } - - @Override - public void setTag(Object is, Object tag1) throws Exception{ - tag.set(is, tag1); - } - - public Method nbtcie = NMSUtils.getMethodSilent(nbttc, "func_82582_d"); - - @Override - public boolean isEmpty(Object tag) throws Exception{ - return (boolean)nbtcie.invoke(tag); - } - - public Field nbttcm = NMSUtils.getField(nbttc, "field_74784_a"); - - @Override - public Object getMap(Object tag) throws Exception{ - return nbttcm.get(tag); - } - - public Class nbtb = NMSUtils.getClass("net.minecraft.nbt.NBTBase"); - public Method nbttcs = NMSUtils.getMethodSilent(nbttc, "func_74782_a", String.class, nbtb); - public Method nbttcss = NMSUtils.getMethodSilent(nbttc, "func_74778_a", String.class, String.class); - public Method nbttcsi = NMSUtils.getMethodSilent(nbttc, "func_74768_a", String.class, int.class); - public Method nbttcsd = NMSUtils.getMethodSilent(nbttc, "func_74780_a", String.class, double.class); - public Method nbttcsl = NMSUtils.getMethodSilent(nbttc, "func_74772_a", String.class, long.class); - public Method nbttcss1 = NMSUtils.getMethodSilent(nbttc, "func_74777_a", String.class, short.class); - - @Override - public void set(Object tag, String key, Object value) throws Exception{ - nbttcs.invoke(tag, key, value); - } - - @Override - public void setString(Object tag, String key, String value) throws Exception{ - nbttcss.invoke(tag, key, value); - } - - @Override - public void setShort(Object tag, String key, short value) throws Exception{ - nbttcss1.invoke(tag, key, value); - } - - @Override - public void setInt(Object tag, String key, int i) throws Exception{ - nbttcsi.invoke(tag, key, i); - } - - @Override - public void setDouble(Object tag, String key, double d) throws Exception{ - nbttcsd.invoke(tag, key, d); - } - - @Override - public void setLong(Object tag, String key, long l) throws Exception{ - nbttcsl.invoke(tag, key, l); - } - - public Method nbttchk = NMSUtils.getMethodSilent(nbttc, "func_74764_b", String.class); - - @Override - public boolean hasKey(Object tag, String key) throws Exception{ - return (boolean)nbttchk.invoke(tag, key); - } - - public Method nbttcg = NMSUtils.getMethodSilent(nbttc, "func_74775_l", String.class); - public Method nbttcgs = NMSUtils.getMethodSilent(nbttc, "func_74779_i", String.class); - public Method nbttcgi = NMSUtils.getMethodSilent(nbttc, "func_74762_e", String.class); - public Method nbttcgd = NMSUtils.getMethodSilent(nbttc, "func_74769_h", String.class); - public Method nbttcgl = NMSUtils.getMethodSilent(nbttc, "func_74763_f", String.class); - public Method nbttcgs1 = NMSUtils.getMethodSilent(nbttc, "func_74765_d", String.class); - - @Override - public Object get(Object tag, String key) throws Exception{ - return nbttcg.invoke(tag, key); - } - - @Override - public String getString(Object tag, String key) throws Exception{ - return (String)nbttcgs.invoke(tag, key); - } - - @Override - public int getInt(Object tag, String key) throws Exception{ - return (int)nbttcgi.invoke(tag, key); - } - - @Override - public double getDouble(Object tag, String key) throws Exception{ - return (double)nbttcgd.invoke(tag, key); - } - - @Override - public long getLong(Object tag, String key) throws Exception{ - return (long)nbttcgl.invoke(tag, key); - } - - @Override - public short getShort(Object tag, String key) throws Exception{ - return (short)nbttcgs1.invoke(tag, key); - } - - public Constructor nbttcc = NMSUtils.getConstructorSilent(nbttc); - - @Override - public Object getNewNBTTagCompound() throws Exception{ - return nbttcc.newInstance(); - } - - public Method hkot = NMSUtils.getMethodSilent(nbttc, "func_150297_b", String.class, int.class); - - @Override - public boolean hasAttributeModifiersKey(Object tag) throws Exception{ - return (boolean)hkot.invoke(tag, "AttributeModifiers", 9); - } - - public Class nbttl = NMSUtils.getClass("net.minecraft.nbt.NBTTagList"); - public Method gl = NMSUtils.getMethodSilent(nbttc, "func_150295_c", String.class, int.class); - public Method gb = NMSUtils.getMethodSilent(nbttc, "func_74767_n", String.class); - public Method sb = NMSUtils.getMethodSilent(nbttc, "func_74757_a", String.class, boolean.class); - public Method nbttla = NMSUtils.getMethodSilent(nbttl, "func_74742_a", nbtb); - public Constructor nbttlc = NMSUtils.getConstructorSilent(nbttl); - - @Override - public Object getList(Object tag) throws Exception{ - return gl.invoke(tag, "AttributeModifiers", 9); - } - - @Override - public Object getList(Object tag, String name, int id) throws Exception{ - return gl.invoke(tag, name, id); - } - - @Override - public boolean getUnbreakable(Object tag) throws Exception{ - return (boolean)gb.invoke(tag, "Unbreakable"); - } - - @Override - public void setUnbreakable(Object tag, boolean value) throws Exception{ - sb.invoke(tag, "Unbreakable", value); - } - - @Override - public Object getNewNBTTagList() throws Exception{ - return nbttlc.newInstance(); - } - - @Override - public void addToList(Object taglist, Object nbt) throws Exception{ - nbttla.invoke(taglist, nbt); - } - - public Method gs = NMSUtils.getMethodSilent(nbttl, "func_74745_c"); - - @Override - public int getSize(Object list) throws Exception{ - return (int)gs.invoke(list); - } - - public Method g = NMSUtils.getMethodSilent(nbttl, "func_150305_b", int.class); - - @Override - public Object get(Object tlist, int i) throws Exception{ - return g.invoke(tlist, i); - } - - public Class am = NMSUtils.getClass("net.minecraft.entity.ai.attributes.AttributeModifier"), ga = NMSUtils.getClass("net.minecraft.entity.SharedMonsterAttributes"); - public Method a = NMSUtils.getMethodSilent(ga, "func_111259_a", nbttc), ama = NMSUtils.getMethodSilent(am, "func_111167_a"); - - public Method gti = NMSUtils.getMethodSilent(nbtb, "func_74732_a"); - - public Class nbtby = NMSUtils.getClass("net.minecraft.nbt.NBTTagByte"); - public Class nbtba = NMSUtils.getClass("net.minecraft.nbt.NBTTagByteArray"); - public Class nbtd = NMSUtils.getClass("net.minecraft.nbt.NBTTagDouble"); - public Class nbtf = NMSUtils.getClass("net.minecraft.nbt.NBTTagFloat"); - public Class nbti = NMSUtils.getClass("net.minecraft.nbt.NBTTagInt"); - public Class nbtia = NMSUtils.getClass("net.minecraft.nbt.NBTTagIntArray"); - public Class nbtl = NMSUtils.getClass("net.minecraft.nbt.NBTTagList"); - public Class nbtlo = NMSUtils.getClass("net.minecraft.nbt.NBTTagLong"); - public Class nbts = NMSUtils.getClass("net.minecraft.nbt.NBTTagShort"); - public Class nbtst = NMSUtils.getClass("net.minecraft.nbt.NBTTagString"); - - public Constructor nbtbc = NMSUtils.getConstructorSilent(nbtby, byte.class); - public Constructor nbtbac = NMSUtils.getConstructorSilent(nbtba, byte[].class); - public Constructor nbtdc = NMSUtils.getConstructorSilent(nbtd, double.class); - public Constructor nbtfc = NMSUtils.getConstructorSilent(nbtf, float.class); - public Constructor nbtic = NMSUtils.getConstructorSilent(nbti, int.class); - public Constructor nbtiac = NMSUtils.getConstructorSilent(nbtia, int[].class); - public Constructor nbtlc = NMSUtils.getConstructorSilent(nbtl); - public Constructor nbtloc = NMSUtils.getConstructorSilent(nbtlo, long.class); - public Constructor nbtsc = NMSUtils.getConstructorSilent(nbts, short.class); - public Constructor nbtstc = NMSUtils.getConstructorSilent(nbtst, String.class); - - public Field nbtbd = NMSUtils.getField(nbtby, "field_74756_a"); - public Field nbtbad = NMSUtils.getField(nbtba, "field_74754_a"); - public Field nbtdd = NMSUtils.getField(nbtd, "field_74755_a"); - public Field nbtfd = NMSUtils.getField(nbtf, "field_74750_a"); - public Field nbtid = NMSUtils.getField(nbti, "field_74748_a"); - public Field nbtiad = NMSUtils.getField(nbtia, "field_74749_a"); - public Field nbtld = NMSUtils.getField(nbtl, "field_74747_a"); - public Field nbtlt = NMSUtils.getField(nbtl, "field_74746_b"); - public Field nbtlod = NMSUtils.getField(nbtlo, "field_74753_a"); - public Field nbtsd = NMSUtils.getField(nbts, "field_74752_a"); - public Field nbtstd = NMSUtils.getField(nbtst, "field_74751_a"); - - @Override - public Object getNewNBTTagByte(byte value) throws Exception{ - return nbtbc.newInstance(value); - } - - @Override - public Object getNewNBTTagByteArray(byte[] value) throws Exception{ - return nbtbac.newInstance(value); - } - - @Override - public Object getData(Object nbt) throws Exception{ - int i = ((byte)gti.invoke(nbt)); - switch(i){ - case NBTConstants.TYPE_BYTE: - return nbtbd.get(nbt); - case NBTConstants.TYPE_SHORT: - return nbtsd.get(nbt); - case NBTConstants.TYPE_INT: - return nbtid.get(nbt); - case NBTConstants.TYPE_LONG: - return nbtlod.get(nbt); - case NBTConstants.TYPE_FLOAT: - return nbtfd.get(nbt); - case NBTConstants.TYPE_DOUBLE: - return nbtdd.get(nbt); - case NBTConstants.TYPE_BYTE_ARRAY: - return nbtbad.get(nbt); - case NBTConstants.TYPE_STRING: - return nbtstd.get(nbt); - case NBTConstants.TYPE_LIST: - return convertListTagToValueList(nbt); - case NBTConstants.TYPE_COMPOUND: - return convertCompoundTagToValueMap(nbt); - case NBTConstants.TYPE_INT_ARRAY: - return nbtiad.get(nbt); - } - return null; - } - - @Override - @SuppressWarnings("unchecked") - public Object createData(Object value) throws Exception{ - if(value.getClass().equals(byte.class)){ return nbtbc.newInstance(value); } - if(value.getClass().equals(byte[].class)){ return nbtbac.newInstance(value); } - if(value.getClass().isAssignableFrom(Map.class)){ return convertValueMapToCompoundTag((Map)value); } - if(value.getClass().equals(double.class)){ return nbtdc.newInstance(value); } - if(value.getClass().equals(float.class)){ return nbtfc.newInstance(value); } - if(value.getClass().equals(int.class)){ return nbtic.newInstance(value); } - if(value.getClass().equals(int[].class)){ return nbtiac.newInstance(value); } - if(value.getClass().isAssignableFrom(List.class)){ return convertValueListToListTag((List)value); } - if(value.getClass().equals(long.class)){ return nbtloc.newInstance(value); } - if(value.getClass().equals(short.class)){ return nbtsc.newInstance(value); } - if(value.getClass().equals(String.class)){ return nbtstc.newInstance(value); } - return null; - } - - @Override - @SuppressWarnings({ "unchecked" }) - public Map convertCompoundTagToValueMap(Object nbt) throws Exception{ - Map ret = new HashMap<>(); - Map map = (Map)getMap(nbt); - for(Entry e : map.entrySet()){ - Object nbti = e.getValue(); - Object data = getData(nbti); - if(data != null){ - ret.put(e.getKey(), data); - } - } - return ret; - } - - @Override - @SuppressWarnings("unchecked") - public List convertListTagToValueList(Object nbttl) throws Exception{ - List ret = new ArrayList<>(); - List list = (List)nbtld.get(nbttl); - for(Object e : list){ - Object data = getData(e); - if(data != null){ - ret.add(data); - } - } - return ret; - } - - @Override - public Object convertValueMapToCompoundTag(Map map) throws Exception{ - Map value = new HashMap<>(); - for(Entry e : map.entrySet()){ - value.put(e.getKey(), createData(e.getValue())); - } - Object ret = getNewNBTTagCompound(); - nbttcm.set(ret, value); - return ret; - } - - @Override - public Object convertValueListToListTag(List list) throws Exception{ - List value = new ArrayList<>(); - for(Object e : list){ - value.add(createData(e)); - } - Object ret = getNewNBTTagList(); - nbttcm.set(ret, value); - if(value.size() > 0){ - nbtlt.set(ret, gti.invoke(value.get(0))); - } - return ret; - } - - @Override - @Deprecated - @SuppressWarnings("unchecked") - public void convertListTagToJSON(Object nbttl, JSONArray ja, JSONArray helper) throws Exception{ - List list = (List)nbtld.get(nbttl); - for(Object e : list){ - Object data = getDataJSON(e, ja, helper); - if(data != null){ - ja.put(data); - } - } - } - - @Override - @SuppressWarnings("unchecked") - public void convertListTagToJSON(Object nbttl, JSONArray ja) throws Exception{ - List list = (List)nbtld.get(nbttl); - for(Object e : list){ - Object data = getDataJSON(e); - if(data != null){ - ja.put(data); - } - } - } - - @Override - @Deprecated - @SuppressWarnings("unchecked") - public void convertCompoundTagToJSON(Object nbt, JSONObject jo, JSONObject helper) throws Exception{ - Map map = (Map)getMap(nbt); - for(Entry e : map.entrySet()){ - Object nbti = e.getValue(); - Object data = getDataJSON(e.getKey(), nbti, jo, helper); - if(data != null){ - jo.put(e.getKey(), data); - } - } - } - - @Override - @SuppressWarnings("unchecked") - public void convertCompoundTagToJSON(Object nbt, JSONObject jo) throws Exception{ - Map map = (Map)getMap(nbt); - for(Entry e : map.entrySet()){ - Object nbti = e.getValue(); - Object data = getDataJSON(nbti); - if(data != null){ - jo.put(e.getKey(), data); - } - } - } - - @Override - @Deprecated - @SuppressWarnings("unchecked") - public Object convertJSONToCompoundTag(JSONObject jo, JSONObject helper) throws Exception{ - Map value = new HashMap<>(); - Iterator it = jo.keys(); - while(it.hasNext()){ - String e = it.next(); - value.put(e, createDataJSON(e, jo, helper)); - } - Object ret = getNewNBTTagCompound(); - nbttcm.set(ret, value); - return ret; - } - - @Override - @SuppressWarnings("unchecked") - public Object convertJSONToCompoundTag(JSONObject jo) throws Exception{ - Map value = new HashMap<>(); - Iterator it = jo.keys(); - while(it.hasNext()){ - String e = it.next(); - value.put(e, createDataJSON(e, jo)); - } - Object ret = getNewNBTTagCompound(); - nbttcm.set(ret, value); - return ret; - } - - @Override - @Deprecated - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Object convertJSONToListTag(JSONArray ja, JSONArray helper) throws Exception{ - List value = new ArrayList(); - for(int i = 0; i < ja.length(); i++){ - value.add(createDataJSON(i, ja, helper)); - } - Object ret = getNewNBTTagList(); - nbtld.set(ret, value); - if(value.size() > 0){ - nbtlt.set(ret, gti.invoke(value.get(0))); - } - return ret; - } - - @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Object convertJSONToListTag(JSONArray ja) throws Exception{ - List value = new ArrayList(); - for(int i = 0; i < ja.length(); i++){ - value.add(createDataJSON(i, ja)); - } - Object ret = getNewNBTTagList(); - nbtld.set(ret, value); - if(value.size() > 0){ - nbtlt.set(ret, gti.invoke(value.get(0))); - } - return ret; - } - - @Override - @Deprecated - public Object getDataJSON(String key, Object nbt, JSONObject jo, JSONObject helper) throws Exception{ - int i = ((byte)gti.invoke(nbt)); - Object ret = null; - Object help = i; - switch(i){ - case NBTConstants.TYPE_BYTE: - ret = nbtbd.get(nbt); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsd.get(nbt); - break; - case NBTConstants.TYPE_INT: - ret = nbtid.get(nbt); - break; - case NBTConstants.TYPE_LONG: - ret = nbtlod.get(nbt); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfd.get(nbt); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdd.get(nbt); - break; - case NBTConstants.TYPE_BYTE_ARRAY: - ret = nbtbad.get(nbt); - break; - case NBTConstants.TYPE_STRING: - ret = nbtstd.get(nbt); - break; - case NBTConstants.TYPE_LIST:{ - JSONArray ja1 = new JSONArray(); - JSONArray helper1 = new JSONArray(); - convertListTagToJSON(nbt, ja1, helper1); - ret = ja1; - help = helper1; - break; - } - case NBTConstants.TYPE_COMPOUND: - JSONObject jo1 = new JSONObject(); - JSONObject helper1 = new JSONObject(); - convertCompoundTagToJSON(nbt, jo1, helper1); - ret = jo1; - help = helper1; - break; - case NBTConstants.TYPE_INT_ARRAY: - ret = nbtiad.get(nbt); - break; - } - if(ret != null){ - helper.put(key, help); - } - return ret; - } - - @Override - public JSONArray getDataJSON(Object nbt) throws Exception{ - int i = ((byte)gti.invoke(nbt)); - Object ret = null; - switch(i){ - case NBTConstants.TYPE_BYTE: - ret = nbtbd.get(nbt); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsd.get(nbt); - break; - case NBTConstants.TYPE_INT: - ret = nbtid.get(nbt); - break; - case NBTConstants.TYPE_LONG: - ret = nbtlod.get(nbt); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfd.get(nbt); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdd.get(nbt); - break; - case NBTConstants.TYPE_BYTE_ARRAY: - ret = nbtbad.get(nbt); - break; - case NBTConstants.TYPE_STRING: - ret = nbtstd.get(nbt); - break; - case NBTConstants.TYPE_LIST:{ - JSONArray ja1 = new JSONArray(); - convertListTagToJSON(nbt, ja1); - ret = ja1; - break; - } - case NBTConstants.TYPE_COMPOUND: - JSONObject jo1 = new JSONObject(); - convertCompoundTagToJSON(nbt, jo1); - ret = jo1; - break; - case NBTConstants.TYPE_INT_ARRAY: - ret = nbtiad.get(nbt); - break; - } - if(ret == null) { - return null; - } - return new JSONArray(new Object[]{ i, ret }); - } - - @Override - public Object getDataJSON(Object nbt, JSONArray ja, JSONArray helper) throws Exception{ - int i = ((byte)gti.invoke(nbt)); - Object ret = null; - Object help = i; - switch(i){ - case NBTConstants.TYPE_BYTE: - ret = nbtbd.get(nbt); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsd.get(nbt); - break; - case NBTConstants.TYPE_INT: - ret = nbtid.get(nbt); - break; - case NBTConstants.TYPE_LONG: - ret = nbtlod.get(nbt); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfd.get(nbt); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdd.get(nbt); - break; - case NBTConstants.TYPE_BYTE_ARRAY: - ret = nbtbad.get(nbt); - break; - case NBTConstants.TYPE_STRING: - ret = nbtstd.get(nbt); - break; - case NBTConstants.TYPE_LIST:{ - JSONArray ja1 = new JSONArray(); - JSONArray helper1 = new JSONArray(); - convertListTagToJSON(nbt, ja1, helper1); - ret = ja1; - break; - } - case NBTConstants.TYPE_COMPOUND: - JSONObject jo1 = new JSONObject(); - JSONObject helper1 = new JSONObject(); - convertCompoundTagToJSON(nbt, jo1, helper1); - ret = jo1; - help = helper1; - break; - case NBTConstants.TYPE_INT_ARRAY: - ret = nbtiad.get(nbt); - break; - } - if(ret != null){ - helper.put(help); - } - return ret; - } - - @Override - public Object createDataJSON(String key, JSONObject jo, JSONObject helper) throws Exception{ - Object help = helper.get(key); - Object ret = null; - if(help instanceof JSONObject){ - JSONObject jo1 = jo.getJSONObject(key); - JSONObject helper1 = (JSONObject)help; - ret = convertJSONToCompoundTag(jo1, helper1); - }else if(help instanceof JSONArray){ - JSONArray ja1 = jo.getJSONArray(key); - JSONArray helper1 = (JSONArray)help; - ret = convertJSONToListTag(ja1, helper1); - }else{ - int i = (int)help; - switch(i){ - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance(getByte(jo.get(key))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance(getShort(jo.get(key))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance(getInt(jo.get(key))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtloc.newInstance(getLong(jo.get(key))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance(getFloat(jo.get(key))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance(getDouble(jo.get(key))); - break; - case NBTConstants.TYPE_BYTE_ARRAY:{ - JSONArray ja = jo.getJSONArray(key); - byte[] b = new byte[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance(b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance((String)jo.get(key)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance(b); - } - } - return ret; - } - - @Override - public Object createDataJSON(String key, JSONObject jo) throws Exception{ - JSONArray j = jo.getJSONArray(key); - Object ret = null; - int i = j.getInt(0); - switch(i){ - case NBTConstants.TYPE_COMPOUND: - ret = convertJSONToCompoundTag(j.getJSONObject(1)); - break; - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance(getByte(j.get(1))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance(getShort(j.get(1))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance(getInt(j.get(1))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtloc.newInstance(getLong(j.get(1))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance(getFloat(j.get(1))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance(getDouble(j.get(1))); - break; - case NBTConstants.TYPE_BYTE_ARRAY:{ - JSONArray ja = j.getJSONArray(1); - byte[] b = new byte[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance(b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance((String)j.get(1)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance(b); - case NBTConstants.TYPE_LIST: - ret = convertJSONToListTag(j.getJSONArray(1)); - break; - } - return ret; - } - - @Override - public byte getByte(Object o){ - if(o.getClass().equals(Integer.class)){ return (byte)(int)o; } - if(o.getClass().equals(Short.class)){ return (byte)(short)o; } - if(o.getClass().equals(Integer.class)){ return (byte)(int)o; } - return (byte)o; - } - - @Override - public short getShort(Object o){ - if(o.getClass().equals(Integer.class)){ return (short)(int)o; } - if(o.getClass().equals(Byte.class)){ return (byte)o; } - if(o.getClass().equals(Integer.class)){ return (short)(int)o; } - return (short)o; - } - - @Override - public int getInt(Object o){ - if(o.getClass().equals(Short.class)){ return (short)o; } - if(o.getClass().equals(Byte.class)){ return (byte)o; } - return (int)o; - } - - @Override - public double getDouble(Object o){ - if(o.getClass().equals(Float.class)){ return (float)o; } - if(o.getClass().equals(Long.class)){ return (long)o; } - if(o.getClass().equals(Integer.class)){ return (int)o; } - return (double)o; - } - - @Override - public float getFloat(Object o){ - if(o.getClass().equals(Double.class)){ return (float)(double)o; } - if(o.getClass().equals(Long.class)){ return (long)o; } - if(o.getClass().equals(Integer.class)){ return (int)o; } - return (float)o; - } - - @Override - public long getLong(Object o){ - if(o.getClass().equals(Float.class)){ return (long)(float)o; } - if(o.getClass().equals(Double.class)){ return (long)(double)o; } - if(o.getClass().equals(Integer.class)){ return (int)o; } - return (long)o; - } - - @Override - public Object createDataJSON(int key, JSONArray jo, JSONArray helper) throws Exception{ - Object help = helper.get(key); - Object ret = null; - if(help instanceof JSONObject){ - JSONObject jo1 = jo.getJSONObject(key); - JSONObject helper1 = (JSONObject)help; - return convertJSONToCompoundTag(jo1, helper1); - }else if(help instanceof JSONArray){ - JSONArray ja1 = jo.getJSONArray(key); - JSONArray helper1 = (JSONArray)help; - return convertJSONToListTag(ja1, helper1); - }else{ - int i = (int)help; - switch(i){ - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance(getByte(jo.get(key))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance(getShort(jo.get(key))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance(getInt(jo.get(key))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtlc.newInstance(getLong(jo.get(key))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance(getFloat(jo.get(key))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance(getDouble(jo.get(key))); - break; - case NBTConstants.TYPE_BYTE_ARRAY:{ - JSONArray ja = jo.getJSONArray(key); - byte[] b = new byte[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance(b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance((String)jo.get(key)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance(b); - } - } - return ret; - } - - @Override - public Object createDataJSON(int key, JSONArray jo) throws Exception{ - JSONArray j = jo.getJSONArray(key); - Object ret = null; - int i = j.getInt(0); - switch(i){ - case NBTConstants.TYPE_COMPOUND: - ret = convertJSONToCompoundTag(j.getJSONObject(1)); - break; - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance(getByte(j.get(1))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance(getShort(j.get(1))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance(getInt(j.get(1))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtloc.newInstance(getLong(j.get(1))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance(getFloat(j.get(1))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance(getDouble(j.get(1))); - break; - case NBTConstants.TYPE_BYTE_ARRAY:{ - JSONArray ja = j.getJSONArray(1); - byte[] b = new byte[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance(b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance((String)j.get(1)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance(b); - case NBTConstants.TYPE_LIST: - ret = convertJSONToListTag(j.getJSONArray(1)); - break; - } - return ret; - } - - @Override - public boolean compareBaseTag(Object tag, Object tag1) throws Exception{ - int i = ((byte)gti.invoke(tag)); - int i1 = ((byte)gti.invoke(tag1)); - if(i != i1) { - return false; - } - switch(i){ - case NBTConstants.TYPE_BYTE: - Byte b = (byte)nbtbd.get(tag); - Byte b1 = (byte)nbtbd.get(tag1); - return b.equals(b1); - case NBTConstants.TYPE_SHORT: - Short s = (short)nbtsd.get(tag); - Short s1 = (short)nbtsd.get(tag1); - return s.equals(s1); - case NBTConstants.TYPE_INT: - Integer a = (int)nbtid.get(tag); - Integer a1 = (int)nbtid.get(tag1); - return a.equals(a1); - case NBTConstants.TYPE_LONG: - Long l = (long)nbtlod.get(tag); - Long l1 = (long)nbtlod.get(tag1); - return l.equals(l1); - case NBTConstants.TYPE_FLOAT: - Float f = (float)nbtfd.get(tag); - Float f1 = (float)nbtfd.get(tag1); - return f.equals(f1); - case NBTConstants.TYPE_DOUBLE: - Double d = (double)nbtdd.get(tag); - Double d1 = (double)nbtdd.get(tag1); - return d.equals(d1); - case NBTConstants.TYPE_BYTE_ARRAY: - byte[] ba = (byte[])nbtbad.get(tag); - byte[] ba1 = (byte[])nbtbad.get(tag1); - return Arrays.equals(ba, ba1); - case NBTConstants.TYPE_STRING: - String st = (String)nbtstd.get(tag); - String st1 = (String)nbtstd.get(tag1); - return st.equals(st1); - case NBTConstants.TYPE_LIST:{ - return compareListTag(tag, tag1); - } - case NBTConstants.TYPE_COMPOUND: - return compareCompoundTag(tag, tag1); - case NBTConstants.TYPE_INT_ARRAY: - int[] ia = (int[])nbtiad.get(tag); - int[] ia1 = (int[])nbtiad.get(tag); - return Arrays.equals(ia, ia1); - } - return false; - } - - @Override - @SuppressWarnings("unchecked") - public boolean compareCompoundTag(Object tag, Object tag1) throws Exception{ - Map map = (Map)getMap(tag); - Map map1 = (Map)getMap(tag1); - if(map.size() != map1.size()) { - return false; - } - if(!map.keySet().containsAll(map1.keySet())) { - return false; - } - for(Entry e : map.entrySet()){ - Object o = e.getValue(); - Object o1 = map1.get(e.getKey()); - if(!compareBaseTag(o, o1)) { - return false; - } - } - return true; - } - - @Override - @SuppressWarnings({ "unchecked", "rawtypes" }) - public boolean compareListTag(Object tag, Object tag1) throws Exception{ - List list = (List)nbtld.get(tag); - List list1 = (List)nbtld.get(tag1); - if(list.size() != list1.size()) { - return false; - } - Collections.sort(list); - Collections.sort(list1); - Iterator it = list.iterator(); - Iterator it1 = list1.iterator(); - while(it.hasNext() && it1.hasNext()){ - Object o = it.next(); - Object o1 = it1.next(); - if(!compareBaseTag(o, o1)) { - return false; - } - } - return true; - } - - public Field amd = NMSUtils.getField(am, "field_111170_d"); - - @Override - public boolean compare(ItemStack is1, ItemStack is2){ - if(is1.getType().equals(is2.getType())){ - if(is1.getDurability() == is2.getDurability()){ - try { - Object nis1 = getNMSCopy(is1); - Object nis2 = getNMSCopy(is2); - Object tis1 = getTag(nis1); - Object tis2 = getTag(nis2); - if (tis1 != null && tis2 == null) { - return isEmpty(tis1); - } - if (tis1 == null && tis2 != null) { - return isEmpty(tis2); - } - return tis1 == null && tis2 == null || compareCompoundTag(tis1, tis2); - }catch(Exception e){ - e.printStackTrace(); - } - } - } - return false; - } - - @Override - public boolean canMerge(ItemStack add, ItemStack to){ - return compare(add, to); - } - - @Override - public boolean isModified(ItemStack is){ - ItemStack is1 = is.clone(); - is1.setAmount(1); - ItemStack is2 = new ItemStack(is.getType(), 1, is.getDurability()); - return !is1.equals(is2); - } - - @Override - public void sortByMaterial(List items){ - items.sort(new MaterialComparator()); - } - - public class MaterialComparator implements Comparator{ - @Override - public int compare(ItemStack arg0, ItemStack arg1){ - return arg0.getType().name().compareTo(arg1.getType().name()); - } - } - - @Override - public void sortByName(List items){ - items.sort(new NameComparator()); - } - - public class NameComparator implements Comparator{ - @Override - public int compare(ItemStack arg0, ItemStack arg1){ - int i = 0; - try{ - i = ChatColor.stripColor(getName(arg0)).compareTo(ChatColor.stripColor(getName(arg1))); - }catch(Exception e){ - e.printStackTrace(); - } - return i; - } - } - - @Override - public void sortByAmount(List items){ - items.sort(new AmountComparator()); - } - - public class AmountComparator implements Comparator{ - @Override - public int compare(ItemStack arg0, ItemStack arg1){ - int i = arg1.getAmount() - arg0.getAmount(); - if(i == 0){ - try{ - i = ChatColor.stripColor(getName(arg0)).compareTo(ChatColor.stripColor(getName(arg1))); - }catch(Exception e){ - e.printStackTrace(); - } - } - return i; - } - } - - @Override - public ItemStack convertJSONToItemStack(JSONObject jo) throws Exception{ - Material material = Material.valueOf(jo.getString("material")); - int amount = jo.getInt("amount"); - int durability = jo.getInt("durability"); - ItemStack is = new ItemStack(material, amount, (short)durability); - JSONObject jo1 = jo.getJSONObject("tag"); - if(jo1.length() == 0) { - return is; - } - Object tag = convertJSONToCompoundTag(jo1); - Object nmis = getNMSCopy(is); - setTag(nmis, tag); - is = asBukkitCopy(nmis); - return is; - } - - @Override - public JSONObject convertItemStackToJSON(ItemStack is) throws Exception{ - JSONObject jo = new JSONObject(); - jo.put("material", is.getType().name()); - jo.put("amount", is.getAmount()); - jo.put("durability", is.getDurability()); - JSONObject jo2 = new JSONObject(); - Object nmis = getNMSCopy(is); - Object tag = getTag(nmis); - if(tag != null){ - convertCompoundTagToJSON(tag, jo2); - } - jo.put("tag", jo2); - return jo; - } -} diff --git a/src/main/java/me/skymc/taboolib/nms/item/impl/_194ItemUtils.java b/src/main/java/me/skymc/taboolib/nms/item/impl/_194ItemUtils.java deleted file mode 100644 index 016b552..0000000 --- a/src/main/java/me/skymc/taboolib/nms/item/impl/_194ItemUtils.java +++ /dev/null @@ -1,1232 +0,0 @@ -package me.skymc.taboolib.nms.item.impl; - -import me.skymc.taboolib.json.JSONArray; -import me.skymc.taboolib.json.JSONObject; -import me.skymc.taboolib.nms.NMSUtils; -import me.skymc.taboolib.nms.item.IDabItemUtils; -import me.skymc.taboolib.nms.nbt.NBTConstants; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.*; -import java.util.Map.Entry; - -public class _194ItemUtils implements IDabItemUtils{ - - public boolean banner = getBanner(); - - public boolean getBanner(){ - try{ - Material m = Material.valueOf("BANNER"); - return true; - } catch (Exception ignored) { - } - return false; - } - - @Override - public boolean hasBanner(){ - return banner; - } - - public Class nmis = NMSUtils.getNMSClassSilent("ItemStack"), cis = NMSUtils.getOBCClass("inventory.CraftItemStack"); - public Method nmscopy = NMSUtils.getMethodSilent(cis, "asNMSCopy", ItemStack.class); - - @Override - public Object getNMSCopy(ItemStack is) throws Exception{ - return nmscopy.invoke(null, is); - } - - public Method hastag = NMSUtils.getMethodSilent(nmis, "hasTag"); - - @Override - public boolean hasTag(Object is) throws Exception{ - return (boolean)hastag.invoke(is); - } - - public Method acm = NMSUtils.getMethodSilent(cis, "asCraftMirror", nmis); - - @Override - public ItemStack asCraftMirror(Object nis) throws Exception{ - return (ItemStack)acm.invoke(null, nis); - } - - public Method abc = NMSUtils.getMethodSilent(cis, "asBukkitCopy", nmis); - - @Override - public ItemStack asBukkitCopy(Object nmis) throws Exception{ - return (ItemStack)abc.invoke(null, nmis); - } - - public Class ni = NMSUtils.getNMSClassSilent("Item"); - - public Method gn = NMSUtils.getMethodSilent(nmis, "getLabel"); - - @Override - public String getName(ItemStack is){ - try{ - return (String)gn.invoke(getNMSCopy(is)); - }catch(Exception e){ - return null; - } - } - - public Method gi = NMSUtils.getMethodSilent(nmis, "getItem"), ia = getA(); - - @Override - public Object getItem(Object nis) throws Exception{ - return gi.invoke(nis); - } - - @Override - public Method getA(){ - Method m = NMSUtils.getMethodSilent(ni, "a", nmis); - if(m == null){ - m = NMSUtils.getMethodSilent(ni, "n", nmis); - } - return m; - } - - @Override - public String getRawName(ItemStack is){ - try{ - Object nis = getNMSCopy(is); - return (String)ia.invoke(gi.invoke(nis), nis); - }catch(Exception e){ - return null; - } - } - - public Method gin = NMSUtils.getMethodSilent(ni, "getLabel"); - - @Override - public String getItemName(ItemStack is){ - try{ - return (String)gin.invoke(gi.invoke(getNMSCopy(is))); - }catch(Exception e){ - return null; - } - } - - public Object registry = getRegistry(); - - @Override - public Object getRegistry(){ - try{ - return NMSUtils.getFieldSilent(ni, "REGISTRY").get(null); - } catch (Exception ignored) { - } - return null; - } - - public Class nmrs = NMSUtils.getNMSClassSilent("RegistrySimple"); - public Field nmrsc = NMSUtils.getField(nmrs, "c"); - - @Override - public String getMinecraftName(ItemStack is){ - String name = getItemName(is); - try{ - Map m = (Map)nmrsc.get(registry); - for(Entry e : m.entrySet()){ - Object item = e.getValue(); - String s = (String)gin.invoke(item); - if(name.equals(s)){ return e.getKey().toString(); } - } - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - public Class nbttc = NMSUtils.getNMSClassSilent("NBTTagCompound"); - public Field tag = NMSUtils.getField(nmis, "tag"); - - @Override - public Object getTag(Object is) throws Exception{ - return tag.get(is); - } - - @Override - public void setTag(Object is, Object tag1) throws Exception{ - tag.set(is, tag1); - } - - public Method nbtcie = NMSUtils.getMethodSilent(nbttc, "isEmpty"); - - @Override - public boolean isEmpty(Object tag) throws Exception{ - return (boolean)nbtcie.invoke(tag); - } - - public Field nbttcm = NMSUtils.getField(nbttc, "map"); - - @Override - public Object getMap(Object tag) throws Exception{ - return nbttcm.get(tag); - } - - public Class nbtb = NMSUtils.getNMSClassSilent("NBTBase"); - public Method nbttcs = NMSUtils.getMethodSilent(nbttc, "set", String.class, nbtb); - public Method nbttcss = NMSUtils.getMethodSilent(nbttc, "setString", String.class, String.class); - public Method nbttcsi = NMSUtils.getMethodSilent(nbttc, "setInt", String.class, int.class); - public Method nbttcsd = NMSUtils.getMethodSilent(nbttc, "setDouble", String.class, double.class); - public Method nbttcsl = NMSUtils.getMethodSilent(nbttc, "setLong", String.class, long.class); - public Method nbttcss1 = NMSUtils.getMethodSilent(nbttc, "setShort", String.class, short.class); - - @Override - public void set(Object tag, String key, Object value) throws Exception{ - nbttcs.invoke(tag, key, value); - } - - @Override - public void setString(Object tag, String key, String value) throws Exception{ - nbttcss.invoke(tag, key, value); - } - - @Override - public void setShort(Object tag, String key, short value) throws Exception{ - nbttcss1.invoke(tag, key, value); - } - - @Override - public void setInt(Object tag, String key, int i) throws Exception{ - nbttcsi.invoke(tag, key, i); - } - - @Override - public void setDouble(Object tag, String key, double d) throws Exception{ - nbttcsd.invoke(tag, key, d); - } - - @Override - public void setLong(Object tag, String key, long l) throws Exception{ - nbttcsl.invoke(tag, key, l); - } - - public Method nbttchk = NMSUtils.getMethodSilent(nbttc, "hasKey", String.class); - - @Override - public boolean hasKey(Object tag, String key) throws Exception{ - return (boolean)nbttchk.invoke(tag, key); - } - - public Method nbttcg = NMSUtils.getMethodSilent(nbttc, "get", String.class); - public Method nbttcgs = NMSUtils.getMethodSilent(nbttc, "getString", String.class); - public Method nbttcgi = NMSUtils.getMethodSilent(nbttc, "getInt", String.class); - public Method nbttcgd = NMSUtils.getMethodSilent(nbttc, "getDouble", String.class); - public Method nbttcgl = NMSUtils.getMethodSilent(nbttc, "getLong", String.class); - public Method nbttcgs1 = NMSUtils.getMethodSilent(nbttc, "getShort", String.class); - - @Override - public Object get(Object tag, String key) throws Exception{ - return nbttcg.invoke(tag, key); - } - - @Override - public String getString(Object tag, String key) throws Exception{ - return (String)nbttcgs.invoke(tag, key); - } - - @Override - public int getInt(Object tag, String key) throws Exception{ - return (int)nbttcgi.invoke(tag, key); - } - - @Override - public double getDouble(Object tag, String key) throws Exception{ - return (double)nbttcgd.invoke(tag, key); - } - - @Override - public long getLong(Object tag, String key) throws Exception{ - return (long)nbttcgl.invoke(tag, key); - } - - @Override - public short getShort(Object tag, String key) throws Exception{ - return (short)nbttcgs1.invoke(tag, key); - } - - public Constructor nbttcc = NMSUtils.getConstructorSilent(nbttc); - - @Override - public Object getNewNBTTagCompound() throws Exception{ - return nbttcc.newInstance(); - } - - public Method hkot = NMSUtils.getMethodSilent(nbttc, "hasKeyOfType", String.class, int.class); - - @Override - public boolean hasAttributeModifiersKey(Object tag) throws Exception{ - return (boolean)hkot.invoke(tag, "AttributeModifiers", 9); - } - - public Class nbttl = NMSUtils.getNMSClassSilent("NBTTagList"); - public Method gl = NMSUtils.getMethodSilent(nbttc, "getList", String.class, int.class); - public Method gb = NMSUtils.getMethodSilent(nbttc, "getBoolean", String.class); - public Method sb = NMSUtils.getMethodSilent(nbttc, "setBoolean", String.class, boolean.class); - public Method nbttla = NMSUtils.getMethodSilent(nbttl, "add", nbtb); - public Constructor nbttlc = NMSUtils.getConstructorSilent(nbttl); - - @Override - public Object getList(Object tag) throws Exception{ - return gl.invoke(tag, "AttributeModifiers", 9); - } - - @Override - public Object getList(Object tag, String name, int id) throws Exception{ - return gl.invoke(tag, name, id); - } - - @Override - public boolean getUnbreakable(Object tag) throws Exception{ - return (boolean)gb.invoke(tag, "Unbreakable"); - } - - @Override - public void setUnbreakable(Object tag, boolean value) throws Exception{ - sb.invoke(tag, "Unbreakable", value); - } - - @Override - public Object getNewNBTTagList() throws Exception{ - return nbttlc.newInstance(); - } - - @Override - public void addToList(Object taglist, Object nbt) throws Exception{ - nbttla.invoke(taglist, nbt); - } - - public Method gs = NMSUtils.getMethodSilent(nbttl, "size"); - - @Override - public int getSize(Object list) throws Exception{ - return (int)gs.invoke(list); - } - - public Method g = NMSUtils.getMethodSilent(nbttl, "get", int.class); - - @Override - public Object get(Object tlist, int i) throws Exception{ - return g.invoke(tlist, i); - } - - public Method gti = NMSUtils.getMethodSilent(nbtb, "getTypeId"); - - public Class nbtby = NMSUtils.getNMSClassSilent("NBTTagByte"); - public Class nbtba = NMSUtils.getNMSClassSilent("NBTTagByteArray"); - public Class nbtd = NMSUtils.getNMSClassSilent("NBTTagDouble"); - public Class nbtf = NMSUtils.getNMSClassSilent("NBTTagFloat"); - public Class nbti = NMSUtils.getNMSClassSilent("NBTTagInt"); - public Class nbtia = NMSUtils.getNMSClassSilent("NBTTagIntArray"); - public Class nbtl = NMSUtils.getNMSClassSilent("NBTTagList"); - public Class nbtlo = NMSUtils.getNMSClassSilent("NBTTagLong"); - public Class nbts = NMSUtils.getNMSClassSilent("NBTTagShort"); - public Class nbtst = NMSUtils.getNMSClassSilent("NBTTagString"); - - public Constructor nbtbc = NMSUtils.getConstructorSilent(nbtby, byte.class); - public Constructor nbtbac = NMSUtils.getConstructorSilent(nbtba, byte[].class); - public Constructor nbtdc = NMSUtils.getConstructorSilent(nbtd, double.class); - public Constructor nbtfc = NMSUtils.getConstructorSilent(nbtf, float.class); - public Constructor nbtic = NMSUtils.getConstructorSilent(nbti, int.class); - public Constructor nbtiac = NMSUtils.getConstructorSilent(nbtia, int[].class); - public Constructor nbtlc = NMSUtils.getConstructorSilent(nbtl); - public Constructor nbtloc = NMSUtils.getConstructorSilent(nbtlo, long.class); - public Constructor nbtsc = NMSUtils.getConstructorSilent(nbts, short.class); - public Constructor nbtstc = NMSUtils.getConstructorSilent(nbtst, String.class); - - public Field nbtbd = NMSUtils.getField(nbtby, "data"); - public Field nbtbad = NMSUtils.getField(nbtba, "data"); - public Field nbtdd = NMSUtils.getField(nbtd, "data"); - public Field nbtfd = NMSUtils.getField(nbtf, "data"); - public Field nbtid = NMSUtils.getField(nbti, "data"); - public Field nbtiad = NMSUtils.getField(nbtia, "data"); - public Field nbtld = NMSUtils.getField(nbtl, "list"); - public Field nbtlt = NMSUtils.getField(nbtl, "type"); - public Field nbttcd = NMSUtils.getField(nbttc, "map"); - public Field nbtlod = NMSUtils.getField(nbtlo, "data"); - public Field nbtsd = NMSUtils.getField(nbts, "data"); - public Field nbtstd = NMSUtils.getField(nbtst, "data"); - - @Override - public Object getNewNBTTagByte(byte value) throws Exception{ - return nbtbc.newInstance(value); - } - - @Override - public Object getNewNBTTagByteArray(byte[] value) throws Exception{ - return nbtbac.newInstance(value); - } - - @Override - public Object getData(Object nbt) throws Exception{ - int i = ((byte)gti.invoke(nbt)); - switch(i){ - case NBTConstants.TYPE_BYTE: - return nbtbd.get(nbt); - case NBTConstants.TYPE_SHORT: - return nbtsd.get(nbt); - case NBTConstants.TYPE_INT: - return nbtid.get(nbt); - case NBTConstants.TYPE_LONG: - return nbtlod.get(nbt); - case NBTConstants.TYPE_FLOAT: - return nbtfd.get(nbt); - case NBTConstants.TYPE_DOUBLE: - return nbtdd.get(nbt); - case NBTConstants.TYPE_BYTE_ARRAY: - return nbtbad.get(nbt); - case NBTConstants.TYPE_STRING: - return nbtstd.get(nbt); - case NBTConstants.TYPE_LIST: - return convertListTagToValueList(nbt); - case NBTConstants.TYPE_COMPOUND: - return convertCompoundTagToValueMap(nbt); - case NBTConstants.TYPE_INT_ARRAY: - return nbtiad.get(nbt); - } - return null; - } - - @Override - @SuppressWarnings("unchecked") - public Object createData(Object value) throws Exception{ - if(value.getClass().equals(byte.class)){ return nbtbc.newInstance(value); } - if(value.getClass().equals(byte[].class)){ return nbtbac.newInstance(value); } - if(value.getClass().isAssignableFrom(Map.class)){ return convertValueMapToCompoundTag((Map)value); } - if(value.getClass().equals(double.class)){ return nbtdc.newInstance(value); } - if(value.getClass().equals(float.class)){ return nbtfc.newInstance(value); } - if(value.getClass().equals(int.class)){ return nbtic.newInstance(value); } - if(value.getClass().equals(int[].class)){ return nbtiac.newInstance(value); } - if(value.getClass().isAssignableFrom(List.class)){ return convertValueListToListTag((List)value); } - if(value.getClass().equals(long.class)){ return nbtloc.newInstance(value); } - if(value.getClass().equals(short.class)){ return nbtsc.newInstance(value); } - if(value.getClass().equals(String.class)){ return nbtstc.newInstance(value); } - return null; - } - - @Override - @SuppressWarnings({ "unchecked" }) - public Map convertCompoundTagToValueMap(Object nbt) throws Exception{ - Map ret = new HashMap<>(); - Map map = (Map)getMap(nbt); - for(Entry e : map.entrySet()){ - Object nbti = e.getValue(); - Object data = getData(nbti); - if(data != null){ - ret.put(e.getKey(), data); - } - } - return ret; - } - - @Override - @SuppressWarnings("unchecked") - public List convertListTagToValueList(Object nbttl) throws Exception{ - List ret = new ArrayList<>(); - List list = (List)nbtld.get(nbttl); - for(Object e : list){ - Object data = getData(e); - if(data != null){ - ret.add(data); - } - } - return ret; - } - - @Override - public Object convertValueMapToCompoundTag(Map map) throws Exception{ - Map value = new HashMap<>(); - for(Entry e : map.entrySet()){ - value.put(e.getKey(), createData(e.getValue())); - } - Object ret = getNewNBTTagCompound(); - nbttcm.set(ret, value); - return ret; - } - - @Override - public Object convertValueListToListTag(List list) throws Exception{ - List value = new ArrayList<>(); - for(Object e : list){ - value.add(createData(e)); - } - Object ret = getNewNBTTagList(); - nbttcm.set(ret, value); - if(value.size() > 0){ - nbtlt.set(ret, gti.invoke(value.get(0))); - } - return ret; - } - - @Override - @SuppressWarnings("unchecked") - @Deprecated - public void convertListTagToJSON(Object nbttl, JSONArray ja, JSONArray helper) throws Exception{ - List list = (List)nbtld.get(nbttl); - for(Object e : list){ - Object data = getDataJSON(e, ja, helper); - if(data != null){ - ja.put(data); - } - } - } - - @Override - @SuppressWarnings("unchecked") - public void convertListTagToJSON(Object nbttl, JSONArray ja) throws Exception{ - List list = (List)nbtld.get(nbttl); - for(Object e : list){ - Object data = getDataJSON(e); - if(data != null){ - ja.put(data); - } - } - } - - @Override - @SuppressWarnings("unchecked") - @Deprecated - public void convertCompoundTagToJSON(Object nbt, JSONObject jo, JSONObject helper) throws Exception{ - Map map = (Map)getMap(nbt); - for(Entry e : map.entrySet()){ - Object nbti = e.getValue(); - Object data = getDataJSON(e.getKey(), nbti, jo, helper); - if(data != null){ - jo.put(e.getKey(), data); - } - } - } - - @Override - @SuppressWarnings("unchecked") - public void convertCompoundTagToJSON(Object nbt, JSONObject jo) throws Exception{ - Map map = (Map)getMap(nbt); - for(Entry e : map.entrySet()){ - Object nbti = e.getValue(); - Object data = getDataJSON(nbti); - if(data != null){ - jo.put(e.getKey(), data); - } - } - } - - @Override - @SuppressWarnings("unchecked") - @Deprecated - public Object convertJSONToCompoundTag(JSONObject jo, JSONObject helper) throws Exception{ - Map value = new HashMap<>(); - Iterator it = jo.keys(); - while(it.hasNext()){ - String e = it.next(); - value.put(e, createDataJSON(e, jo, helper)); - } - Object ret = getNewNBTTagCompound(); - nbttcm.set(ret, value); - return ret; - } - - @Override - @SuppressWarnings("unchecked") - public Object convertJSONToCompoundTag(JSONObject jo) throws Exception{ - Map value = new HashMap<>(); - Iterator it = jo.keys(); - while(it.hasNext()){ - String e = it.next(); - value.put(e, createDataJSON(e, jo)); - } - Object ret = getNewNBTTagCompound(); - nbttcm.set(ret, value); - return ret; - } - - @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Deprecated - public Object convertJSONToListTag(JSONArray ja, JSONArray helper) throws Exception{ - List value = new ArrayList(); - for(int i = 0; i < ja.length(); i++){ - value.add(createDataJSON(i, ja, helper)); - } - Object ret = getNewNBTTagList(); - nbtld.set(ret, value); - if(value.size() > 0){ - nbtlt.set(ret, gti.invoke(value.get(0))); - } - return ret; - } - - @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Object convertJSONToListTag(JSONArray ja) throws Exception{ - List value = new ArrayList(); - for(int i = 0; i < ja.length(); i++){ - value.add(createDataJSON(i, ja)); - } - Object ret = getNewNBTTagList(); - nbtld.set(ret, value); - if(value.size() > 0){ - nbtlt.set(ret, gti.invoke(value.get(0))); - } - return ret; - } - - @Override - @Deprecated - public Object getDataJSON(String key, Object nbt, JSONObject jo, JSONObject helper) throws Exception{ - int i = ((byte)gti.invoke(nbt)); - Object ret = null; - Object help = i; - switch(i){ - case NBTConstants.TYPE_BYTE: - ret = nbtbd.get(nbt); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsd.get(nbt); - break; - case NBTConstants.TYPE_INT: - ret = nbtid.get(nbt); - break; - case NBTConstants.TYPE_LONG: - ret = nbtlod.get(nbt); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfd.get(nbt); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdd.get(nbt); - break; - case NBTConstants.TYPE_BYTE_ARRAY: - ret = nbtbad.get(nbt); - break; - case NBTConstants.TYPE_STRING: - ret = nbtstd.get(nbt); - break; - case NBTConstants.TYPE_LIST:{ - JSONArray ja1 = new JSONArray(); - JSONArray helper1 = new JSONArray(); - convertListTagToJSON(nbt, ja1, helper1); - ret = ja1; - help = helper1; - break; - } - case NBTConstants.TYPE_COMPOUND: - JSONObject jo1 = new JSONObject(); - JSONObject helper1 = new JSONObject(); - convertCompoundTagToJSON(nbt, jo1, helper1); - ret = jo1; - help = helper1; - break; - case NBTConstants.TYPE_INT_ARRAY: - ret = nbtiad.get(nbt); - break; - } - if(ret != null){ - helper.put(key, help); - } - return ret; - } - - @Override - public JSONArray getDataJSON(Object nbt) throws Exception{ - int i = ((byte)gti.invoke(nbt)); - Object ret = null; - switch(i){ - case NBTConstants.TYPE_BYTE: - ret = nbtbd.get(nbt); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsd.get(nbt); - break; - case NBTConstants.TYPE_INT: - ret = nbtid.get(nbt); - break; - case NBTConstants.TYPE_LONG: - ret = nbtlod.get(nbt); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfd.get(nbt); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdd.get(nbt); - break; - case NBTConstants.TYPE_BYTE_ARRAY: - ret = nbtbad.get(nbt); - break; - case NBTConstants.TYPE_STRING: - ret = nbtstd.get(nbt); - break; - case NBTConstants.TYPE_LIST:{ - JSONArray ja1 = new JSONArray(); - convertListTagToJSON(nbt, ja1); - ret = ja1; - break; - } - case NBTConstants.TYPE_COMPOUND: - JSONObject jo1 = new JSONObject(); - convertCompoundTagToJSON(nbt, jo1); - ret = jo1; - break; - case NBTConstants.TYPE_INT_ARRAY: - ret = nbtiad.get(nbt); - break; - } - if(ret == null) { - return null; - } - return new JSONArray(new Object[]{ i, ret }); - } - - @Override - @Deprecated - public Object getDataJSON(Object nbt, JSONArray ja, JSONArray helper) throws Exception{ - int i = ((byte)gti.invoke(nbt)); - Object ret = null; - Object help = i; - switch(i){ - case NBTConstants.TYPE_BYTE: - ret = nbtbd.get(nbt); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsd.get(nbt); - break; - case NBTConstants.TYPE_INT: - ret = nbtid.get(nbt); - break; - case NBTConstants.TYPE_LONG: - ret = nbtlod.get(nbt); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfd.get(nbt); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdd.get(nbt); - break; - case NBTConstants.TYPE_BYTE_ARRAY: - ret = nbtbad.get(nbt); - break; - case NBTConstants.TYPE_STRING: - ret = nbtstd.get(nbt); - break; - case NBTConstants.TYPE_LIST:{ - JSONArray ja1 = new JSONArray(); - JSONArray helper1 = new JSONArray(); - convertListTagToJSON(nbt, ja1, helper1); - ret = ja1; - break; - } - case NBTConstants.TYPE_COMPOUND: - JSONObject jo1 = new JSONObject(); - JSONObject helper1 = new JSONObject(); - convertCompoundTagToJSON(nbt, jo1, helper1); - ret = jo1; - help = helper1; - break; - case NBTConstants.TYPE_INT_ARRAY: - ret = nbtiad.get(nbt); - break; - } - if(ret != null){ - helper.put(help); - } - return ret; - } - - @Override - @Deprecated - public Object createDataJSON(String key, JSONObject jo, JSONObject helper) throws Exception{ - Object help = helper.get(key); - Object ret = null; - if(help instanceof JSONObject){ - JSONObject jo1 = jo.getJSONObject(key); - JSONObject helper1 = (JSONObject)help; - ret = convertJSONToCompoundTag(jo1, helper1); - }else if(help instanceof JSONArray){ - JSONArray ja1 = jo.getJSONArray(key); - JSONArray helper1 = (JSONArray)help; - ret = convertJSONToListTag(ja1, helper1); - }else{ - int i = (int)help; - switch(i){ - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance(getByte(jo.get(key))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance(getShort(jo.get(key))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance(getInt(jo.get(key))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtloc.newInstance(getLong(jo.get(key))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance(getFloat(jo.get(key))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance(getDouble(jo.get(key))); - break; - case NBTConstants.TYPE_BYTE_ARRAY:{ - JSONArray ja = jo.getJSONArray(key); - byte[] b = new byte[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance(b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance((String)jo.get(key)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance(b); - } - } - return ret; - } - - @Override - public Object createDataJSON(String key, JSONObject jo) throws Exception{ - JSONArray j = jo.getJSONArray(key); - Object ret = null; - int i = j.getInt(0); - switch(i){ - case NBTConstants.TYPE_COMPOUND: - ret = convertJSONToCompoundTag(j.getJSONObject(1)); - break; - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance(getByte(j.get(1))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance(getShort(j.get(1))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance(getInt(j.get(1))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtloc.newInstance(getLong(j.get(1))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance(getFloat(j.get(1))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance(getDouble(j.get(1))); - break; - case NBTConstants.TYPE_BYTE_ARRAY:{ - JSONArray ja = j.getJSONArray(1); - byte[] b = new byte[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance(b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance((String)j.get(1)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance(b); - case NBTConstants.TYPE_LIST: - ret = convertJSONToListTag(j.getJSONArray(1)); - break; - } - return ret; - } - - @Override - public byte getByte(Object o){ - if(o.getClass().equals(Integer.class)){ return (byte)(int)o; } - if(o.getClass().equals(Short.class)){ return (byte)(short)o; } - if(o.getClass().equals(Integer.class)){ return (byte)(int)o; } - return (byte)o; - } - - @Override - public short getShort(Object o){ - if(o.getClass().equals(Integer.class)){ return (short)(int)o; } - if(o.getClass().equals(Byte.class)){ return (byte)o; } - if(o.getClass().equals(Integer.class)){ return (short)(int)o; } - return (short)o; - } - - @Override - public int getInt(Object o){ - if(o.getClass().equals(Short.class)){ return (short)o; } - if(o.getClass().equals(Byte.class)){ return (byte)o; } - return (int)o; - } - - @Override - public double getDouble(Object o){ - if(o.getClass().equals(Float.class)){ return (float)o; } - if(o.getClass().equals(Long.class)){ return (long)o; } - if(o.getClass().equals(Integer.class)){ return (int)o; } - return (double)o; - } - - @Override - public float getFloat(Object o){ - if(o.getClass().equals(Double.class)){ return (float)(double)o; } - if(o.getClass().equals(Long.class)){ return (long)o; } - if(o.getClass().equals(Integer.class)){ return (int)o; } - return (float)o; - } - - @Override - public long getLong(Object o){ - if(o.getClass().equals(Float.class)){ return (long)(float)o; } - if(o.getClass().equals(Double.class)){ return (long)(double)o; } - if(o.getClass().equals(Integer.class)){ return (int)o; } - return (long)o; - } - - @Override - @Deprecated - public Object createDataJSON(int key, JSONArray jo, JSONArray helper) throws Exception{ - Object help = helper.get(key); - Object ret = null; - if(help instanceof JSONObject){ - JSONObject jo1 = jo.getJSONObject(key); - JSONObject helper1 = (JSONObject)help; - return convertJSONToCompoundTag(jo1, helper1); - }else if(help instanceof JSONArray){ - JSONArray ja1 = jo.getJSONArray(key); - JSONArray helper1 = (JSONArray)help; - return convertJSONToListTag(ja1, helper1); - }else{ - int i = (int)help; - switch(i){ - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance(getByte(jo.get(key))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance(getShort(jo.get(key))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance(getInt(jo.get(key))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtloc.newInstance(getLong(jo.get(key))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance(getFloat(jo.get(key))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance(getDouble(jo.get(key))); - break; - case NBTConstants.TYPE_BYTE_ARRAY:{ - JSONArray ja = jo.getJSONArray(key); - byte[] b = new byte[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance(b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance((String)jo.get(key)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance(b); - } - } - return ret; - } - - @Override - public Object createDataJSON(int key, JSONArray jo) throws Exception{ - JSONArray j = jo.getJSONArray(key); - Object ret = null; - int i = j.getInt(0); - switch(i){ - case NBTConstants.TYPE_COMPOUND: - ret = convertJSONToCompoundTag(j.getJSONObject(1)); - break; - case NBTConstants.TYPE_BYTE: - ret = nbtbc.newInstance(getByte(j.get(1))); - break; - case NBTConstants.TYPE_SHORT: - ret = nbtsc.newInstance(getShort(j.get(1))); - break; - case NBTConstants.TYPE_INT: - ret = nbtic.newInstance(getInt(j.get(1))); - break; - case NBTConstants.TYPE_LONG: - ret = nbtloc.newInstance(getLong(j.get(1))); - break; - case NBTConstants.TYPE_FLOAT: - ret = nbtfc.newInstance(getFloat(j.get(1))); - break; - case NBTConstants.TYPE_DOUBLE: - ret = nbtdc.newInstance(getDouble(j.get(1))); - break; - case NBTConstants.TYPE_BYTE_ARRAY:{ - JSONArray ja = j.getJSONArray(1); - byte[] b = new byte[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getByte(ja.get(a)); - } - return nbtbac.newInstance(b); - } - case NBTConstants.TYPE_STRING: - ret = nbtstc.newInstance((String)j.get(1)); - break; - case NBTConstants.TYPE_INT_ARRAY: - JSONArray ja = jo.getJSONArray(key); - int[] b = new int[ja.length()]; - for(int a = 0; a < ja.length(); a++){ - b[a] = getInt(ja.get(a)); - } - return nbtiac.newInstance(b); - case NBTConstants.TYPE_LIST: - ret = convertJSONToListTag(j.getJSONArray(1)); - break; - } - return ret; - } - - @Override - public boolean compareBaseTag(Object tag, Object tag1) throws Exception{ - int i = ((byte)gti.invoke(tag)); - int i1 = ((byte)gti.invoke(tag1)); - if(i != i1) { - return false; - } - switch(i){ - case NBTConstants.TYPE_BYTE: - Byte b = (byte)nbtbd.get(tag); - Byte b1 = (byte)nbtbd.get(tag1); - return b.equals(b1); - case NBTConstants.TYPE_SHORT: - Short s = (short)nbtsd.get(tag); - Short s1 = (short)nbtsd.get(tag1); - return s.equals(s1); - case NBTConstants.TYPE_INT: - Integer a = (int)nbtid.get(tag); - Integer a1 = (int)nbtid.get(tag1); - return a.equals(a1); - case NBTConstants.TYPE_LONG: - Long l = (long)nbtlod.get(tag); - Long l1 = (long)nbtlod.get(tag1); - return l.equals(l1); - case NBTConstants.TYPE_FLOAT: - Float f = (float)nbtfd.get(tag); - Float f1 = (float)nbtfd.get(tag1); - return f.equals(f1); - case NBTConstants.TYPE_DOUBLE: - Double d = (double)nbtdd.get(tag); - Double d1 = (double)nbtdd.get(tag1); - return d.equals(d1); - case NBTConstants.TYPE_BYTE_ARRAY: - byte[] ba = (byte[])nbtbad.get(tag); - byte[] ba1 = (byte[])nbtbad.get(tag1); - return Arrays.equals(ba, ba1); - case NBTConstants.TYPE_STRING: - String st = (String)nbtstd.get(tag); - String st1 = (String)nbtstd.get(tag1); - return st.equals(st1); - case NBTConstants.TYPE_LIST:{ - return compareListTag(tag, tag1); - } - case NBTConstants.TYPE_COMPOUND: - return compareCompoundTag(tag, tag1); - case NBTConstants.TYPE_INT_ARRAY: - int[] ia = (int[])nbtiad.get(tag); - int[] ia1 = (int[])nbtiad.get(tag); - return Arrays.equals(ia, ia1); - } - return false; - } - - @Override - @SuppressWarnings("unchecked") - public boolean compareCompoundTag(Object tag, Object tag1) throws Exception{ - Map map = (Map)getMap(tag); - Map map1 = (Map)getMap(tag1); - if(map.size() != map1.size()) { - return false; - } - if(!map.keySet().containsAll(map1.keySet())) { - return false; - } - for(Entry e : map.entrySet()){ - Object o = e.getValue(); - Object o1 = map1.get(e.getKey()); - if(!compareBaseTag(o, o1)) { - return false; - } - } - return true; - } - - @Override - @SuppressWarnings({ "unchecked", "rawtypes" }) - public boolean compareListTag(Object tag, Object tag1) throws Exception{ - List list = (List)nbtld.get(tag); - List list1 = (List)nbtld.get(tag1); - if(list.size() != list1.size()) { - return false; - } - if(list.isEmpty() && list1.isEmpty()) { - return true; - } - List copy = new ArrayList(list); - List copy1 = new ArrayList(list1); - Iterator it = copy.iterator(); - while(it.hasNext()){ - Object o = it.next(); - Iterator it1 = copy1.iterator(); - boolean cont = false; - while(it1.hasNext()){ - Object o1 = it1.next(); - if(compareBaseTag(o, o1)){ - it1.remove(); - it.remove(); - cont = true; - break; - } - } - if(!cont) { - return false; - } - } - return copy.isEmpty() && copy1.isEmpty(); - } - - @Override - public boolean compare(ItemStack is1, ItemStack is2){ - if(is1.getType().equals(is2.getType())){ - if(is1.getDurability() == is2.getDurability()){ - try { - Object nis1 = getNMSCopy(is1); - Object nis2 = getNMSCopy(is2); - Object tis1 = getTag(nis1); - Object tis2 = getTag(nis2); - if (tis1 != null && tis2 == null) { - return isEmpty(tis1); - } - if (tis1 == null && tis2 != null) { - return isEmpty(tis2); - } - return tis1 == null && tis2 == null || compareCompoundTag(tis1, tis2); - }catch(Exception e){ - e.printStackTrace(); - } - } - } - return false; - } - - @Override - public boolean canMerge(ItemStack add, ItemStack to){ - return compare(add, to); - } - - @Override - public boolean isModified(ItemStack is){ - ItemStack is1 = is.clone(); - is1.setAmount(1); - ItemStack is2 = new ItemStack(is.getType(), 1, is.getDurability()); - return !is1.equals(is2); - } - - @Override - public void sortByMaterial(List items){ - items.sort(new MaterialComparator()); - } - - public class MaterialComparator implements Comparator{ - @Override - public int compare(ItemStack arg0, ItemStack arg1){ - return arg0.getType().name().compareTo(arg1.getType().name()); - } - } - - @Override - public void sortByName(List items){ - items.sort(new NameComparator()); - } - - public class NameComparator implements Comparator{ - @Override - public int compare(ItemStack arg0, ItemStack arg1){ - int i = 0; - try{ - i = ChatColor.stripColor(getName(arg0)).compareTo(ChatColor.stripColor(getName(arg1))); - }catch(Exception e){ - e.printStackTrace(); - } - return i; - } - } - - @Override - public void sortByAmount(List items){ - items.sort(new AmountComparator()); - } - - public class AmountComparator implements Comparator{ - @Override - public int compare(ItemStack arg0, ItemStack arg1){ - int i = arg1.getAmount() - arg0.getAmount(); - if(i == 0){ - try{ - i = ChatColor.stripColor(getName(arg0)).compareTo(ChatColor.stripColor(getName(arg1))); - }catch(Exception e){ - e.printStackTrace(); - } - } - return i; - } - } - - @Override - public ItemStack convertJSONToItemStack(JSONObject jo) throws Exception{ - Material material = Material.valueOf(jo.getString("material")); - int amount = jo.getInt("amount"); - int durability = jo.getInt("durability"); - ItemStack is = new ItemStack(material, amount, (short)durability); - JSONObject jo1 = jo.getJSONObject("tag"); - if(jo1.length() == 0) { - return is; - } - Object tag = convertJSONToCompoundTag(jo1); - Object nmis = getNMSCopy(is); - setTag(nmis, tag); - is = asBukkitCopy(nmis); - return is; - } - - @Override - public JSONObject convertItemStackToJSON(ItemStack is) throws Exception{ - JSONObject jo = new JSONObject(); - jo.put("material", is.getType().name()); - jo.put("amount", is.getAmount()); - jo.put("durability", is.getDurability()); - JSONObject jo2 = new JSONObject(); - Object nmis = getNMSCopy(is); - Object tag = getTag(nmis); - if(tag != null){ - convertCompoundTagToJSON(tag, jo2); - } - jo.put("tag", jo2); - return jo; - } -} diff --git a/src/main/java/me/skymc/taboolib/nms/nbt/NBTConstants.java b/src/main/java/me/skymc/taboolib/nms/nbt/NBTConstants.java deleted file mode 100644 index 03c7a57..0000000 --- a/src/main/java/me/skymc/taboolib/nms/nbt/NBTConstants.java +++ /dev/null @@ -1,25 +0,0 @@ -package me.skymc.taboolib.nms.nbt; - -import java.nio.charset.Charset; - -@Deprecated -public final class NBTConstants { - - public static final Charset CHARSET = Charset.forName("UTF-8"); - public static final int TYPE_END = 0; - public static final int TYPE_BYTE = 1; - public static final int TYPE_SHORT = 2; - public static final int TYPE_INT = 3; - public static final int TYPE_LONG = 4; - public static final int TYPE_FLOAT = 5; - public static final int TYPE_DOUBLE = 6; - public static final int TYPE_BYTE_ARRAY = 7; - public static final int TYPE_STRING = 8; - public static final int TYPE_LIST = 9; - public static final int TYPE_COMPOUND = 10; - public static final int TYPE_INT_ARRAY = 11; - - private NBTConstants() { - throw new AssertionError("Not instantiable"); - } -} diff --git a/src/main/java/me/skymc/taboolib/object/WeightCategory.java b/src/main/java/me/skymc/taboolib/object/WeightCategory.java deleted file mode 100644 index 98d8ca3..0000000 --- a/src/main/java/me/skymc/taboolib/object/WeightCategory.java +++ /dev/null @@ -1,34 +0,0 @@ -package me.skymc.taboolib.object; - -@Deprecated -public class WeightCategory { - - private String category; - private Integer weight; - - public WeightCategory() { - super(); - } - - public WeightCategory(String category, Integer weight) { - super(); - this.setCategory(category); - this.setWeight(weight); - } - - public Integer getWeight() { - return weight; - } - - public void setWeight(Integer weight) { - this.weight = weight; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } -} \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/other/DateUtils.java b/src/main/java/me/skymc/taboolib/other/DateUtils.java deleted file mode 100644 index e4f5cc4..0000000 --- a/src/main/java/me/skymc/taboolib/other/DateUtils.java +++ /dev/null @@ -1,80 +0,0 @@ -package me.skymc.taboolib.other; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; - -public class DateUtils { - - /** - * 最后一次更新:2018年1月16日21:07:27 - * - * @author sky - */ - - public static SimpleDateFormat CH_ALL = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒"); - public static SimpleDateFormat EN_ALL = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - - public static SimpleDateFormat YEAR = new SimpleDateFormat("yyyy"); - - public static SimpleDateFormat MONTH = new SimpleDateFormat("MM"); - - public static SimpleDateFormat DAY_OF_MONTH = new SimpleDateFormat("dd"); - public static SimpleDateFormat DAY_OF_YEAR = new SimpleDateFormat("DD"); - - public static SimpleDateFormat HOUR_OF_DAY = new SimpleDateFormat("HH"); - public static SimpleDateFormat HOUR = new SimpleDateFormat("hh"); - - public static SimpleDateFormat MINUTE = new SimpleDateFormat("mm"); - public static SimpleDateFormat SECONDS = new SimpleDateFormat("ss"); - - public static SimpleDateFormat MILLISECOND = new SimpleDateFormat("SSS"); - - public static SimpleDateFormat WEEK = new SimpleDateFormat("E"); - - private static SimpleDateFormat Hour = new SimpleDateFormat("HH:mm"); - - public static Calendar getCalendar() { - return Calendar.getInstance(); - } - - public static Date getTime() { - return Calendar.getInstance().getTime(); - } - - public static Integer getTime(SimpleDateFormat date) { - return Integer.valueOf(date.format(getTime())); - } - - public static boolean timeInDifference(String m1, String m2) { - try { - Date now = Hour.parse(Hour.format(System.currentTimeMillis())); - Date min = Hour.parse(m1); - Date max = Hour.parse(m2); - return (now.after(min) && now.before(max)) || now.equals(min) || now.equals(max); - } catch (Exception e) { - return false; - } - } - - public static long formatDate(String time) { - long date = 0; - try { - for (String value : time.toLowerCase().split(";")) { - Integer num = Integer.valueOf(value.substring(0, value.length() - 1)); - if (value.endsWith("d")) { - date += num * 1000L * 60 * 60 * 24; - } else if (value.endsWith("h")) { - date += num * 1000L * 60 * 60; - } else if (value.endsWith("m")) { - date += num * 1000L * 60; - } else if (value.endsWith("s")) { - date += num * 1000L; - } - } - } catch (Exception e) { - // TODO: handle exception - } - return date; - } -} diff --git a/src/main/java/me/skymc/taboolib/other/MathUtils.java b/src/main/java/me/skymc/taboolib/other/MathUtils.java deleted file mode 100644 index fbc751a..0000000 --- a/src/main/java/me/skymc/taboolib/other/MathUtils.java +++ /dev/null @@ -1,55 +0,0 @@ -package me.skymc.taboolib.other; - -import me.skymc.taboolib.particle.EffLib; -import org.bukkit.Color; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -public class MathUtils { - - public static double tronc(double paramDouble, int paramInt) { - double d = Math.pow(10.0D, paramInt); - return Math.floor(paramDouble * d) / d; - } - - public static void drawVec(Vector paramVector, Location paramLocation, Color paramColor) { - for (double d = 0.0D; d < 1.0D; d += 0.1D) { - EffLib.REDSTONE.display(new EffLib.OrdinaryColor(paramColor), paramLocation.clone().add(paramVector.clone().multiply(d)), 100.0D); - } - } - - public static void sendCoords(Player paramPlayer, Vector paramVector, String paramString) { - paramPlayer.sendMessage(paramString + tronc(paramVector.getX(), 2) + " " + tronc(paramVector.getY(), 2) + " " + tronc(paramVector.getZ(), 2)); - } - - public static void sendCoords(Player paramPlayer, Location paramLocation, String paramString) { - paramPlayer.sendMessage(paramString + tronc(paramLocation.getX(), 2) + " " + tronc(paramLocation.getY(), 2) + " " + tronc(paramLocation.getZ(), 2)); - } - - public static Vector rotAxisX(Vector paramVector, double paramDouble) { - double d1 = paramVector.getY() * Math.cos(paramDouble) - paramVector.getZ() * Math.sin(paramDouble); - double d2 = paramVector.getY() * Math.sin(paramDouble) + paramVector.getZ() * Math.cos(paramDouble); - return paramVector.setY(d1).setZ(d2); - } - - public static Vector rotAxisY(Vector paramVector, double paramDouble) { - double d1 = paramVector.getX() * Math.cos(paramDouble) + paramVector.getZ() * Math.sin(paramDouble); - double d2 = paramVector.getX() * -Math.sin(paramDouble) + paramVector.getZ() * Math.cos(paramDouble); - return paramVector.setX(d1).setZ(d2); - } - - public static Vector rotAxisZ(Vector paramVector, double paramDouble) { - double d1 = paramVector.getX() * Math.cos(paramDouble) - paramVector.getY() * Math.sin(paramDouble); - double d2 = paramVector.getX() * Math.sin(paramDouble) + paramVector.getY() * Math.cos(paramDouble); - return paramVector.setX(d1).setY(d2); - } - - public static Vector rotateFunc(Vector paramVector, Location paramLocation) { - double d1 = paramLocation.getYaw() / 180.0F * 3.141592653589793D; - double d2 = paramLocation.getPitch() / 180.0F * 3.141592653589793D; - paramVector = rotAxisX(paramVector, d2); - paramVector = rotAxisY(paramVector, -d1); - return paramVector; - } -} diff --git a/src/main/java/me/skymc/taboolib/other/NumberUtils.java b/src/main/java/me/skymc/taboolib/other/NumberUtils.java deleted file mode 100644 index f811baa..0000000 --- a/src/main/java/me/skymc/taboolib/other/NumberUtils.java +++ /dev/null @@ -1,83 +0,0 @@ -package me.skymc.taboolib.other; - -import java.text.DecimalFormat; -import java.util.Random; - -/** - * @author sky - */ -public class NumberUtils { - - private static Random random = new Random(); - private static DecimalFormat doubleFormat = new DecimalFormat("#.##"); - - public static Random getRandom() { - return random; - } - - public static Double format(Double num) { - return Double.valueOf(doubleFormat.format(num)); - } - - public static int getRandomInteger(Number num1, Number num2) { - int min = Math.min(num1.intValue(), num2.intValue()); - int max = Math.max(num1.intValue(), num2.intValue()); - return (int) (random.nextDouble() * (max - min) + min); - } - - public static double getRandomDouble(Number num1, Number num2) { - double min = Math.min(num1.doubleValue(), num2.doubleValue()); - double max = Math.max(num1.doubleValue(), num2.doubleValue()); - return random.nextDouble() * (max - min) + min; - } - - public static int getInteger(String s) { - try { - return Integer.valueOf(s); - } catch (Exception e) { - return 0; - } - } - - public static double getDouble(String s) { - try { - return Double.valueOf(s); - } catch (Exception e) { - return 0; - } - } - - public static Boolean getBoolean(String s) { - try { - return Boolean.valueOf(s); - } catch (Exception e) { - return false; - } - } - - public static Boolean getBooleanAbbreviation(String str) { - if (str == null || str.isEmpty()) { - return false; - } - if (str.length() < 4) { - char var = str.charAt(0); - if (var == 'y' || var == 'Y' || var == 't' || var == 'T' || var == '1') { - return true; - } - if (var == 'n' || var == 'N' || var == 'f' || var == 'F' || var == '0') { - return false; - } - } - return getBoolean(str); - } - - @Deprecated - public static Random getRand() { - return random; - } - - @Deprecated - public static boolean getChance(int a) { - return getRandom().nextInt(100) <= a; - } -} diff --git a/src/main/java/me/skymc/taboolib/other/WeightUtils.java b/src/main/java/me/skymc/taboolib/other/WeightUtils.java deleted file mode 100644 index 0ac7f43..0000000 --- a/src/main/java/me/skymc/taboolib/other/WeightUtils.java +++ /dev/null @@ -1,33 +0,0 @@ -package me.skymc.taboolib.other; - -import me.skymc.taboolib.object.WeightCategory; - -import java.util.List; - -@Deprecated -public class WeightUtils { - - public static String getStringByWeight(List categorys) { - - int weightSum = 0; - for (WeightCategory wc : categorys) { - weightSum += wc.getWeight(); - } - - if (weightSum <= 0) { - return null; - } - - Integer n = NumberUtils.getRandom().nextInt(weightSum); - Integer m = 0; - - for (WeightCategory wc : categorys) { - if (m <= n && n < m + wc.getWeight()) { - return wc.getCategory(); - } - m += wc.getWeight(); - } - return null; - } - -} \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/packet/PacketUtils.java b/src/main/java/me/skymc/taboolib/packet/PacketUtils.java deleted file mode 100644 index 1a85164..0000000 --- a/src/main/java/me/skymc/taboolib/packet/PacketUtils.java +++ /dev/null @@ -1,93 +0,0 @@ -package me.skymc.taboolib.packet; - -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.ProtocolManager; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.google.common.base.Preconditions; -import org.bukkit.Bukkit; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -/** - * @author sky - */ -public class PacketUtils { - - public static void checkProtocolLib() { - Preconditions.checkArgument(isProtocolLibEnabled(), "Plugin \"ProtocolLib\" cannot found!"); - } - - public static boolean isProtocolLibEnabled() { - return Bukkit.getPluginManager().getPlugin("ProtocolLib") != null && Bukkit.getPluginManager().getPlugin("ProtocolLib").isEnabled(); - } - - public static ProtocolManager getManager() { - return ProtocolLibrary.getProtocolManager(); - } - - public static void sendPacketEntityStatus(Entity entity, EntityStatus status, Player... players) { - PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); - packet.getIntegers().write(0, entity.getEntityId()); - WrappedDataWatcher watcher = new WrappedDataWatcher(); - WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(Byte.class); - switch (status) { - case FIRE: - watcher.setObject(0, serializer, (byte) 0x01); - break; - case CROUCHED: - watcher.setObject(0, serializer, (byte) 0x02); - break; - case UNUSED1: - watcher.setObject(0, serializer, (byte) 0x04); - break; - case SPRINTING: - watcher.setObject(0, serializer, (byte) 0x08); - break; - case UNUSED2: - watcher.setObject(0, serializer, (byte) 0x10); - break; - case INVISIBLE: - watcher.setObject(0, serializer, (byte) 0x20); - break; - case GLOWING: - watcher.setObject(0, serializer, (byte) 0x40); - break; - case ELYTRA: - watcher.setObject(0, serializer, (byte) 0x80); - break; - default: - watcher.setObject(0, serializer, (byte) 0x00); - break; - } - packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); - try { - for (Player player : players) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void sendPacketEntityCustomName(Entity entity, String value, Player... players) { - PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); - packet.getIntegers().write(0, entity.getEntityId()); - WrappedDataWatcher watcher = new WrappedDataWatcher(); - WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(String.class); - watcher.setObject(2, serializer, value == null ? "" : value); - packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); - try { - for (Player player : players) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public enum EntityStatus { - FIRE, CROUCHED, UNUSED1, UNUSED2, SPRINTING, INVISIBLE, GLOWING, ELYTRA - } -} diff --git a/src/main/java/me/skymc/taboolib/particle/ParticlePack.java b/src/main/java/me/skymc/taboolib/particle/ParticlePack.java deleted file mode 100644 index 039c06c..0000000 --- a/src/main/java/me/skymc/taboolib/particle/ParticlePack.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.skymc.taboolib.particle; - -import me.skymc.taboolib.TabooLib; -import org.bukkit.Location; - -public class ParticlePack { - - public EffLib particle = EffLib.VILLAGER_HAPPY; - - public float x = 0F; - public float y = 0F; - public float z = 0F; - public int a = 0; - - /** - * VILLAGER_HAPPY-10-1-1-1 - * 粒子-数量-X-Y-Z - * - * @param value - */ - public ParticlePack(String value) { - try { - particle = EffLib.valueOf(value.split("-")[0]); - a = Integer.valueOf(value.split("-")[1]); - x = Float.valueOf(value.split("-")[2]); - y = Float.valueOf(value.split("-")[3]); - z = Float.valueOf(value.split("-")[4]); - } - catch (Exception e) { - // TODO: handle exception - } - } - - /** - * 播放粒子 - * - * @param loc - */ - public void play(Location loc) { - if (TabooLib.getVerint() > 10800) { - particle.display(x, y, z, 0f, a, loc, 50); - } - } -} diff --git a/src/main/java/me/skymc/taboolib/particle/ParticleUtils.java b/src/main/java/me/skymc/taboolib/particle/ParticleUtils.java deleted file mode 100644 index 6420b4e..0000000 --- a/src/main/java/me/skymc/taboolib/particle/ParticleUtils.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.skymc.taboolib.particle; - -import org.bukkit.Color; -import org.bukkit.Effect; -import org.bukkit.Location; - -public class ParticleUtils { - - public static void sendColor(Effect particle, Location l, int data, Color color) { - l.getWorld().spigot().playEffect(l, particle, data, 0, (float)getColor(color.getRed()), (float)getColor(color.getGreen()), (float)getColor(color.getBlue()), 1, 0, 35); - } - - public static void sendColor(Effect particle, Location l, int data, java.awt.Color color) { - l.getWorld().spigot().playEffect(l, particle, data, 0, (float)getColor(color.getRed()), (float)getColor(color.getGreen()), (float)getColor(color.getBlue()), 1, 0, 35); - } - - public static void sendEffect(Effect particle, Location l, float offsetX, float offsetY, float offsetZ, float speed, int amount) { - l.getWorld().spigot().playEffect(l, particle, 0, 0, offsetX, offsetY, offsetZ, speed, amount, 35); - } - - private static double getColor(double value) { - if (value <= 0) { - value = -1; - } - return value / 255; - } -} \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/permission/PermissionUtils.java b/src/main/java/me/skymc/taboolib/permission/PermissionUtils.java deleted file mode 100644 index 3d5ba16..0000000 --- a/src/main/java/me/skymc/taboolib/permission/PermissionUtils.java +++ /dev/null @@ -1,34 +0,0 @@ -package me.skymc.taboolib.permission; - -import me.skymc.taboolib.Main; -import net.milkbowl.vault.permission.Permission; -import org.bukkit.entity.Player; -import org.bukkit.plugin.RegisteredServiceProvider; - -import java.util.Arrays; - -public class PermissionUtils { - - private static Permission perms; - - public static void loadRegisteredServiceProvider() { - RegisteredServiceProvider rsp = Main.getInst().getServer().getServicesManager().getRegistration(Permission.class); - perms = rsp.getProvider(); - } - - public static Permission getPermission() { - return perms; - } - - public static void addPermission(Player player, String perm) { - perms.playerAdd(player, perm); - } - - public static void removePermission(Player player, String perm) { - perms.playerRemove(player, perm); - } - - public static boolean hasPermission(Player player, String perm) { - return perms.playerHas(player, perm) || Arrays.stream(perms.getPlayerGroups(player)).anyMatch(group -> perms.groupHas(player.getWorld(), group, perm)); - } -} diff --git a/src/main/java/me/skymc/taboolib/player/PlayerUtils.java b/src/main/java/me/skymc/taboolib/player/PlayerUtils.java deleted file mode 100644 index cb2ed91..0000000 --- a/src/main/java/me/skymc/taboolib/player/PlayerUtils.java +++ /dev/null @@ -1,139 +0,0 @@ -package me.skymc.taboolib.player; - -import com.google.common.collect.ImmutableList; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.block.Block; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; - -/** - * @author sky - */ -public class PlayerUtils { - - private static boolean setup; - private static boolean useReflection; - private static Method oldGetOnlinePlayersMethod; - - public static Collection getOnlinePlayers() { - try { - if (!setup) { - oldGetOnlinePlayersMethod = Bukkit.class.getDeclaredMethod("getOnlinePlayers"); - if (oldGetOnlinePlayersMethod.getReturnType() == Player[].class) { - useReflection = true; - } - setup = true; - } - if (!useReflection) { - return Bukkit.getOnlinePlayers(); - } else { - Player[] playersArray = (Player[]) oldGetOnlinePlayersMethod.invoke(null); - return ImmutableList.copyOf(playersArray); - } - } catch (Exception e) { - return Collections.emptyList(); - } - } - - /** - * 获取目标方块 - * - * @param player 玩家 - * @param max 最大视野 - * @return - */ - public static Block getTargetBlock(Player player, int max) { - HashSet bytes = new HashSet<>(); - bytes.add((byte) 0); - return player.getTargetBlock(bytes, max); - } - - /** - * 重写数据 - * - * @param player 玩家 - * @param scoreboard 是否清理计分板 - */ - public static void resetData(Player player, boolean scoreboard) { - if (player.isDead()) { - player.spigot().respawn(); - } - player.closeInventory(); - player.setGameMode(GameMode.SURVIVAL); - player.getInventory().setArmorContents(new ItemStack[4]); - player.getInventory().setContents(new ItemStack[0]); - player.setAllowFlight(false); - player.setFlying(false); - player.setExp(0.0F); - player.setLevel(0); - player.setSneaking(false); - player.setSprinting(false); - player.setFoodLevel(20); - player.setSaturation(10.0F); - player.setExhaustion(0.0F); - player.setMaxHealth(20.0D); - player.setHealth(20.0D); - player.setFireTicks(0); - player.setItemOnCursor(null); - player.getActivePotionEffects().clear(); - player.getEnderChest().clear(); - player.updateInventory(); - if (scoreboard) { - player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - } - } - - /** - * 获取玩家的鱼钩 - * - * @param player 玩家 - * @return net.minecraft.server.{version}.EntityFishingHook - */ - public static Object getPlayerHookedFish(HumanEntity player) { - try { - Object entityHuman = player.getClass().getMethod("getHandle").invoke(player); - return entityHuman.getClass().getField("hookedFish").get(entityHuman); - } catch (Exception ignored) { - } - return null; - } - - /** - * 获取鱼钩的钓鱼时间 - * - * @param fishHook 鱼钩 - * @return int - */ - public static int getFishingTicks(Object fishHook) { - try { - Field fishingTicks = fishHook.getClass().getDeclaredField("h"); - fishingTicks.setAccessible(true); - return (int) fishingTicks.get(fishHook); - } catch (Exception ignored) { - } - return -1; - } - - /** - * 设置鱼钩的钓鱼时间 - * - * @param fishHook 鱼钩 - * @param ticks 时间 - */ - public static void setFishingTicks(Object fishHook, int ticks) { - try { - Field fishingTicks = fishHook.getClass().getDeclaredField("h"); - fishingTicks.setAccessible(true); - fishingTicks.set(fishHook, ticks); - } catch (Exception ignored) { - } - } -} diff --git a/src/main/java/me/skymc/taboolib/player/TargetUtils.java b/src/main/java/me/skymc/taboolib/player/TargetUtils.java deleted file mode 100644 index fa993a9..0000000 --- a/src/main/java/me/skymc/taboolib/player/TargetUtils.java +++ /dev/null @@ -1,25 +0,0 @@ -package me.skymc.taboolib.player; - -import org.bukkit.block.Block; -import org.bukkit.entity.LivingEntity; -import org.bukkit.util.BlockIterator; - -import java.util.LinkedList; - - -@Deprecated -public class TargetUtils { - - public static LinkedList getTarget(LivingEntity p, int max) { - BlockIterator itor = new BlockIterator(p); - LinkedList block = new LinkedList<>(); - while (itor.hasNext()) { - max++; - block.add(itor.next()); - if (max >= 100) { - break; - } - } - return block; - } -} diff --git a/src/main/java/me/skymc/taboolib/regen/WorldGuardUtils.java b/src/main/java/me/skymc/taboolib/regen/WorldGuardUtils.java deleted file mode 100644 index d0ad421..0000000 --- a/src/main/java/me/skymc/taboolib/regen/WorldGuardUtils.java +++ /dev/null @@ -1,26 +0,0 @@ -package me.skymc.taboolib.regen; - -import com.sk89q.worldguard.bukkit.WorldGuardPlugin; -import com.sk89q.worldguard.protection.regions.ProtectedRegion; -import org.bukkit.Location; - -import java.util.Map; - -@Deprecated -public class WorldGuardUtils { - - public static String getRegen(Location loc) { - int x = (int) loc.getX(); - int y = (int) loc.getY() + 1; - int z = (int) loc.getZ(); - - Map regens = WorldGuardPlugin.inst().getRegionManager(loc.getWorld()).getRegions(); - for (String s : regens.keySet()) { - ProtectedRegion regen = regens.get(s); - if (regen.contains(x, y, z)) { - return regen.getId(); - } - } - return null; - } -} diff --git a/src/main/java/me/skymc/taboolib/sign/SignUtils.java b/src/main/java/me/skymc/taboolib/sign/SignUtils.java deleted file mode 100644 index dbdc8a9..0000000 --- a/src/main/java/me/skymc/taboolib/sign/SignUtils.java +++ /dev/null @@ -1,152 +0,0 @@ -package me.skymc.taboolib.sign; - -import com.google.common.annotations.Beta; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.listener.TListener; -import me.skymc.taboolib.location.LocationUtils; -import me.skymc.taboolib.message.MsgUtils; -import me.skymc.taboolib.methods.MethodsUtils; -import me.skymc.taboolib.nms.NMSUtils; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.block.SignChangeEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.metadata.FixedMetadataValue; - -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; - -@Deprecated -@Beta -@TListener(condition = "check") -public class SignUtils implements Listener { - - public static HashMap signs = new HashMap<>(); - - public static boolean check() { - return TabooLib.getVerint() > 10700; - } - - public static void openSign(Player p, Block b) { - - if (!(b.getType().equals(Material.WALL_SIGN) || b.getType().equals(Material.SIGN_POST))) { - return; - } - - b.setMetadata("TabooLib-Sign-Editing", new FixedMetadataValue(Main.getInst(), true)); - - try { - Object world = b.getWorld().getClass().getMethod("getHandle").invoke(b.getWorld()); - Object blockPos = NMSUtils.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(b.getX(), b.getY(), b.getZ()); - Object sign = world.getClass().getMethod("getTileEntity", NMSUtils.getNMSClass("BlockPosition")).invoke(world, blockPos); - - Object player = p.getClass().getMethod("getHandle").invoke(p); - - player.getClass().getMethod("openSign", NMSUtils.getNMSClass("TileEntitySign")).invoke(player, sign); - } catch (Exception e) { - MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.1)"); - e.printStackTrace(); - } - } - - public static void openSign(Player p, String[] lines, String signid) { - if (!MethodsUtils.checkUser(new String(new byte[]{'m', 'e', '.', 's', 'k', 'y', 'm', 'c'}), new Exception().getStackTrace()[1].getClassName())) { - throw new Error("未经允许的方法调用"); - } - - Block b = LocationUtils.findBlockByLocation(p.getLocation()); - if (b == null) { - MsgUtils.send(p, "&4所在位置无法进行该操作 &8(NOT FOUND AIR BY SIGN)"); - return; - } - - b.setData((byte) 0); - b.setType(Material.WALL_SIGN); - - b.setMetadata("TabooLib-Sign", new FixedMetadataValue(Main.getInst(), true)); - b.setMetadata("TabooLib-Sign-UUID", new FixedMetadataValue(Main.getInst(), signid)); - - try { - Object world = b.getWorld().getClass().getMethod("getHandle").invoke(b.getWorld()); - Object blockPos = NMSUtils.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(b.getX(), b.getY(), b.getZ()); - Object sign = world.getClass().getMethod("getTileEntity", NMSUtils.getNMSClass("BlockPosition")).invoke(world, blockPos); - - Object[] _lines = (Object[]) sign.getClass().getField("lines").get(sign); - - for (int i = 0; i < lines.length; i++) { - Object object = NMSUtils.getNMSClass("ChatComponentText").getConstructor(String.class).newInstance(lines[i]); - _lines[i] = object; - } - - Object player = p.getClass().getMethod("getHandle").invoke(p); - - Bukkit.getScheduler().runTaskLater(Main.getInst(), () -> { - if (p.isOnline()) { - try { - player.getClass().getMethod("openSign", NMSUtils.getNMSClass("TileEntitySign")).invoke(player, sign); - signs.put(p.getName(), b); - } catch (IllegalAccessException | SecurityException | NoSuchMethodException | InvocationTargetException | IllegalArgumentException e) { - MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.2)"); - e.printStackTrace(); - } - } - }, 3); - } catch (Exception e) { - MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.1)"); - e.printStackTrace(); - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void signChange(SignChangeEvent e) { - Block block = e.getBlock(); - if (block.hasMetadata("TabooLib-Sign")) { - signs.remove(e.getPlayer().getName()); - - String signid = String.valueOf(block.getMetadata("TabooLib-Sign-UUID").get(0).value()); - Bukkit.getPluginManager().callEvent(new TabooSignChangeEvent(e.getPlayer(), block, e.getLines(), signid)); - - block.removeMetadata("TabooLib-Sign", Main.getInst()); - block.removeMetadata("TabooLib-Sign-UUID", Main.getInst()); - block.setType(Material.AIR); - block.setData((byte) 0); - } - } - - @EventHandler - public void quit(PlayerQuitEvent e) { - if (signs.containsKey(e.getPlayer().getName())) { - Block block = signs.get(e.getPlayer().getName()); - if (block.hasMetadata("TabooLib-Sign")) { - block.removeMetadata("TabooLib-Sign", Main.getInst()); - block.removeMetadata("TabooLib-Sign-UUID", Main.getInst()); - block.setType(Material.AIR); - block.setData((byte) 0); - } - } - } - - @EventHandler - public void block(BlockPhysicsEvent e) { - Block block = e.getBlock(); - if (block.hasMetadata("TabooLib-Sign")) { - e.setCancelled(true); - } - } - - @EventHandler - public void blocku(BlockBreakEvent e) { - Block block = e.getBlock(); - if (block.hasMetadata("TabooLib-Sign") && !e.getPlayer().isOp()) { - e.setCancelled(true); - } - } -} diff --git a/src/main/java/me/skymc/taboolib/sign/TabooSignChangeEvent.java b/src/main/java/me/skymc/taboolib/sign/TabooSignChangeEvent.java deleted file mode 100644 index f198ba7..0000000 --- a/src/main/java/me/skymc/taboolib/sign/TabooSignChangeEvent.java +++ /dev/null @@ -1,48 +0,0 @@ -package me.skymc.taboolib.sign; - -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -@Deprecated -public class TabooSignChangeEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - private Player player; - private Block block; - private String[] lines; - private String uuid; - - public TabooSignChangeEvent(Player player, Block block, String[] lines, String uuid) { - this.player = player; - this.block = block; - this.lines = lines; - this.uuid = uuid; - } - - public Player getPlayer() { - return this.player; - } - - public Block getBlock() { - return this.block; - } - - public String[] getLines() { - return this.lines; - } - - public String getUUID() { - return this.uuid; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/main/java/me/skymc/taboolib/skript/SkriptHandler.java b/src/main/java/me/skymc/taboolib/skript/SkriptHandler.java deleted file mode 100644 index 909e87d..0000000 --- a/src/main/java/me/skymc/taboolib/skript/SkriptHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package me.skymc.taboolib.skript; - -import ch.njol.skript.Skript; -import ch.njol.skript.lang.ExpressionType; -import me.skymc.taboolib.skript.expression.ExpressionItemCache; -import me.skymc.taboolib.skript.expression.ExpressionTabooCodeItem; -import org.bukkit.Bukkit; -import org.bukkit.inventory.ItemStack; - -/** - * @author sky - * @since 2018-02-28 15:40:55 - */ -public class SkriptHandler { - - public static void register() { - if (Bukkit.getPluginManager().getPlugin("Skript") != null) { - try { - Skript.registerExpression(ExpressionItemCache.class, ItemStack.class, ExpressionType.SIMPLE, "taboolib itemcache %string%"); - Skript.registerExpression(ExpressionTabooCodeItem.class, ItemStack.class, ExpressionType.SIMPLE, "taboocode itemcache %string%"); - } catch (Exception ignored) { - } - } - } -} diff --git a/src/main/java/me/skymc/taboolib/skript/expression/ExpressionItemCache.java b/src/main/java/me/skymc/taboolib/skript/expression/ExpressionItemCache.java deleted file mode 100644 index 761f8c2..0000000 --- a/src/main/java/me/skymc/taboolib/skript/expression/ExpressionItemCache.java +++ /dev/null @@ -1,46 +0,0 @@ -package me.skymc.taboolib.skript.expression; - -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.lang.util.SimpleExpression; -import ch.njol.util.Kleenean; -import me.skymc.taboolib.inventory.ItemUtils; -import org.bukkit.event.Event; -import org.bukkit.inventory.ItemStack; - -/** - * @author sky - * @since 2018-02-28 15:45:49 - */ -public class ExpressionItemCache extends SimpleExpression { - - private Expression name; - - @Override - public Class getReturnType() { - return ItemStack.class; - } - - @Override - public boolean isSingle() { - return true; - } - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] args, int arg1, Kleenean arg2, ParseResult arg3) { - name = (Expression) args[0]; - return true; - } - - @Override - public String toString(Event e, boolean arg1) { - return this.getClass().getName(); - } - - @Override - protected ItemStack[] get(Event e) { - ItemStack item = ItemUtils.getCacheItem(name.getSingle(e)); - return new ItemStack[] { item == null ? null : item.clone() }; - } -} diff --git a/src/main/java/me/skymc/taboolib/skript/expression/ExpressionTabooCodeItem.java b/src/main/java/me/skymc/taboolib/skript/expression/ExpressionTabooCodeItem.java deleted file mode 100644 index 566305a..0000000 --- a/src/main/java/me/skymc/taboolib/skript/expression/ExpressionTabooCodeItem.java +++ /dev/null @@ -1,51 +0,0 @@ -package me.skymc.taboolib.skript.expression; - -import ch.njol.skript.lang.Expression; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.skript.lang.util.SimpleExpression; -import ch.njol.util.Kleenean; -import me.skymc.taboocode.TabooCodeItem; -import org.bukkit.event.Event; -import org.bukkit.inventory.ItemStack; - -/** - * @author sky - * @since 2018-02-28 15:45:49 - */ -public class ExpressionTabooCodeItem extends SimpleExpression { - - private Expression name; - - @Override - public Class getReturnType() { - return ItemStack.class; - } - - @Override - public boolean isSingle() { - return true; - } - - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] args, int arg1, Kleenean arg2, ParseResult arg3) { - name = (Expression) args[0]; - return true; - } - - @Override - public String toString(Event e, boolean arg1) { - return this.getClass().getName(); - } - - @Override - protected ItemStack[] get(Event e) { - try { - ItemStack item = TabooCodeItem.getItem(name.getSingle(e), false); - return new ItemStack[] { item == null ? null : item.clone() }; - } - catch (Exception err) { - return null; - } - } -} diff --git a/src/main/java/me/skymc/taboolib/skull/SkullUtils.java b/src/main/java/me/skymc/taboolib/skull/SkullUtils.java deleted file mode 100644 index c30b668..0000000 --- a/src/main/java/me/skymc/taboolib/skull/SkullUtils.java +++ /dev/null @@ -1,21 +0,0 @@ -package me.skymc.taboolib.skull; - -import com.google.common.annotations.Beta; -import me.skymc.taboolib.inventory.builder.ItemBuilder; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.inventory.ItemStack; - -@Beta -@Deprecated -public class SkullUtils { - - public static ItemStack getItem(OfflinePlayer p) { - return new ItemBuilder(p).build(); - } - - public static ItemStack getOnlineItem(OfflinePlayer p) { - return p.isOnline() ? new ItemBuilder(p).build() : new ItemStack(Material.SKULL_ITEM); - } - -} diff --git a/src/main/java/me/skymc/taboolib/string/obfuscated/CT.java b/src/main/java/me/skymc/taboolib/string/obfuscated/CT.java deleted file mode 100644 index 37c3537..0000000 --- a/src/main/java/me/skymc/taboolib/string/obfuscated/CT.java +++ /dev/null @@ -1,52 +0,0 @@ -package me.skymc.taboolib.string.obfuscated; - -import javax.xml.bind.DatatypeConverter; - -@Deprecated -public class CT { - - public static String decode(CodeType type, String string) { - switch (type) { - case BASE64: { - return new String(DatatypeConverter.parseBase64Binary(string)); - } - case BINARY: { - StringBuilder text = new StringBuilder(); - for (String segment : string.split(" ")) { - text.append(Character.toString((char) Integer.parseInt(segment, 2))); - } - return text.toString(); - } - default: - } - return ""; - } - - public static String encode(CodeType type, String string) { - switch (type) { - case BASE64: { - return DatatypeConverter.printBase64Binary(string.getBytes()); - } - case BINARY: { - StringBuilder binary = new StringBuilder(); - for (byte b : string.getBytes()) { - int value = b; - for (int i = 0; i < 8; i++) { - binary.append((value & 128) == 0 ? 0 : 1); - value <<= 1; - } - binary.append(" "); - } - return binary.toString(); - } - default: - } - return ""; - } - - public enum CodeType { - BASE64, - BINARY - } - -} diff --git a/src/main/java/me/skymc/taboolib/string/obfuscated/FZ.java b/src/main/java/me/skymc/taboolib/string/obfuscated/FZ.java deleted file mode 100644 index 1d02cbe..0000000 --- a/src/main/java/me/skymc/taboolib/string/obfuscated/FZ.java +++ /dev/null @@ -1,59 +0,0 @@ -package me.skymc.taboolib.string.obfuscated; - -@Deprecated -public class FZ { - - public static String toByte(final String string) { - final StringBuilder sb = new StringBuilder(); - final byte[] bs = string.getBytes(); - byte[] array; - for (int length = (array = bs).length, i = 0; i < length; ++i) { - final byte b = array[i]; - sb.append(String.valueOf(b)).append("#"); - } - return sb.toString(); - } - - public static byte[] getByte(final String string) { - final String[] value = string.split("#"); - final byte[] bs = new byte[value.length]; - for (int i = 0; i < value.length; ++i) { - bs[i] = Byte.valueOf(value[i]); - } - return bs; - } - - public static String unByte(final String string) { - final String[] value = string.split("#"); - final byte[] bs = new byte[value.length]; - for (int i = 0; i < value.length; ++i) { - bs[i] = Byte.valueOf(value[i]); - } - return new String(bs); - } - - public static String load(final String string, final int power) { - final StringBuilder sb = new StringBuilder(); - char[] charArray; - for (int length = (charArray = string.toCharArray()).length, j = 0; j < length; ++j) { - int i; - final char c = (char)(i = charArray[j]); - i *= power; - sb.append(String.valueOf(i)).append("#"); - } - return sb.toString(); - } - - public static String load2(final String string, final int power) { - final String[] value = string.split("#"); - final StringBuilder sb = new StringBuilder(); - String[] array; - for (int length = (array = value).length, j = 0; j < length; ++j) { - final String c = array[j]; - int i = Integer.valueOf(c); - i /= power; - sb.append((char)i); - } - return sb.toString(); - } -} diff --git a/src/main/java/me/skymc/taboolib/string/obfuscated/RS.java b/src/main/java/me/skymc/taboolib/string/obfuscated/RS.java deleted file mode 100644 index e407a3e..0000000 --- a/src/main/java/me/skymc/taboolib/string/obfuscated/RS.java +++ /dev/null @@ -1,48 +0,0 @@ -package me.skymc.taboolib.string.obfuscated; - -import me.skymc.taboolib.Main; - -@Deprecated -public class RS { - - private static final char[] charsDown = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); - private static final char[] charsUp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); - - public static char getRandomCharacter() { - return charsDown[Main.getRandom().nextInt(charsDown.length)]; - } - - public static char getRandomCharacter(Boolean isUp) { - if (isUp) { - return charsUp[Main.getRandom().nextInt(charsUp.length)]; - } - return charsDown[Main.getRandom().nextInt(charsDown.length)]; - } - - public static String getRandomString(int length) { - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < length; i++) { - builder.append(getRandomCharacter()); - } - return builder.toString(); - } - - public static String getRandomString(String prefix, String rule, Boolean isUp) { - StringBuilder builder = new StringBuilder(prefix + "-"); - String[] value = rule.split("-"); - - int size = 0; - for (String subrule : value) { - size++; - - for (int i = 0; i < Integer.valueOf(subrule); i++) { - builder.append(getRandomCharacter(isUp)); - } - if (!(size == value.length)) { - builder.append("-"); - } - } - - return builder.toString(); - } -} diff --git a/src/main/java/me/skymc/taboolib/team/TagAPI.java b/src/main/java/me/skymc/taboolib/team/TagAPI.java deleted file mode 100644 index 5afb4da..0000000 --- a/src/main/java/me/skymc/taboolib/team/TagAPI.java +++ /dev/null @@ -1,66 +0,0 @@ -package me.skymc.taboolib.team; - -import com.google.common.base.Preconditions; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.itagapi.TagDataHandler; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.util.Set; - -/** - * @Author sky - * @Since 2018-05-09 21:03 - */ -@Deprecated -public class TagAPI { - - /** - * 该工具于 2018年5月23日02:31:14 失效 - * 新工具类: {@link TagDataHandler} - */ - - TagAPI() { - } - - public static void inst() { - } - - public static String getPlayerDisplayName(Player player) { - return TagDataHandler.getHandler().getDisplay(player); - } - - public static void setPlayerDisplayName(Player player, String name) { - TagDataHandler.getHandler().setDisplay(player, name); - } - - public static void removePlayerDisplayName(Player player) { - TagDataHandler.getHandler().setDisplay(player, player.getName()); - } - - public static void refreshPlayer(Player player) { - Preconditions.checkState(Main.getInst().isEnabled(), "Not Enabled!"); - Preconditions.checkNotNull(player, "player"); - - player.getWorld().getPlayers().forEach(playerFor -> refreshPlayer(player, playerFor)); - } - - public static void refreshPlayer(final Player player, final Player forWhom) { - Preconditions.checkState(Main.getInst().isEnabled(), "Not Enabled!"); - Preconditions.checkNotNull(player, "player"); - Preconditions.checkNotNull(forWhom, "forWhom"); - - if (player != forWhom && player.getWorld() == forWhom.getWorld() && forWhom.canSee(player)) { - forWhom.hidePlayer(player); - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Main.getInst(), () -> forWhom.showPlayer(player), 2); - } - } - - public static void refreshPlayer(Player player, Set forWhom) { - Preconditions.checkState(Main.getInst().isEnabled(), "Not Enabled!"); - Preconditions.checkNotNull(player, "player"); - Preconditions.checkNotNull(forWhom, "forWhom"); - - forWhom.forEach(playerFor -> refreshPlayer(player, playerFor)); - } -} diff --git a/src/main/java/me/skymc/taboolib/team/TagManager.java b/src/main/java/me/skymc/taboolib/team/TagManager.java deleted file mode 100644 index 7c78340..0000000 --- a/src/main/java/me/skymc/taboolib/team/TagManager.java +++ /dev/null @@ -1,126 +0,0 @@ -package me.skymc.taboolib.team; - -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.itagapi.TagDataHandler; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.scoreboard.Scoreboard; -import org.bukkit.scoreboard.Team; - -import java.util.HashMap; -import java.util.UUID; - -/** - * @author sky - * @since 2018-03-17 21:43:49 - */ -@Deprecated -public class TagManager { - - /** - * 该工具于 2018年5月23日02:31:14 失效 - * 新工具类: {@link TagDataHandler} - */ - - private static TagManager inst; - - public static TagManager getInst() { - synchronized (TagManager.class) { - if (inst == null) { - inst = new TagManager(); - } - } - return inst; - } - - public HashMap getPlayerData() { - return new HashMap<>(0); - } - - public void setPrefix(Player player, String prefix) { - TagDataHandler.getHandler().setPrefix(player, prefix); - } - - public void setSuffix(Player player, String suffix) { - TagDataHandler.getHandler().setSuffix(player, suffix); - } - - public String getPrefix(Player player) { - return TagDataHandler.getHandler().getPrefix(player); - } - - public String getSuffix(Player player) { - return TagDataHandler.getHandler().getSuffix(player); - } - - public PlayerData getPlayerData(Player player) { - return new PlayerData(player); - } - - public void unloadData(Player targetPlayer) { - TagDataHandler.getHandler().resetVariable(targetPlayer); - } - - public void uploadData(Player targetPlayer) { - } - - public void downloadData(Player targetPlayer) { - } - - static class PlayerData { - - private UUID uuid; - private String name; - private String prefix; - private String suffix; - - public PlayerData(Player player) { - this.uuid = player.getUniqueId(); - this.name = player.getName(); - this.prefix = ""; - this.suffix = ""; - } - - public UUID getUuid() { - return uuid; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getPrefix() { - return prefix; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public String getSuffix() { - return suffix; - } - - public void setSuffix(String suffix) { - this.suffix = suffix; - } - - public boolean isEmpty() { - return Strings.isEmpty(suffix) && Strings.isEmpty(prefix); - } - - public void reset() { - prefix = ""; - suffix = ""; - } - } -} diff --git a/src/main/java/me/skymc/taboolib/thread/ThreadUtils.java b/src/main/java/me/skymc/taboolib/thread/ThreadUtils.java deleted file mode 100644 index 750e218..0000000 --- a/src/main/java/me/skymc/taboolib/thread/ThreadUtils.java +++ /dev/null @@ -1,86 +0,0 @@ -package me.skymc.taboolib.thread; - -import java.util.LinkedList; - -/** - * @author sky - */ -@Deprecated -public class ThreadUtils { - - private static final LinkedList queue = new LinkedList<>(); - private static PoolWorker[] threads; - - /** - * 构造方法 - * - * @param number 线程数量 - */ - public ThreadUtils(int number) { - threads = new PoolWorker[number]; - - for (int i = 0; i < number; i++) { - threads[i] = new PoolWorker(); - threads[i].setName("TabooLib WorkThread - " + i); - threads[i].start(); - } - } - - /** - * 停止工作 - */ - public void stop() { - for (PoolWorker p : threads) { - p.stop(); - } - } - - /** - * 添加任务 - * - * @param r - */ - public void execute(Runnable r) { - // 线程锁 - synchronized (queue) { - // 添加任务 - queue.addLast(r); - // 开始任务 - queue.notify(); - } - } - - private class PoolWorker extends Thread { - - @Override - public void run() { - Runnable runnable; - - while (true) { - - // 线程锁 - synchronized (queue) { - - // 如果任务为空 - while (queue.isEmpty()) { - // 等待任务 - try { - queue.wait(); - } catch (InterruptedException ignored) { - - } - } - // 获取任务 - runnable = queue.removeFirst(); - } - - // 运行任务 - try { - runnable.run(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } -} \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/timecycle/TimeCycle.java b/src/main/java/me/skymc/taboolib/timecycle/TimeCycle.java deleted file mode 100644 index c8609bb..0000000 --- a/src/main/java/me/skymc/taboolib/timecycle/TimeCycle.java +++ /dev/null @@ -1,35 +0,0 @@ -package me.skymc.taboolib.timecycle; - -import me.skymc.taboolib.other.DateUtils; -import org.bukkit.plugin.Plugin; - -public class TimeCycle { - - private String name; - private Plugin plugin; - - private long cycle; - - public TimeCycle(String name, long cycle, Plugin plugin) { - this.name = name; - this.cycle = cycle; - this.plugin = plugin; - - long millisHour = DateUtils.getTime(DateUtils.HOUR_OF_DAY) * 60L * 60L * 1000L; - long millisMinute = DateUtils.getTime(DateUtils.MINUTE) * 60L * 1000L; - - long time = System.currentTimeMillis() - millisHour - millisMinute; - } - - public Plugin getPlugin() { - return plugin; - } - - public String getName() { - return name; - } - - public long getCycle() { - return cycle; - } -} diff --git a/src/main/java/me/skymc/taboolib/timecycle/TimeCycleEvent.java b/src/main/java/me/skymc/taboolib/timecycle/TimeCycleEvent.java deleted file mode 100644 index 2797f25..0000000 --- a/src/main/java/me/skymc/taboolib/timecycle/TimeCycleEvent.java +++ /dev/null @@ -1,28 +0,0 @@ -package me.skymc.taboolib.timecycle; - -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -public class TimeCycleEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - private TimeCycle cycle; - - public TimeCycleEvent(TimeCycle cycle) { - super(true); - this.cycle = cycle; - } - - public TimeCycle getCycle() { - return this.cycle; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/main/java/me/skymc/taboolib/timecycle/TimeCycleInitializeEvent.java b/src/main/java/me/skymc/taboolib/timecycle/TimeCycleInitializeEvent.java deleted file mode 100644 index e8fa476..0000000 --- a/src/main/java/me/skymc/taboolib/timecycle/TimeCycleInitializeEvent.java +++ /dev/null @@ -1,46 +0,0 @@ -package me.skymc.taboolib.timecycle; - -import org.bukkit.Bukkit; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -public class TimeCycleInitializeEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - private TimeCycle cycle; - private Long time; - - public TimeCycleInitializeEvent(TimeCycle cycle, Long time) { - super(true); - this.cycle = cycle; - this.time = time; - } - - public TimeCycleInitializeEvent call() { - Bukkit.getPluginManager().callEvent(this); - return this; - } - - public Long getTimeline() { - return time; - } - - public void setTimeLine(Long time) { - this.time = time; - } - - public TimeCycle getCycle() { - return this.cycle; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - -} diff --git a/src/main/java/me/skymc/taboolib/timecycle/TimeCycleManager.java b/src/main/java/me/skymc/taboolib/timecycle/TimeCycleManager.java deleted file mode 100644 index 6357156..0000000 --- a/src/main/java/me/skymc/taboolib/timecycle/TimeCycleManager.java +++ /dev/null @@ -1,159 +0,0 @@ -package me.skymc.taboolib.timecycle; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.database.GlobalDataManager; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.Collection; -import java.util.HashMap; -import java.util.concurrent.ConcurrentHashMap; - -public class TimeCycleManager { - - /** - * 最后一次更新: 2018年1月16日21:07:49 - * - * @author sky - */ - - private static ConcurrentHashMap cycles = new ConcurrentHashMap<>(); - - /** - * 获取周期管理器 - * - * @param name - * @return - */ - public static TimeCycle getTimeCycle(String name) { - return cycles.get(name); - } - - /** - * 获取所有周期管理器 - * - * @return - */ - public static Collection getTimeCycles() { - return cycles.values(); - } - - /** - * 彻底删除周期数据 - * - * @param name - */ - public static void deleteCycleData(String name) { - HashMap map = GlobalDataManager.getVariables(); - map.keySet().stream().filter(_name -> _name.startsWith("timecycle")).forEach(_name -> GlobalDataManager.setVariable(name, null)); - } - - /** - * 注册周期管理器 - * - * @param cycle - */ - public static void register(TimeCycle cycle) { - if (!cycles.containsKey(cycle.getName())) { - cycles.put(cycle.getName(), cycle); - } else { - TLocale.Logger.error("TIMECYCLE.FAIL-CYCLE-EXISTS", cycle.getName()); - } - } - - /** - * 注销周期管理器 - * - * @param name - * @return - */ - public static TimeCycle cancel(String name) { - return cycles.remove(name); - } - - /** - * 注销插件所有周期管理器 - * - * @param plugin - */ - public static void cancel(Plugin plugin) { - cycles.values().stream().filter(x -> x.getPlugin().equals(plugin)).forEach(x -> cycles.remove(x.getName())); - } - - /** - * 设置上一次更新事件 - * - * @param name - * @param time - */ - public static boolean setTimeline(String name, Long time) { - if (cycles.containsKey(name)) { - GlobalDataManager.setVariable("timecycle:" + name, time.toString()); - return true; - } - return false; - } - - /** - * 获取下一次刷新时间 - * - * @param name - * @return - */ - public static long getAfterTimeline(String name) { - if (cycles.containsKey(name)) { - Long value = Long.valueOf(GlobalDataManager.getVariable("timecycle:" + name, "0")); - return value + cycles.get(name).getCycle(); - } - return 0L; - } - - /** - * 获取上一次刷新时间 - * - * @param name - * @return - */ - public static long getBeforeTimeline(String name) { - if (cycles.containsKey(name)) { - return Long.valueOf(GlobalDataManager.getVariable("timecycle:" + name, "0")); - } - return 0L; - } - - - public static void load() { - // 注册调度器 - new BukkitRunnable() { - - @Override - public void run() { - for (TimeCycle cycle : cycles.values()) { - // 调度器没有被执行过 - if (!GlobalDataManager.contains("timecycle:" + cycle.getName())) { - long time = new TimeCycleInitializeEvent(cycle, System.currentTimeMillis()).call().getTimeline(); - // 初始化 - GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(time)); - // 触发器 - Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle)); - } - // 如果超出刷新时间 - else if (System.currentTimeMillis() >= getAfterTimeline(cycle.getName())) { - long time = System.currentTimeMillis(); - // 如果时间差大于 30 秒 - if (time - getAfterTimeline(cycle.getName()) > 30000) { - // 初始化 - time = new TimeCycleInitializeEvent(cycle, time).call().getTimeline(); - } - // 重置 - GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(time)); - // 触发器 - Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle)); - } - } - } - }.runTaskTimerAsynchronously(Main.getInst(), 0, 20); - } -} diff --git a/src/main/java/me/skymc/taboolib/translateuuid/TranslateUUID.java b/src/main/java/me/skymc/taboolib/translateuuid/TranslateUUID.java deleted file mode 100644 index 25a8732..0000000 --- a/src/main/java/me/skymc/taboolib/translateuuid/TranslateUUID.java +++ /dev/null @@ -1,205 +0,0 @@ -package me.skymc.taboolib.translateuuid; - -import com.ilummc.tlib.logger.TLogger; -import com.ilummc.tlib.util.Strings; -import com.zaxxer.hikari.HikariDataSource; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.fileutils.ConfigUtils; -import me.skymc.taboolib.json.JSONObject; -import me.skymc.taboolib.mysql.builder.*; -import me.skymc.taboolib.mysql.hikari.HikariHandler; -import me.skymc.taboolib.nms.NMSUtils; -import org.bukkit.configuration.file.FileConfiguration; - -import java.io.*; -import java.lang.reflect.Method; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Properties; -import java.util.UUID; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @Author sky - * @Since 2018-06-21 22:16 - */ -public class TranslateUUID { - - private static FileConfiguration settings; - private static HikariDataSource dataSource; - - private static SQLHost sqlHost; - private static SQLTable sqlTable; - - private static final String INSERT_PLAYER_DATA = "insert into {0} values(null, ?, ?)"; - private static final String SELECT_WITH_UUID = "select * from {0} where uuid = ?"; - private static final String SELECT_WITH_USERNAME = "select * from {0} where username = ?"; - private static final String UPDATE_PLAYER_USERNAME = "update {0} set username = ? where uuid = ?"; - - private static boolean enabled = false; - - public static void init() { - settings = ConfigUtils.saveDefaultConfig(Main.getInst(), "translateuuid.yml"); - if (!settings.getBoolean("Enable")) { - enabled = false; - return; - } - sqlHost = new SQLHost(settings.getConfigurationSection("Database"), Main.getInst()); - sqlTable = new SQLTable(settings.getString("Database.table"), SQLColumn.PRIMARY_KEY_ID, new SQLColumn(SQLColumnType.TEXT, "uuid"), new SQLColumn(SQLColumnType.TEXT, "username")); - try { - dataSource = HikariHandler.createDataSource(sqlHost, null); - createTable(); - } catch (Exception e) { - TLogger.getGlobalLogger().error("Database connected fail: " + e.toString()); - } - enabled = true; - } - - public static void cancel() { - HikariHandler.closeDataSource(sqlHost); - } - - public static String translateUUID(String username) { - try (Connection connection = dataSource.getConnection()) { - return translateInternal(connection, username, "uuid", SELECT_WITH_USERNAME); - } catch (SQLException e) { - TLogger.getGlobalLogger().error("Database error: " + e.toString()); - return null; - } - } - - public static String translateUsername(UUID uuid) { - try (Connection connection = dataSource.getConnection()) { - return translateInternal(connection, uuid.toString(), "username", SELECT_WITH_UUID); - } catch (SQLException e) { - TLogger.getGlobalLogger().error("Database error: " + e.toString()); - return null; - } - } - - public static void updateUsername(UUID uuid, String username) { - PreparedStatement preparedStatement = null; - try (Connection connection = dataSource.getConnection()) { - String usernameExists = translateInternal(connection, uuid.toString(), "username", SELECT_WITH_UUID); - if (usernameExists == null) { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder(INSERT_PLAYER_DATA, sqlTable.getTableName())); - preparedStatement.setString(1, uuid.toString()); - preparedStatement.setString(2, username); - } else { - preparedStatement = connection.prepareStatement(Strings.replaceWithOrder(UPDATE_PLAYER_USERNAME, sqlTable.getTableName())); - preparedStatement.setString(1, username); - preparedStatement.setString(2, uuid.toString()); - } - preparedStatement.executeUpdate(); - } catch (SQLException e) { - TLogger.getGlobalLogger().error("Database error: " + e.toString()); - } finally { - SQLExecutor.freeStatement(preparedStatement, null); - } - } - - public static void importLocal() { - File worldFolder = new File(getDefaultWorldName()); - if (!worldFolder.exists()) { - TLogger.getGlobalLogger().error("Invalid \"world\" folder"); - return; - } - - File playerDataFolder = new File(worldFolder, "playerdata"); - if (!playerDataFolder.exists() || !playerDataFolder.isDirectory()) { - TLogger.getGlobalLogger().error("Invalid \"playerdata\" folder"); - return; - } - - ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(32); - - AtomicInteger i = new AtomicInteger(); - AtomicInteger fail = new AtomicInteger(); - int size = playerDataFolder.listFiles().length; - - TLogger.getGlobalLogger().info("Start importing the local data..."); - for (File file : playerDataFolder.listFiles()) { - if (fail.get() > 10) { - TLogger.getGlobalLogger().info("The number of failures exceeds the threshold! import stopped.."); - break; - } - threadPool.submit(() -> { - try { - String username = getUsernameInDatFile(file); - updateUsername(UUID.fromString(file.getName().split("\\.")[0]), username); - TLogger.getGlobalLogger().info("importing... " + username + "(" + i.getAndIncrement() + "/" + size + ")"); - } catch (Exception ignored) { - fail.getAndIncrement(); - } - }); - } - - threadPool.shutdown(); - } - - public static JSONObject getPlayerDataInDatFile(File datFile) { - Class clazz = NMSUtils.getNMSClassSilent("NBTCompressedStreamTools"); - try (FileInputStream fileInputStream = new FileInputStream(datFile)) { - Method a = clazz.getMethod("a", InputStream.class); - Object nbtTagCompound = a.invoke(null, fileInputStream); - return new JSONObject(nbtTagCompound.getClass().getMethod("toString").invoke(nbtTagCompound)); - } catch (Exception ignored) { - } - return new JSONObject(); - } - - // ********************************* - // - // Private Methods - // - // ********************************* - - private static void createTable() { - sqlTable.executeUpdate(sqlTable.createQuery()).dataSource(dataSource).run(); - } - - private static String getDefaultWorldName() { - Properties properties = new Properties(); - try { - properties.load(new FileReader(new File("server.properties"))); - } catch (IOException ignored) { - } - return properties.getProperty("level-name", "world"); - } - - private static String getUsernameInDatFile(File datFile) { - Class clazz = NMSUtils.getNMSClassSilent("NBTCompressedStreamTools"); - try (FileInputStream fileInputStream = new FileInputStream(datFile)) { - Method a = clazz.getMethod("a", InputStream.class); - Object nbtTagCompound = a.invoke(null, fileInputStream); - Method getCompound = nbtTagCompound.getClass().getMethod("getCompound", String.class); - Object bukkit = getCompound.invoke(nbtTagCompound, "bukkit"); - Method getString = bukkit.getClass().getMethod("getString", String.class); - return String.valueOf(getString.invoke(bukkit, "lastKnownName")); - } catch (Exception ignored) { - } - return "null"; - } - - private static String translateInternal(Connection connection, String input, String output, String command) { - return sqlTable.executeQuery(Strings.replaceWithOrder(command, sqlTable.getTableName())) - .connection(connection) - .statement(statement -> statement.setString(1, input)) - .resultNext(result -> result.getString(output)) - .run(null, ""); - } - - // ********************************* - // - // Getter and Setter - // - // ********************************* - - public static boolean isEnabled() { - return enabled; - } -} diff --git a/src/main/java/me/skymc/taboolib/translateuuid/TranslateUUIDCommand.java b/src/main/java/me/skymc/taboolib/translateuuid/TranslateUUIDCommand.java deleted file mode 100644 index 86e3c31..0000000 --- a/src/main/java/me/skymc/taboolib/translateuuid/TranslateUUIDCommand.java +++ /dev/null @@ -1,81 +0,0 @@ -package me.skymc.taboolib.translateuuid; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.commands.internal.BaseMainCommand; -import me.skymc.taboolib.commands.internal.BaseSubCommand; -import me.skymc.taboolib.commands.internal.TCommand; -import me.skymc.taboolib.commands.internal.type.CommandArgument; -import me.skymc.taboolib.commands.internal.type.CommandRegister; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -/** - * @Author sky - * @Since 2018-06-22 17:09 - */ -@TCommand( - name = "translateuuid", - aliases = "tuuid", - permission = "taboolib.admin" -) -public class TranslateUUIDCommand extends BaseMainCommand { - - @Override - public String getCommandTitle() { - return TLocale.asString("COMMANDS.TRANSLATE-UUID.COMMAND-TITLE"); - } - - @CommandRegister - BaseSubCommand importLocal = new BaseSubCommand() { - @Override - public String getLabel() { - return "importLocal"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TRANSLATE-UUID.IMPORTLOCAL.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - if (!TranslateUUID.isEnabled()) { - TLocale.sendTo(sender, "COMMANDS.TRANSLATE-UUID.IMPORTLOCAL.DISABLED"); - return; - } - - TLocale.sendTo(sender, "COMMANDS.TRANSLATE-UUID.IMPORTLOCAL.SUCCESS"); - TranslateUUID.importLocal(); - } - }; - - @CommandRegister - BaseSubCommand reload = new BaseSubCommand() { - @Override - public String getLabel() { - return "reload"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TRANSLATE-UUID.RELOAD.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - TLocale.sendTo(sender, "COMMANDS.TRANSLATE-UUID.RELOAD.SUCCESS"); - TranslateUUID.cancel(); - TranslateUUID.init(); - } - }; -} diff --git a/src/main/java/me/skymc/tlm/TLM.java b/src/main/java/me/skymc/tlm/TLM.java deleted file mode 100644 index 1578e34..0000000 --- a/src/main/java/me/skymc/tlm/TLM.java +++ /dev/null @@ -1,102 +0,0 @@ -package me.skymc.tlm; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.fileutils.ConfigUtils; -import me.skymc.taboolib.string.language2.Language2; -import me.skymc.tlm.module.TabooLibraryModule; -import me.skymc.tlm.module.sub.ModuleCommandChanger; -import me.skymc.tlm.module.sub.ModuleInventorySave; -import me.skymc.tlm.module.sub.ModuleKits; -import me.skymc.tlm.module.sub.ModuleTimeCycle; -import org.bukkit.configuration.file.FileConfiguration; - -/** - * @author sky - * @since 2018年2月17日 下午10:28:05 - */ -public class TLM { - - private static TLM inst = null; - - private FileConfiguration config; - - private Language2 language; - - /** - * 构造方法 - */ - private TLM() { - // 重载配置文件 - reloadConfig(); - - // 载入模块 - if (isEnableModule("TimeCycle")) { - TabooLibraryModule.getInst().register(new ModuleTimeCycle()); - } - if (isEnableModule("Kits")) { - TabooLibraryModule.getInst().register(new ModuleKits()); - } - if (isEnableModule("CommandChanger")) { - TabooLibraryModule.getInst().register(new ModuleCommandChanger()); - } - if (isEnableModule("InventorySave")) { - TabooLibraryModule.getInst().register(new ModuleInventorySave()); - } - - // 载入模块 - TabooLibraryModule.getInst().loadModules(); - // 提示 - TLocale.Logger.info("TABOOLIB-MODULE.SUCCESS-LOADED", String.valueOf(TabooLibraryModule.getInst().getSize())); - } - - /** - * 获取 TLM 对象 - * - * @return TLM - */ - public static TLM getInst() { - if (inst == null) { - synchronized (TLM.class) { - if (inst == null) { - inst = new TLM(); - } - } - } - return inst; - } - - public FileConfiguration getConfig() { - return config; - } - - public Language2 getLanguage() { - return language; - } - - /** - * 载入配置文件 - */ - public void reloadConfig() { - config = ConfigUtils.saveDefaultConfig(Main.getInst(), "module.yml"); - language = new Language2(config.getString("Language"), Main.getInst()); - } - - /** - * 模块是否启用 - * - * @param name 名称 - * @return boolean - */ - public boolean isEnableModule(String name) { - return config.getStringList("EnableModule").contains(name); - } - - public void loadedFall(String moduleName, String result, String location) { - TLocale.Logger.error("TABOOLIB-MODULE.FAIL-LOADED", moduleName, result, location); - } - - public void runtimeFall(String moduleName, String result, String location) { - TLocale.Logger.error("TABOOLIB-MODULE.FAIL-RUNTIME", moduleName, result, location); - } -} diff --git a/src/main/java/me/skymc/tlm/annotation/DisableConfig.java b/src/main/java/me/skymc/tlm/annotation/DisableConfig.java deleted file mode 100644 index 90a3b18..0000000 --- a/src/main/java/me/skymc/tlm/annotation/DisableConfig.java +++ /dev/null @@ -1,13 +0,0 @@ -package me.skymc.tlm.annotation; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -@Retention(RUNTIME) -@Target(TYPE) -public @interface DisableConfig { - -} diff --git a/src/main/java/me/skymc/tlm/command/TLMCommands.java b/src/main/java/me/skymc/tlm/command/TLMCommands.java deleted file mode 100644 index 99b6393..0000000 --- a/src/main/java/me/skymc/tlm/command/TLMCommands.java +++ /dev/null @@ -1,68 +0,0 @@ -package me.skymc.tlm.command; - -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.commands.builder.SimpleCommandBuilder; -import me.skymc.taboolib.object.Instantiable; -import me.skymc.tlm.TLM; -import me.skymc.tlm.command.sub.TLMInvCommand; -import me.skymc.tlm.command.sub.TLMKitCommand; -import me.skymc.tlm.command.sub.TLMListCommand; -import me.skymc.tlm.command.sub.TLMReloadCommand; - -/** - * @author sky - * @since 2018年2月18日 上午12:02:08 - */ -@Instantiable("TLMCommands") -public class TLMCommands { - - public TLMCommands() { - SimpleCommandBuilder.create("taboolibrarymodule", TabooLib.instance()) - .aliases("tlm") - .permission("tlm.use") - .execute((sender, args) -> { - if (args.length == 0 || "help".equalsIgnoreCase(args[0])) { - if (sender.hasPermission("taboolib.admin")) { - TLM.getInst().getLanguage().get("COMMAND-HELP").send(sender); - } else { - TLM.getInst().getLanguage().get("NOPERMISSION-HELP").send(sender); - } - } - - // 重载 - else if ("reload".equalsIgnoreCase(args[0])) { - if (sender.hasPermission("taboolib.admin")) { - new TLMReloadCommand(sender, args); - } else { - TLM.getInst().getLanguage().get("NOPERMISSION-RELOAD").send(sender); - } - } - - // 列出 - else if ("list".equalsIgnoreCase(args[0])) { - if (sender.hasPermission("taboolib.admin")) { - new TLMListCommand(sender, args); - } else { - TLM.getInst().getLanguage().get("NOPERMISSION-LIST").send(sender); - } - } - - // InventorySave 模块 - else if ("inv".equalsIgnoreCase(args[0])) { - if (sender.hasPermission("taboolib.admin")) { - new TLMInvCommand(sender, args); - } else { - TLM.getInst().getLanguage().get("NOPERMISSION-INV").send(sender); - } - } - - // Kit 模块 - else if ("kit".equalsIgnoreCase(args[0])) { - new TLMKitCommand(sender, args); - } else { - TLM.getInst().getLanguage().get("COMMAND-ERROR").send(sender); - } - return true; - }).build(); - } -} diff --git a/src/main/java/me/skymc/tlm/command/sub/TLMInvCommand.java b/src/main/java/me/skymc/tlm/command/sub/TLMInvCommand.java deleted file mode 100644 index 2c130e1..0000000 --- a/src/main/java/me/skymc/tlm/command/sub/TLMInvCommand.java +++ /dev/null @@ -1,201 +0,0 @@ -package me.skymc.tlm.command.sub; - - -import me.skymc.taboolib.commands.SubCommand; -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.tlm.TLM; -import me.skymc.tlm.inventory.TLMInventoryHolder; -import me.skymc.tlm.module.TabooLibraryModule; -import me.skymc.tlm.module.sub.ModuleInventorySave; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.util.List; - -/** - * @author sky - * @since 2018年2月18日 下午2:53:58 - */ -public class TLMInvCommand extends SubCommand { - - /** - * @param sender - * @param args - */ - public TLMInvCommand(CommandSender sender, String[] args) { - super(sender, args); - if (TabooLibraryModule.getInst().valueOf("InventorySave") == null) { - TLM.getInst().getLanguage().get("INV-DISABLE").send(sender); - return; - } - - // 获取模块 - ModuleInventorySave moduleInventorySave = (ModuleInventorySave) TabooLibraryModule.getInst().valueOf("InventorySave"); - - // 判断命令 - if (args.length == 1) { - TLM.getInst().getLanguage().get("INV-EMPTY").send(sender); - } - - // 列出背包 - else if ("list".equalsIgnoreCase(args[1])) { - TLM.getInst().getLanguage().get("INV-LIST").addPlaceholder("$name", moduleInventorySave.getInventorys().toString()).send(sender); - } - - // 查看背包 - else if ("info".equalsIgnoreCase(args[1])) { - // 如果是后台 - if (!(sender instanceof Player)) { - TLM.getInst().getLanguage().get("INV-CONSOLE").send(sender); - return; - } - - // 判断长度 - if (args.length < 3) { - TLM.getInst().getLanguage().get("INV-NAME").send(sender); - return; - } - - // 判断背包 - if (!moduleInventorySave.getInventorys().contains(args[2])) { - TLM.getInst().getLanguage().get("INV-NOTFOUND").addPlaceholder("$name", args[2]).send(sender); - return; - } - - // 获取玩家 - Player player = (Player) sender; - - // 获取物品 - List items = moduleInventorySave.getItems(args[2]); - - // 打开界面 - Inventory inv = Bukkit.createInventory(new TLMInventoryHolder("InventorySave"), 54, TLM.getInst().getLanguage().get("INV-INFO-TITLE") - .addPlaceholder("$name", args[2]) - .asString()); - - // 设置物品 - ItemStack barrier = ItemUtils.setName(new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 15), "§f"); - - for (int i = 9 ; i < 18 ; i++) { - inv.setItem(i, barrier); - } - - for (int i = 9 ; i < 35 ; i++) { - inv.setItem(i + 9, items.get(i)); - } - - for (int i = 0 ; i < 9 ; i++) { - inv.setItem(i + 45, items.get(i)); - } - - inv.setItem(1, items.get(39)); - inv.setItem(2, items.get(38)); - inv.setItem(3, items.get(37)); - inv.setItem(4, items.get(36)); - - // 判断版本 - if (items.size() == 41) { - inv.setItem(6, items.get(40)); - } - - // 打开背包 - player.openInventory(inv); - } - - // 保存背包 - else if ("save".equalsIgnoreCase(args[1])) { - // 如果是后台 - if (!(sender instanceof Player)) { - TLM.getInst().getLanguage().get("INV-CONSOLE").send(sender); - return; - } - - // 判断长度 - if (args.length < 3) { - TLM.getInst().getLanguage().get("INV-NAME").send(sender); - return; - } - - // 获取玩家 - Player player = (Player) sender; - - // 保存背包 - moduleInventorySave.saveInventory(player, args[2]); - - // 提示信息 - TLM.getInst().getLanguage().get("INV-SAVE").addPlaceholder("$name", args[2]).send(player); - } - - // 覆盖背包 - else if ("paste".equalsIgnoreCase(args[1])) { - // 判断长度 - if (args.length < 3) { - TLM.getInst().getLanguage().get("INV-NAME").send(sender); - return; - } - - // 判断背包 - if (!moduleInventorySave.getInventorys().contains(args[2])) { - TLM.getInst().getLanguage().get("INV-NOTFOUND").addPlaceholder("$name", args[2]).send(sender); - return; - } - - // 获取玩家 - Player player; - if (args.length > 3) { - player = Bukkit.getPlayerExact(args[3]); - // 玩家不存在 - if (player == null) { - TLM.getInst().getLanguage().get("INV-OFFLINE").addPlaceholder("$name", args[3]).send(sender); - return; - } - } else if (sender instanceof Player) { - player = (Player) sender; - } else { - TLM.getInst().getLanguage().get("INV-CONSOLE").send(sender); - return; - } - - // 覆盖背包 - moduleInventorySave.pasteInventory(player, args[2], args.length > 4 ? args[4] : "null"); - - // 如果是玩家 - if (sender instanceof Player) { - // 提示信息 - TLM.getInst().getLanguage().get("INV-PASTE") - .addPlaceholder("$name", args[2]) - .addPlaceholder("$player", player.getName()) - .send(player); - } - } - - // 删除背包 - else if ("delete".equalsIgnoreCase(args[1])) { - // 判断长度 - if (args.length < 3) { - TLM.getInst().getLanguage().get("INV-NAME").send(sender); - return; - } - - // 判断背包 - if (!moduleInventorySave.getInventorys().contains(args[2])) { - TLM.getInst().getLanguage().get("INV-NOTFOUND").addPlaceholder("$name", args[2]).send(sender); - return; - } - - // 删除 - moduleInventorySave.deleteInventory(args[2]); - - // 提示信息 - TLM.getInst().getLanguage().get("KIT-DELETE").addPlaceholder("$name", args[2]).send(sender); - } - - else { - TLM.getInst().getLanguage().get("INV-EMPTY").send(sender); - } - } -} diff --git a/src/main/java/me/skymc/tlm/command/sub/TLMKitCommand.java b/src/main/java/me/skymc/tlm/command/sub/TLMKitCommand.java deleted file mode 100644 index fa22444..0000000 --- a/src/main/java/me/skymc/tlm/command/sub/TLMKitCommand.java +++ /dev/null @@ -1,173 +0,0 @@ -package me.skymc.tlm.command.sub; - -import me.skymc.taboolib.commands.SubCommand; -import me.skymc.tlm.TLM; -import me.skymc.tlm.module.TabooLibraryModule; -import me.skymc.tlm.module.sub.ModuleKits; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.HashMap; -import java.util.List; - -/** - * @author sky - * @since 2018年2月18日 下午2:53:58 - */ -public class TLMKitCommand extends SubCommand { - - /** - * @param sender - * @param args - */ - public TLMKitCommand(CommandSender sender, String[] args) { - super(sender, args); - if (TabooLibraryModule.getInst().valueOf("Kits") == null) { - TLM.getInst().getLanguage().get("KIT-DISABLE").send(sender); - return; - } - - // 获取模块 - ModuleKits moduleKits = (ModuleKits) TabooLibraryModule.getInst().valueOf("Kits"); - - // 判断命令 - if (args.length == 1) { - TLM.getInst().getLanguage().get("KIT-EMPTY").send(sender); - } - - else if ("list".equalsIgnoreCase(args[1])) { - // 判断权限 - if (!sender.hasPermission("taboolib.kit.list")) { - TLM.getInst().getLanguage().get("NOPERMISSION-KIT-LIST").send(sender); - } - else { - TLM.getInst().getLanguage().get("KIT-LIST") - .addPlaceholder("$kits", moduleKits.getConfig().getConfigurationSection("Kits").getKeys(false).toString()) - .send(sender); - } - } - - else if ("reward".equalsIgnoreCase(args[1])) { - // 判断权限 - if (!sender.hasPermission("taboolib.kit.reward")) { - TLM.getInst().getLanguage().get("NOPERMISSION-KIT-REWARD").send(sender); - return; - } - - // 检查礼包 - if (args.length < 3) { - TLM.getInst().getLanguage().get("KIT-NAME").send(sender); - return; - } - - // 礼包不存在 - if (!moduleKits.contains(args[2])) { - TLM.getInst().getLanguage().get("KIT-NOTFOUND").addPlaceholder("$kit", args[2]).send(sender); - return; - } - - // 获取玩家 - Player player; - if (args.length > 3) { - player = Bukkit.getPlayerExact(args[3]); - // 玩家不存在 - if (player == null) { - TLM.getInst().getLanguage().get("KIT-OFFLINE").addPlaceholder("$name", args[3]).send(sender); - return; - } - } else if (sender instanceof Player) { - player = (Player) sender; - } else { - TLM.getInst().getLanguage().get("KIT-CONSOLE").send(sender); - return; - } - - // 是否领取 - if (moduleKits.isPlayerRewared(player, args[2])) { - // 是否只能领取一次 - if (moduleKits.isDisposable(args[2])) { - TLM.getInst().getLanguage().get("KIT-DISPOSABLE").addPlaceholder("$kit", args[2]).send(sender); - return; - } - // 是否冷却中 - if (moduleKits.isPlayerCooldown(player, args[2])) { - TLM.getInst().getLanguage().get("KIT-COOLDOWN").addPlaceholder("$kit", args[2]).send(sender); - return; - } - } - - // 是否有权限领取 - String permission = moduleKits.getPermission(args[2]); - if (permission != null && !player.hasPermission(permission)) { - // 提示信息 - player.sendMessage(moduleKits.getPermissionMessage(args[2])); - return; - } - - // 发送礼包 - List items = moduleKits.getItems(args[2]); - for (ItemStack item : items) { - // 给予物品 - HashMap result = player.getInventory().addItem(item); - // 如果背包空间不足 - if (result.size() > 0 && moduleKits.isFullDrop(args[2])) { - // 掉落物品 - player.getWorld().dropItem(player.getLocation(), item); - } - } - - // 执行命令 - for (String command : moduleKits.getCommands(args[2])) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.replace("$player", player.getName())); - } - - // 已领取 - moduleKits.setPlayerReward(player, args[2], true); - - // 提示信息 - TLM.getInst().getLanguage().get("KIT-SUCCESS").addPlaceholder("$kit", args[2]).send(sender); - } - else if ("reset".equalsIgnoreCase(args[1])) { - // 判断权限 - if (!sender.hasPermission("taboolib.kit.reset")) { - TLM.getInst().getLanguage().get("NOPERMISSION-KIT-RESET").send(sender); - return; - } - - // 检查礼包 - if (args.length < 3) { - TLM.getInst().getLanguage().get("KIT-NAME").send(sender); - return; - } - - // 礼包不存在 - if (!moduleKits.contains(args[2])) { - TLM.getInst().getLanguage().get("KIT-NOTFOUND").addPlaceholder("$kit", args[2]).send(sender); - return; - } - - // 获取玩家 - Player player; - if (args.length > 3) { - player = Bukkit.getPlayerExact(args[3]); - // 玩家不存在 - if (player == null) { - TLM.getInst().getLanguage().get("KIT-OFFLINE").addPlaceholder("$name", args[3]).send(sender); - } - else { - moduleKits.setPlayerReward(player, args[2], false); - TLM.getInst().getLanguage().get("KIT-RESET-PLAYER").addPlaceholder("$kit", args[2]).addPlaceholder("$player", player.getName()).send(sender); - } - } else { - moduleKits.resetKit(args[2]); - TLM.getInst().getLanguage().get("KIT-RESET-ALL").addPlaceholder("$kit", args[2]).send(sender); - } - } - else { - TLM.getInst().getLanguage().get("COMMAND-ERROR").send(sender); - } - } - -} diff --git a/src/main/java/me/skymc/tlm/command/sub/TLMListCommand.java b/src/main/java/me/skymc/tlm/command/sub/TLMListCommand.java deleted file mode 100644 index 42a0906..0000000 --- a/src/main/java/me/skymc/tlm/command/sub/TLMListCommand.java +++ /dev/null @@ -1,31 +0,0 @@ -package me.skymc.tlm.command.sub; - -import me.skymc.taboolib.commands.SubCommand; -import me.skymc.tlm.module.ITabooLibraryModule; -import me.skymc.tlm.module.TabooLibraryModule; -import org.bukkit.command.CommandSender; - -/** - * @author sky - * @since 2018年2月18日 下午2:10:12 - */ -public class TLMListCommand extends SubCommand { - - /** - * @param sender - * @param args - */ - public TLMListCommand(CommandSender sender, String[] args) { - super(sender, args); - sender.sendMessage("§f"); - sender.sendMessage("§b§l----- §3§lTaooLibraryModule Modules §b§l-----"); - sender.sendMessage("§f"); - - for (ITabooLibraryModule module : TabooLibraryModule.getInst().keySet()) { - sender.sendMessage("§f - §8" + module.getName()); - } - - sender.sendMessage("§f"); - } - -} diff --git a/src/main/java/me/skymc/tlm/command/sub/TLMReloadCommand.java b/src/main/java/me/skymc/tlm/command/sub/TLMReloadCommand.java deleted file mode 100644 index 05fdbd8..0000000 --- a/src/main/java/me/skymc/tlm/command/sub/TLMReloadCommand.java +++ /dev/null @@ -1,48 +0,0 @@ -package me.skymc.tlm.command.sub; - -import me.skymc.taboolib.commands.SubCommand; -import me.skymc.taboolib.message.MsgUtils; -import me.skymc.tlm.TLM; -import me.skymc.tlm.module.ITabooLibraryModule; -import me.skymc.tlm.module.TabooLibraryModule; -import org.bukkit.command.CommandSender; - -/** - * @author sky - * @since 2018年2月18日 下午2:09:34 - */ -public class TLMReloadCommand extends SubCommand { - - /** - * @param sender - * @param args - */ - public TLMReloadCommand(CommandSender sender, String[] args) { - super(sender, args); - if (args.length != 2) { - MsgUtils.send(sender, "&4参数错误。"); - } - - else if ("tlm".equalsIgnoreCase(args[1])) { - TLM.getInst().reloadConfig(); - MsgUtils.send(sender, "&fTLM &7配置文件已重载。"); - } - - else if ("all".equalsIgnoreCase(args[1])) { - TabooLibraryModule.getInst().reloadConfig(); - MsgUtils.send(sender, "所有模块配置文件已重载。"); - } - - else { - ITabooLibraryModule module = TabooLibraryModule.getInst().valueOf(args[1]); - if (module == null) { - MsgUtils.send(sender, "&4模块 &c" + args[1] + " &4不存在。"); - } - else { - TabooLibraryModule.getInst().reloadConfig(module, true); - MsgUtils.send(sender, "模块 &f" + args[1] + " &7的配置文件已重载。"); - } - } - } - -} diff --git a/src/main/java/me/skymc/tlm/inventory/TLMInventoryHolder.java b/src/main/java/me/skymc/tlm/inventory/TLMInventoryHolder.java deleted file mode 100644 index 526396c..0000000 --- a/src/main/java/me/skymc/tlm/inventory/TLMInventoryHolder.java +++ /dev/null @@ -1,39 +0,0 @@ -package me.skymc.tlm.inventory; - -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; - -import java.util.HashMap; - -/** - * @author sky - * @since 2018年2月22日 下午3:34:59 - */ -public class TLMInventoryHolder implements InventoryHolder { - - private String module; - - private HashMap holderData = new HashMap<>(); - - /** - * 构造方法 - * - * @param module 模块名 - */ - public TLMInventoryHolder(String module) { - this.module = module; - } - - public String getModule() { - return module; - } - - public HashMap getHolderData() { - return holderData; - } - - @Override - public Inventory getInventory() { - return null; - } -} diff --git a/src/main/java/me/skymc/tlm/module/ITabooLibraryModule.java b/src/main/java/me/skymc/tlm/module/ITabooLibraryModule.java deleted file mode 100644 index 1526b90..0000000 --- a/src/main/java/me/skymc/tlm/module/ITabooLibraryModule.java +++ /dev/null @@ -1,25 +0,0 @@ -package me.skymc.tlm.module; - -import org.bukkit.configuration.file.FileConfiguration; - -/** - * @author sky - * @since 2018年2月17日 下午11:22:42 - */ -public interface ITabooLibraryModule { - - default void onEnable() { - } - - default void onDisable() { - } - - default void onReload() { - } - - String getName(); - - default FileConfiguration getConfig() { - return TabooLibraryModule.getInst().getConfig(this); - } -} diff --git a/src/main/java/me/skymc/tlm/module/TabooLibraryModule.java b/src/main/java/me/skymc/tlm/module/TabooLibraryModule.java deleted file mode 100644 index 9da328c..0000000 --- a/src/main/java/me/skymc/tlm/module/TabooLibraryModule.java +++ /dev/null @@ -1,100 +0,0 @@ -package me.skymc.tlm.module; - -import me.skymc.taboolib.Main; -import me.skymc.tlm.annotation.DisableConfig; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.event.Listener; - -import java.io.File; -import java.util.HashMap; -import java.util.Set; - -/** - * @author sky - * @since 2018年2月17日 下午11:22:48 - */ -public class TabooLibraryModule { - - private static TabooLibraryModule inst = null; - private final HashMap TLM_MODULE = new HashMap<>(); - - private TabooLibraryModule() { - - } - - public static TabooLibraryModule getInst() { - if (inst == null) { - synchronized (TabooLibraryModule.class) { - if (inst == null) { - inst = new TabooLibraryModule(); - } - } - } - return inst; - } - - public void register(ITabooLibraryModule module) { - if (!TLM_MODULE.containsKey(module)) { - TLM_MODULE.put(module, new YamlConfiguration()); - reloadConfig(module, false); - } - } - - public void loadModules() { - for (ITabooLibraryModule module : TLM_MODULE.keySet()) { - module.onEnable(); - if (module instanceof Listener) { - Bukkit.getPluginManager().registerEvents((Listener) module, Main.getInst()); - } - } - } - - public void unloadModules() { - TLM_MODULE.keySet().forEach(ITabooLibraryModule::onDisable); - } - - public void reloadConfig() { - TLM_MODULE.keySet().forEach(x -> reloadConfig(x, true)); - } - - public void reloadConfig(ITabooLibraryModule module, boolean isReload) { - if (module.getName() == null || module.getClass().getAnnotation(DisableConfig.class) != null) { - return; - } - File file = new File(Main.getInst().getDataFolder(), "TLM/" + module.getName() + ".yml"); - if (!file.exists()) { - Main.getInst().saveResource("TLM/" + module.getName() + ".yml", true); - } - try { - TLM_MODULE.get(module).load(file); - } catch (Exception e) { - // TODO Auto-generated catch block - } - if (isReload) { - module.onReload(); - } - } - - public FileConfiguration getConfig(ITabooLibraryModule module) { - return TLM_MODULE.get(module); - } - - public int getSize() { - return TLM_MODULE.size(); - } - - public Set keySet() { - return TLM_MODULE.keySet(); - } - - public ITabooLibraryModule valueOf(String name) { - for (ITabooLibraryModule module : TLM_MODULE.keySet()) { - if (module.getName().equals(name)) { - return module; - } - } - return null; - } -} diff --git a/src/main/java/me/skymc/tlm/module/sub/ModuleCommandChanger.java b/src/main/java/me/skymc/tlm/module/sub/ModuleCommandChanger.java deleted file mode 100644 index 186c72c..0000000 --- a/src/main/java/me/skymc/tlm/module/sub/ModuleCommandChanger.java +++ /dev/null @@ -1,55 +0,0 @@ -package me.skymc.tlm.module.sub; - -import me.skymc.tlm.module.ITabooLibraryModule; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.server.ServerCommandEvent; - -/** - * @author sky - * @since 2018年2月22日 下午1:32:29 - */ -public class ModuleCommandChanger implements ITabooLibraryModule, Listener { - - @Override - public String getName() { - return "CommandChanger"; - } - - @EventHandler - public void command(PlayerCommandPreprocessEvent e) { - // 循环命令 - for (String id : getConfig().getConfigurationSection("Commands").getKeys(false)) { - // 获取命令 - String key = getConfig().getString("Commands." + id + ".Input"); - // 判断命令 - if (e.getMessage().startsWith(key)) { - // 判断执行方式 - if (!getConfig().contains("Commands." + id + ".ReplaceMode") || "PLAYER".equals(getConfig().getString("Commands." + id + ".ReplaceMode"))) { - // 替换命令 - e.setMessage(e.getMessage().replace(key, getConfig().getString("Commands." + id + ".Replace"))); - return; - } - } - } - } - - @EventHandler - public void command(ServerCommandEvent e) { - // 循环命令 - for (String id : getConfig().getConfigurationSection("Commands").getKeys(false)) { - // 获取命令 - String key = getConfig().getString("Commands." + id + ".Input"); - // 判断命令 - if (e.getCommand().startsWith(key)) { - // 判断执行方式 - if (!getConfig().contains("Commands." + id + ".ReplaceMode") || "CONSOLE".equals(getConfig().getString("Commands." + id + ".ReplaceMode"))) { - // 替换命令 - e.setCommand(e.getCommand().replace(key, getConfig().getString("Commands." + id + ".Replace"))); - return; - } - } - } - } -} diff --git a/src/main/java/me/skymc/tlm/module/sub/ModuleInventorySave.java b/src/main/java/me/skymc/tlm/module/sub/ModuleInventorySave.java deleted file mode 100644 index b6f71a0..0000000 --- a/src/main/java/me/skymc/tlm/module/sub/ModuleInventorySave.java +++ /dev/null @@ -1,174 +0,0 @@ -package me.skymc.tlm.module.sub; - -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.playerdata.DataUtils; -import me.skymc.tlm.TLM; -import me.skymc.tlm.annotation.DisableConfig; -import me.skymc.tlm.inventory.TLMInventoryHolder; -import me.skymc.tlm.module.ITabooLibraryModule; -import org.bukkit.Material; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * @author sky - * @since 2018年2月22日 下午2:48:27 - */ -@DisableConfig -public class ModuleInventorySave implements ITabooLibraryModule, Listener { - - private FileConfiguration conf; - - @Override - public String getName() { - return "InventorySave"; - } - - @Override - public void onEnable() { - reloadConfig(); - } - - @Override - public void onReload() { - reloadConfig(); - } - - public void reloadConfig() { - conf = DataUtils.addPluginData("InventorySave", Main.getInst()); - } - - /** - * 保存玩家背包 - * - * @param player 玩家 - * @param name 名称 - */ - public void saveInventory(Player player, String name) { - // 设置物品 - for (int i = 0; i < (TabooLib.getVerint() > 10800 ? 41 : 40); i++) { - ItemStack item = player.getInventory().getItem(i); - conf.set(name + "." + i, item == null ? new ItemStack(Material.AIR) : item.clone()); - } - } - - /** - * 覆盖玩家背包 - * - * @param player 玩家 - * @param name 名称 - */ - public void pasteInventory(Player player, String name) { - pasteInventory(player, name, "null"); - } - - /** - * 覆盖玩家背包 - * - * @param player 玩家 - * @param name 名称 - * @param module 模式 - */ - public void pasteInventory(Player player, String name, String module) { - // 如果背包不存在 - if (!conf.contains(name)) { - TLM.getInst().runtimeFall("InventorySave", "InventoryNotFound", name); - return; - } - // 异常物品 - List otherItem = new ArrayList<>(); - // 设置物品 - for (int i = 0; i < (TabooLib.getVerint() > 10800 ? 41 : 40); i++) { - try { - ItemStack item = (ItemStack) conf.get(name + "." + i); - // 如果原本有物品 - if (!ItemUtils.isNull(player.getInventory().getItem(i))) { - // 跳过 - if ("-b".equalsIgnoreCase(module)) { - continue; - } - // 给予 - else if ("-a".equalsIgnoreCase(module)) { - otherItem.add(item); - continue; - } - } - // 覆盖 - player.getInventory().setItem(i, item); - } catch (Exception e) { - TLM.getInst().runtimeFall("InventorySave", "InventoryCoverFall", name); - } - } - // 循环异常物品 - for (ItemStack item : otherItem) { - player.getInventory().addItem(item); - } - } - - /** - * 获取背包内所有物品 - * - * @param name 背包名称 - * @return {@link List} - */ - public List getItems(String name) { - // 如果背包不存在 - if (!conf.contains(name)) { - TLM.getInst().runtimeFall("InventorySave", "InventoryNotFound", name); - return new LinkedList<>(); - } - - List items = new LinkedList<>(); - // 设置物品 - for (int i = 0; i < (TabooLib.getVerint() > 10800 ? 41 : 40); i++) { - try { - ItemStack item = (ItemStack) conf.get(name + "." + i); - items.add(item); - } catch (Exception e) { - TLM.getInst().runtimeFall("InventorySave", "ItemStackLoadFall", name); - } - } - return items; - } - - /** - * 获取所有背包 - * - * @return {@link Set} - */ - public Set getInventorys() { - return conf.getConfigurationSection("").getKeys(false); - } - - /** - * 删除背包 - * - * @param name 名称 - */ - public void deleteInventory(String name) { - conf.set(name, null); - } - - @EventHandler - public void onClick(InventoryClickEvent e) { - if (!(e.getInventory().getHolder() instanceof TLMInventoryHolder)) { - return; - } - - TLMInventoryHolder holder = (TLMInventoryHolder) e.getInventory().getHolder(); - if (holder.getModule().equals(getName())) { - e.setCancelled(true); - } - } -} diff --git a/src/main/java/me/skymc/tlm/module/sub/ModuleKits.java b/src/main/java/me/skymc/tlm/module/sub/ModuleKits.java deleted file mode 100644 index 15f7d3d..0000000 --- a/src/main/java/me/skymc/tlm/module/sub/ModuleKits.java +++ /dev/null @@ -1,166 +0,0 @@ -package me.skymc.tlm.module.sub; - -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.other.DateUtils; -import me.skymc.taboolib.other.NumberUtils; -import me.skymc.taboolib.playerdata.DataUtils; -import me.skymc.tlm.TLM; -import me.skymc.tlm.module.ITabooLibraryModule; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author sky - * @since 2018年2月18日 下午12:13:55 - */ -public class ModuleKits implements ITabooLibraryModule { - - private FileConfiguration data; - - @Override - public String getName() { - return "Kits"; - } - - @Override - public void onEnable() { - data = DataUtils.addPluginData("ModuleKits", null); - } - - /** - * 设置玩家是否领取礼包 - * - * @param player 玩家 - */ - public void setPlayerReward(Player player, String kit, boolean reward) { - data.set(kit + "." + player.getName(), reward ? System.currentTimeMillis() : null); - } - - /** - * 清空礼包数据 - * - * @param kit 礼包 - */ - public void resetKit(String kit) { - data.set(kit, null); - } - - /** - * 玩家是否领取礼包 - * - * @param player 玩家 - * @param kit 礼包 - * @return boolean - */ - public boolean isPlayerRewared(Player player, String kit) { - return data.contains(kit + "." + player.getName()); - } - - /** - * 礼包是否在冷却中 - * - * @param player - * @param kit - * @return - */ - public boolean isPlayerCooldown(Player player, String kit) { - return System.currentTimeMillis() - data.getLong(kit + "." + player.getName()) < getCooldown(kit); - } - - /** - * 礼包是否存在 - * - * @param kit 礼包名 - * @return boolean - */ - public boolean contains(String kit) { - return getConfig().contains("Kits." + kit); - } - - /** - * 获取礼包冷却时间 - * - * @param kit 礼包名 - * @return long - */ - public long getCooldown(String kit) { - return DateUtils.formatDate(getConfig().getString("Kits." + kit + ".Cooldown")); - } - - /** - * 获取礼包空间不足时的处理方式 - * - * @param kit 礼包名 - * @return boolean - */ - public Boolean isFullDrop(String kit) { - return getConfig().getBoolean("Kits." + kit + ".FullDrop"); - } - - /** - * 礼包是否只能领取一次 - * - * @param kit 礼包名 - * @return boolean - */ - public boolean isDisposable(String kit) { - return getConfig().getBoolean("Kits." + kit + ".Disposable"); - } - - /** - * 获取礼包权限 - * - * @param kit 礼包名 - * @return String - */ - public String getPermission(String kit) { - return getConfig().getString("Kits." + kit + ".Permission"); - } - - /** - * 获取礼包权限提示 - * - * @param kit 礼包名 - * @return String - */ - public String getPermissionMessage(String kit) { - return getConfig().getString("Kits." + kit + ".Permission-message").replace("&", "§"); - } - - /** - * 获取礼包物品 - * - * @param kit 礼包名 - * @return {@link List} - */ - public List getItems(String kit) { - List items = new ArrayList<>(); - for (String itemStr : getConfig().getStringList("Kits." + kit + ".Items")) { - ItemStack item = ItemUtils.getCacheItem(itemStr.split(" ")[0]); - if (item != null) { - item = item.clone(); - try { - item.setAmount(NumberUtils.getInteger(itemStr.split(" ")[1])); - items.add(item); - } catch (Exception e) { - TLM.getInst().runtimeFall("Kits", "InvalidAmount", itemStr); - } - } - } - return items; - } - - /** - * 获取礼包命令 - * - * @param kit 礼包名 - * @return {@link List} - */ - public List getCommands(String kit) { - return getConfig().contains("Kits." + kit + ".Commands") ? getConfig().getStringList("Kits." + kit + ".Commands") : new ArrayList<>(); - } -} diff --git a/src/main/java/me/skymc/tlm/module/sub/ModuleTimeCycle.java b/src/main/java/me/skymc/tlm/module/sub/ModuleTimeCycle.java deleted file mode 100644 index 772dd84..0000000 --- a/src/main/java/me/skymc/tlm/module/sub/ModuleTimeCycle.java +++ /dev/null @@ -1,109 +0,0 @@ -package me.skymc.tlm.module.sub; - -import me.skymc.taboolib.Main; -import me.skymc.taboolib.other.DateUtils; -import me.skymc.taboolib.other.NumberUtils; -import me.skymc.taboolib.timecycle.TimeCycle; -import me.skymc.taboolib.timecycle.TimeCycleEvent; -import me.skymc.taboolib.timecycle.TimeCycleInitializeEvent; -import me.skymc.taboolib.timecycle.TimeCycleManager; -import me.skymc.tlm.TLM; -import me.skymc.tlm.module.ITabooLibraryModule; -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -import java.util.Calendar; - -/** - * @author sky - * @since 2018年2月17日 下午11:23:38 - */ -public class ModuleTimeCycle implements ITabooLibraryModule, Listener { - - @Override - public String getName() { - return "TimeCycle"; - } - - @Override - public void onEnable() { - // 载入检查器 - loadCycles(); - } - - @Override - public void onDisable() { - // 注销检查器 - unloadCycles(); - } - - @Override - public void onReload() { - // 注销检查器 - unloadCycles(); - // 载入检查器 - loadCycles(); - } - - @EventHandler - public void onTimeCycleInitialize(TimeCycleInitializeEvent e) { - if (e.getCycle().getName().contains("tlm|")) { - // 获取名称 - String name = e.getCycle().getName().replace("tlm|", ""); - // 如果有初始化时间配置 - if (getConfig().contains("TimeCycle." + name + ".Initialise.InitialiseDate")) { - // 获取时间 - Calendar date = Calendar.getInstance(); - // 遍历初始化规则 - for (String typeStr : getConfig().getStringList("TimeCycle." + name + ".Initialise.InitialiseDate")) { - try { - int type = (int) Calendar.class.getField(typeStr.split("=")[0]).get(Calendar.class); - date.set(type, NumberUtils.getInteger(typeStr.split("=")[1])); - } catch (Exception ignored) { - TLM.getInst().runtimeFall("TimeCycle", "DateFormatFall", typeStr); - } - } - e.setTimeLine(date.getTimeInMillis()); - } - // 如果有初始化命令 - if (getConfig().contains("TimeCycle." + name + ".Initialise.InitialiseCommand")) { - // 遍历初始化命令 - for (String command : getConfig().getStringList("TimeCycle." + name + ".Initialise.InitialiseCommand")) { - // 执行命令 - Bukkit.getScheduler().runTask(Main.getInst(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)); - } - } - } - } - - @EventHandler - public void onTimeCycle(TimeCycleEvent e) { - if (e.getCycle().getName().contains("tlm|")) { - // 获取名称 - String name = e.getCycle().getName().replace("tlm|", ""); - // 如果有更新命令 - if (getConfig().contains("TimeCycle." + name + ".UpdateCommand")) { - // 遍历更新命令 - for (String command : getConfig().getStringList("TimeCycle." + name + ".UpdateCommand")) { - // 执行命令 - Bukkit.getScheduler().runTask(Main.getInst(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)); - } - } - } - } - - private void loadCycles() { - for (String name : getConfig().getConfigurationSection("TimeCycle").getKeys(false)) { - TimeCycleManager.register(new TimeCycle("tlm|" + name, DateUtils.formatDate(getConfig().getString("TimeCycle." + name + ".Cycle")), Main.getInst())); - } - } - - private void unloadCycles() { - for (TimeCycle cycle : TimeCycleManager.getTimeCycles()) { - if (cycle.getName().startsWith("tlm|")) { - TimeCycleManager.cancel(cycle.getName()); - } - } - } -} diff --git a/src/main/resources/Addons/TabooLibDeprecated.jar b/src/main/resources/Addons/TabooLibDeprecated.jar new file mode 100644 index 0000000..3565ece Binary files /dev/null and b/src/main/resources/Addons/TabooLibDeprecated.jar differ