From 19d318a610d71cea6fc9f3e35cf685bdeda5038d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9D=8F=E9=BB=91?= Date: Tue, 8 May 2018 23:31:26 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 20 +- .../java/com/ilummc/tlib/ExampleMain.java | 5 +- .../java/com/ilummc/tlib/bean/Property.java | 6 +- .../com/ilummc/tlib/bungee/api/ChatColor.java | 180 ++ .../tlib/bungee/api/ChatMessageType.java | 12 + .../tlib/bungee/api/chat/BaseComponent.java | 493 ++++ .../tlib/bungee/api/chat/ClickEvent.java | 61 + .../bungee/api/chat/ComponentBuilder.java | 311 ++ .../tlib/bungee/api/chat/HoverEvent.java | 38 + .../tlib/bungee/api/chat/TextComponent.java | 184 ++ .../api/chat/TranslatableComponent.java | 242 ++ .../bungee/chat/BaseComponentSerializer.java | 121 + .../tlib/bungee/chat/ComponentSerializer.java | 58 + .../bungee/chat/TextComponentSerializer.java | 47 + .../chat/TranslatableComponentSerializer.java | 46 + .../ilummc/tlib/compat/PlaceholderHook.java | 6 +- src/main/java/com/ilummc/tlib/db/Pool.java | 4 +- .../com/ilummc/tlib/filter/TLoggerFilter.java | 7 +- .../ilummc/tlib/inject/TConfigInjector.java | 21 +- .../ilummc/tlib/inject/TConfigWatcher.java | 10 +- .../tlib/inject/TDependencyInjector.java | 9 +- .../ilummc/tlib/inject/TPluginManager.java | 4 +- .../java/com/ilummc/tlib/logger/TLogger.java | 21 +- .../com/ilummc/tlib/resources/TLocale.java | 8 +- .../tlib/resources/TLocaleInstance.java | 4 +- .../ilummc/tlib/resources/TLocaleLoader.java | 8 +- .../tlib/resources/type/TLocaleActionBar.java | 3 +- .../tlib/resources/type/TLocaleJson.java | 10 +- src/main/java/com/ilummc/tlib/util/Ref.java | 21 +- .../java/com/ilummc/tlib/util/Strings.java | 9 +- .../com/ilummc/tlib/util/asm/AsmAnalyser.java | 3 +- .../tlib/util/asm/AsmClassTransformer.java | 16 +- .../taboolib/anvil/AnvilContainerAPI.java | 4 +- .../bookformatter/BookReflection.java | 10 +- .../bookformatter/action/ClickAction.java | 5 +- .../bookformatter/builder/PageBuilder.java | 3 +- .../me/skymc/taboolib/bstats/Metrics.java | 157 +- .../skymc/taboolib/commands/MainCommands.java | 40 +- .../commands/internal/InternalArgument.java | 1 + .../commands/language/Language2Command.java | 6 +- .../locale/TabooLibLocaleCommand.java | 7 +- .../plugin/TabooLibPluginCommand.java | 1 + .../taboolib/commands/sub/SaveCommand.java | 2 +- .../commands/sub/VariableGetCommand.java | 54 +- .../commands/sub/VariableSetCommand.java | 47 +- .../commands/sub/cycle/CycleCommand.java | 8 +- .../commands/sub/shell/ShellCommand.java | 5 +- .../taboolib/database/GlobalDataManager.java | 14 +- .../skymc/taboolib/display/ActionUtils.java | 3 +- .../me/skymc/taboolib/entity/EntityTag.java | 16 +- .../skymc/taboolib/fileutils/ConfigUtils.java | 23 +- .../skymc/taboolib/inventory/ItemUtils.java | 4 +- .../taboolib/itemnbtapi/NBTCompound.java | 8 +- .../itemnbtapi/NBTReflectionUtil.java | 118 +- .../me/skymc/taboolib/itemnbtapi/NBTType.java | 6 +- .../java/me/skymc/taboolib/json/Cookie.java | 2 +- .../me/skymc/taboolib/json/JSONArray.java | 4 +- .../java/me/skymc/taboolib/json/JSONML.java | 2 +- .../me/skymc/taboolib/json/JSONObject.java | 14 +- .../me/skymc/taboolib/json/JSONWriter.java | 2 +- .../taboolib/jsonformatter/JSONFormatter.java | 60 +- .../listener/ListenerPlayerCommand.java | 4 +- .../taboolib/location/LocationUtils.java | 4 +- .../skymc/taboolib/message/ChatCatcher.java | 2 +- .../me/skymc/taboolib/message/MsgUtils.java | 4 +- .../skymc/taboolib/methods/MethodsUtils.java | 81 +- .../skymc/taboolib/mysql/MysqlConnection.java | 660 +++-- .../me/skymc/taboolib/mysql/MysqlUtils.java | 59 +- .../mysql/protect/MySQLConnection.java | 364 +-- .../java/me/skymc/taboolib/nms/NMSUtil18.java | 208 +- .../java/me/skymc/taboolib/nms/NMSUtil19.java | 320 ++- .../java/me/skymc/taboolib/nms/NMSUtils.java | 42 +- .../taboolib/nms/item/impl/_164ItemUtils.java | 2513 +++++++++-------- .../nms/item/impl/_1710ItemUtils.java | 40 +- .../taboolib/nms/item/impl/_194ItemUtils.java | 45 +- .../me/skymc/taboolib/plugin/PluginUtils.java | 32 +- .../me/skymc/taboolib/sound/SoundPack.java | 1 + .../me/skymc/taboolib/string/StringUtils.java | 11 +- .../string/language2/value/Language2Book.java | 2 +- .../string/language2/value/Language2Json.java | 2 +- .../me/skymc/taboolib/thread/ThreadUtils.java | 3 + .../me/skymc/tlm/command/TLMCommands.java | 10 +- .../skymc/tlm/command/sub/TLMInvCommand.java | 10 +- .../skymc/tlm/command/sub/TLMKitCommand.java | 6 +- .../tlm/command/sub/TLMReloadCommand.java | 4 +- .../tlm/module/sub/ModuleCommandChanger.java | 4 +- .../tlm/module/sub/ModuleInventorySave.java | 5 +- .../org/javalite/activejdbc/MetaModel.java | 13 +- src/main/resources/lang/zh_CN.yml | 11 + 89 files changed, 4664 insertions(+), 2410 deletions(-) create mode 100644 src/main/java/com/ilummc/tlib/bungee/api/ChatColor.java create mode 100644 src/main/java/com/ilummc/tlib/bungee/api/ChatMessageType.java create mode 100644 src/main/java/com/ilummc/tlib/bungee/api/chat/BaseComponent.java create mode 100644 src/main/java/com/ilummc/tlib/bungee/api/chat/ClickEvent.java create mode 100644 src/main/java/com/ilummc/tlib/bungee/api/chat/ComponentBuilder.java create mode 100644 src/main/java/com/ilummc/tlib/bungee/api/chat/HoverEvent.java create mode 100644 src/main/java/com/ilummc/tlib/bungee/api/chat/TextComponent.java create mode 100644 src/main/java/com/ilummc/tlib/bungee/api/chat/TranslatableComponent.java create mode 100644 src/main/java/com/ilummc/tlib/bungee/chat/BaseComponentSerializer.java create mode 100644 src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java create mode 100644 src/main/java/com/ilummc/tlib/bungee/chat/TextComponentSerializer.java create mode 100644 src/main/java/com/ilummc/tlib/bungee/chat/TranslatableComponentSerializer.java diff --git a/.gitignore b/.gitignore index 0378fc2..216c1fc 100644 --- a/.gitignore +++ b/.gitignore @@ -19,21 +19,5 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* -.gradle/4.3.1/ -.idea -target/TabooLib-3.832-shaded.jar -target/TabooLib-3.832.jar -target/classes/JavaShells/ -target/classes/Language/ -target/classes/Language2/ -target/classes/TLM/ -target/classes/config.yml -target/classes/internalLang.yml -target/classes/items.yml -target/classes/lang/ -target/classes/module.yml -target/classes/plugin.yml -target/generated-sources/ -target/maven-archiver/ -target/maven-status/ -target/original-TabooLib-3.832.jar +/target/ +/.idea/ diff --git a/src/main/java/com/ilummc/tlib/ExampleMain.java b/src/main/java/com/ilummc/tlib/ExampleMain.java index 3544dbc..f3f1739 100644 --- a/src/main/java/com/ilummc/tlib/ExampleMain.java +++ b/src/main/java/com/ilummc/tlib/ExampleMain.java @@ -14,10 +14,11 @@ public class ExampleMain extends JavaPlugin { public void onEnable() { update.addListener(((oldVal, newVal) -> { Bukkit.getLogger().info("配置项 enableUpdate 的值由 " + oldVal + " 变为了 " + newVal); - if (newVal) + if (newVal) { Updater.start(); - else + } else { Updater.stop(); + } })); } diff --git a/src/main/java/com/ilummc/tlib/bean/Property.java b/src/main/java/com/ilummc/tlib/bean/Property.java index 29cfff7..66f3950 100644 --- a/src/main/java/com/ilummc/tlib/bean/Property.java +++ b/src/main/java/com/ilummc/tlib/bean/Property.java @@ -16,10 +16,11 @@ public class Property { public void set(T value) { if (value != this.value) { - if (consumers != null) + if (consumers != null) { for (BiConsumer consumer : consumers) { consumer.accept(this.value, value); } + } this.value = value; } } @@ -29,8 +30,9 @@ public class Property { } public void addListener(BiConsumer consumer) { - if (consumers == null) + if (consumers == null) { consumers = new ArrayList<>(); + } consumers.add(consumer); } diff --git a/src/main/java/com/ilummc/tlib/bungee/api/ChatColor.java b/src/main/java/com/ilummc/tlib/bungee/api/ChatColor.java new file mode 100644 index 0000000..752b7be --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/api/ChatColor.java @@ -0,0 +1,180 @@ +package com.ilummc.tlib.bungee.api; + +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Simplistic enumeration of all supported color values for chat. + * @author md_5 + */ +public enum ChatColor { + + /** + * Represents black. + */ + BLACK('0', "black"), + /** + * Represents dark blue. + */ + DARK_BLUE('1', "dark_blue"), + /** + * Represents dark green. + */ + DARK_GREEN('2', "dark_green"), + /** + * Represents dark blue (aqua). + */ + DARK_AQUA('3', "dark_aqua"), + /** + * Represents dark red. + */ + DARK_RED('4', "dark_red"), + /** + * Represents dark purple. + */ + DARK_PURPLE('5', "dark_purple"), + /** + * Represents gold. + */ + GOLD('6', "gold"), + /** + * Represents gray. + */ + GRAY('7', "gray"), + /** + * Represents dark gray. + */ + DARK_GRAY('8', "dark_gray"), + /** + * Represents blue. + */ + BLUE('9', "blue"), + /** + * Represents green. + */ + GREEN('a', "green"), + /** + * Represents aqua. + */ + AQUA('b', "aqua"), + /** + * Represents red. + */ + RED('c', "red"), + /** + * Represents light purple. + */ + LIGHT_PURPLE('d', "light_purple"), + /** + * Represents yellow. + */ + YELLOW('e', "yellow"), + /** + * Represents white. + */ + WHITE('f', "white"), + /** + * Represents magical characters that change around randomly. + */ + MAGIC('k', "obfuscated"), + /** + * Makes the text bold. + */ + BOLD('l', "bold"), + /** + * Makes a line appear through the text. + */ + STRIKETHROUGH('m', "strikethrough"), + /** + * Makes the text appear underlined. + */ + UNDERLINE('n', "underline"), + /** + * Makes the text italic. + */ + ITALIC('o', "italic"), + /** + * Resets all previous chat colors or formats. + */ + RESET('r', "reset"); + /** + * The special character which prefixes all chat colour codes. Use this if + * you need to dynamically convert colour codes from your custom format. + */ + public static final char COLOR_CHAR = '\u00A7'; + public static final String ALL_CODES = "0123456789AaBbCcDdEeFfKkLlMmNnOoRr"; + /** + * Pattern to remove all colour codes. + */ + public static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "[0-9A-FK-OR]"); + /** + * Colour instances keyed by their active character. + */ + private static final Map BY_CHAR = new HashMap(); + /** + * The code appended to {@link #COLOR_CHAR} to make usable colour. + */ + private final char code; + /** + * This colour's colour char prefixed by the {@link #COLOR_CHAR}. + */ + private final String toString; + + private final String name; + + public String getName() { + return name; + } + + static { + for (ChatColor colour : values()) { + BY_CHAR.put(colour.code, colour); + } + } + + ChatColor(char code, String name) { + this.code = code; + this.name = name; + this.toString = new String(new char[]{COLOR_CHAR, code}); + } + + @Override + public String toString() { + return toString; + } + + /** + * Strips the given message of all color codes + * + * @param input String to strip of color + * @return A copy of the input string, without any coloring + */ + public static String stripColor(final String input) { + if (input == null) { + return null; + } + return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); + } + + public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) { + char[] b = textToTranslate.toCharArray(); + for (int i = 0; i < b.length - 1; i++) { + if (b[i] == altColorChar && ALL_CODES.indexOf(b[i + 1]) > -1) { + b[i] = ChatColor.COLOR_CHAR; + b[i + 1] = Character.toLowerCase(b[i + 1]); + } + } + return new String(b); + } + + /** + * Get the colour represented by the specified code. + * + * @param code the code to search for + * @return the mapped colour, or null if non exists + */ + public static ChatColor getByChar(char code) { + return BY_CHAR.get(code); + } +} diff --git a/src/main/java/com/ilummc/tlib/bungee/api/ChatMessageType.java b/src/main/java/com/ilummc/tlib/bungee/api/ChatMessageType.java new file mode 100644 index 0000000..788cf5e --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/api/ChatMessageType.java @@ -0,0 +1,12 @@ +package com.ilummc.tlib.bungee.api; + +/** + * Represents the position on the screen where a message will appear. + * @author md_5 + */ +public enum ChatMessageType { + + CHAT, + SYSTEM, + ACTION_BAR +} diff --git a/src/main/java/com/ilummc/tlib/bungee/api/chat/BaseComponent.java b/src/main/java/com/ilummc/tlib/bungee/api/chat/BaseComponent.java new file mode 100644 index 0000000..493fc45 --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/api/chat/BaseComponent.java @@ -0,0 +1,493 @@ +package com.ilummc.tlib.bungee.api.chat; + +import com.ilummc.tlib.bungee.api.ChatColor; +import com.ilummc.tlib.bungee.api.chat.ComponentBuilder.FormatRetention; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author md_5 + */ +public abstract class BaseComponent { + + BaseComponent parent; + + /** + * The color of this component and any child components (unless overridden) + */ + private ChatColor color; + /** + * Whether this component and any child components (unless overridden) is + * bold + */ + private Boolean bold; + /** + * Whether this component and any child components (unless overridden) is + * italic + */ + private Boolean italic; + /** + * Whether this component and any child components (unless overridden) is + * underlined + */ + private Boolean underlined; + /** + * Whether this component and any child components (unless overridden) is + * strikethrough + */ + private Boolean strikethrough; + /** + * Whether this component and any child components (unless overridden) is + * obfuscated + */ + private Boolean obfuscated; + /** + * The text to insert into the chat when this component (and child + * components) are clicked while pressing the shift key + */ + private String insertion; + + /** + * Appended components that inherit this component's formatting and events + */ + private List extra; + + /** + * The action to perform when this component (and child components) are + * clicked + */ + private ClickEvent clickEvent; + /** + * The action to perform when this component (and child components) are + * hovered over + */ + private HoverEvent hoverEvent; + + public String getInsertion() { + return insertion; + } + + public List getExtra() { + return extra; + } + + public ClickEvent getClickEvent() { + return clickEvent; + } + + public HoverEvent getHoverEvent() { + return hoverEvent; + } + + public void setParent(BaseComponent parent) { + this.parent = parent; + } + + public void setColor(ChatColor color) { + this.color = color; + } + + public void setBold(Boolean bold) { + this.bold = bold; + } + + public void setItalic(Boolean italic) { + this.italic = italic; + } + + public void setUnderlined(Boolean underlined) { + this.underlined = underlined; + } + + public void setStrikethrough(Boolean strikethrough) { + this.strikethrough = strikethrough; + } + + public void setObfuscated(Boolean obfuscated) { + this.obfuscated = obfuscated; + } + + public void setInsertion(String insertion) { + this.insertion = insertion; + } + + public void setClickEvent(ClickEvent clickEvent) { + this.clickEvent = clickEvent; + } + + public void setHoverEvent(HoverEvent hoverEvent) { + this.hoverEvent = hoverEvent; + } + + @Override + public String toString() { + return "parent=" + "BaseComponent{" + parent + ", color=" + color + ", bold=" + bold + ", italic=" + italic + ", underlined=" + underlined + ", strikethrough=" + strikethrough + ", obfuscated=" + obfuscated + ", insertion='" + insertion + '\'' + ", extra=" + extra + ", clickEvent=" + clickEvent + ", hoverEvent=" + hoverEvent + '}'; + } + + BaseComponent() { + } + + BaseComponent(BaseComponent old) { + copyFormatting(old, FormatRetention.ALL, true); + + if (old.getExtra() != null) { + for (BaseComponent extra : old.getExtra()) { + addExtra(extra.duplicate()); + } + } + } + + /** + * Copies the events and formatting of a BaseComponent. Already set + * formatting will be replaced. + * + * @param component the component to copy from + */ + public void copyFormatting(BaseComponent component) { + copyFormatting(component, FormatRetention.ALL, true); + } + + /** + * Copies the events and formatting of a BaseComponent. + * + * @param component the component to copy from + * @param replace if already set formatting should be replaced by the new + * component + */ + public void copyFormatting(BaseComponent component, boolean replace) { + copyFormatting(component, FormatRetention.ALL, replace); + } + + /** + * Copies the specified formatting of a BaseComponent. + * + * @param component the component to copy from + * @param retention the formatting to copy + * @param replace if already set formatting should be replaced by the new + * component + */ + public void copyFormatting(BaseComponent component, FormatRetention retention, boolean replace) { + if (retention == FormatRetention.EVENTS || retention == FormatRetention.ALL) { + if (replace || clickEvent == null) { + setClickEvent(component.getClickEvent()); + } + if (replace || hoverEvent == null) { + setHoverEvent(component.getHoverEvent()); + } + } + if (retention == FormatRetention.FORMATTING || retention == FormatRetention.ALL) { + if (replace || color == null) { + setColor(component.getColorRaw()); + } + if (replace || bold == null) { + setBold(component.isBoldRaw()); + } + if (replace || italic == null) { + setItalic(component.isItalicRaw()); + } + if (replace || underlined == null) { + setUnderlined(component.isUnderlinedRaw()); + } + if (replace || strikethrough == null) { + setStrikethrough(component.isStrikethroughRaw()); + } + if (replace || obfuscated == null) { + setObfuscated(component.isObfuscatedRaw()); + } + if (replace || insertion == null) { + setInsertion(component.getInsertion()); + } + } + } + + /** + * Retains only the specified formatting. + * + * @param retention the formatting to retain + */ + public void retain(FormatRetention retention) { + if (retention == FormatRetention.FORMATTING || retention == FormatRetention.NONE) { + setClickEvent(null); + setHoverEvent(null); + } + if (retention == FormatRetention.EVENTS || retention == FormatRetention.NONE) { + setColor(null); + setBold(null); + setItalic(null); + setUnderlined(null); + setStrikethrough(null); + setObfuscated(null); + setInsertion(null); + } + } + + /** + * Clones the BaseComponent and returns the clone. + * + * @return The duplicate of this BaseComponent + */ + public abstract BaseComponent duplicate(); + + /** + * Clones the BaseComponent without formatting and returns the clone. + * + * @return The duplicate of this BaseComponent + * @deprecated API use discouraged, use traditional duplicate + */ + @Deprecated + public BaseComponent duplicateWithoutFormatting() { + BaseComponent component = duplicate(); + component.retain(FormatRetention.NONE); + return component; + } + + /** + * Converts the components to a string that uses the old formatting codes + * ({@link ChatColor#COLOR_CHAR} + * + * @param components the components to convert + * @return the string in the old format + */ + public static String toLegacyText(BaseComponent... components) { + StringBuilder builder = new StringBuilder(); + for (BaseComponent msg : components) { + builder.append(msg.toLegacyText()); + } + return builder.toString(); + } + + /** + * Converts the components into a string without any formatting + * + * @param components the components to convert + * @return the string as plain text + */ + public static String toPlainText(BaseComponent... components) { + StringBuilder builder = new StringBuilder(); + for (BaseComponent msg : components) { + builder.append(msg.toPlainText()); + } + return builder.toString(); + } + + /** + * Returns the color of this component. This uses the parent's color if this + * component doesn't have one. {@link ChatColor#WHITE} + * is returned if no color is found. + * + * @return the color of this component + */ + public ChatColor getColor() { + if (color == null) { + if (parent == null) { + return ChatColor.WHITE; + } + return parent.getColor(); + } + return color; + } + + /** + * Returns the color of this component without checking the parents color. + * May return null + * + * @return the color of this component + */ + public ChatColor getColorRaw() { + return color; + } + + /** + * Returns whether this component is bold. This uses the parent's setting if + * this component hasn't been set. false is returned if none of the parent + * chain has been set. + * + * @return whether the component is bold + */ + public boolean isBold() { + if (bold == null) { + return parent != null && parent.isBold(); + } + return bold; + } + + /** + * Returns whether this component is bold without checking the parents + * setting. May return null + * + * @return whether the component is bold + */ + public Boolean isBoldRaw() { + return bold; + } + + /** + * Returns whether this component is italic. This uses the parent's setting + * if this component hasn't been set. false is returned if none of the + * parent chain has been set. + * + * @return whether the component is italic + */ + public boolean isItalic() { + if (italic == null) { + return parent != null && parent.isItalic(); + } + return italic; + } + + /** + * Returns whether this component is italic without checking the parents + * setting. May return null + * + * @return whether the component is italic + */ + public Boolean isItalicRaw() { + return italic; + } + + /** + * Returns whether this component is underlined. This uses the parent's + * setting if this component hasn't been set. false is returned if none of + * the parent chain has been set. + * + * @return whether the component is underlined + */ + public boolean isUnderlined() { + if (underlined == null) { + return parent != null && parent.isUnderlined(); + } + return underlined; + } + + /** + * Returns whether this component is underlined without checking the parents + * setting. May return null + * + * @return whether the component is underlined + */ + public Boolean isUnderlinedRaw() { + return underlined; + } + + /** + * Returns whether this component is strikethrough. This uses the parent's + * setting if this component hasn't been set. false is returned if none of + * the parent chain has been set. + * + * @return whether the component is strikethrough + */ + public boolean isStrikethrough() { + if (strikethrough == null) { + return parent != null && parent.isStrikethrough(); + } + return strikethrough; + } + + /** + * Returns whether this component is strikethrough without checking the + * parents setting. May return null + * + * @return whether the component is strikethrough + */ + public Boolean isStrikethroughRaw() { + return strikethrough; + } + + /** + * Returns whether this component is obfuscated. This uses the parent's + * setting if this component hasn't been set. false is returned if none of + * the parent chain has been set. + * + * @return whether the component is obfuscated + */ + public boolean isObfuscated() { + if (obfuscated == null) { + return parent != null && parent.isObfuscated(); + } + return obfuscated; + } + + /** + * Returns whether this component is obfuscated without checking the parents + * setting. May return null + * + * @return whether the component is obfuscated + */ + public Boolean isObfuscatedRaw() { + return obfuscated; + } + + public void setExtra(List components) { + components.forEach(component -> component.parent = this); + extra = components; + } + + /** + * Appends a text element to the component. The text will inherit this + * component's formatting + * + * @param text the text to append + */ + public void addExtra(String text) { + addExtra(new TextComponent(text)); + } + + /** + * Appends a component to the component. The text will inherit this + * component's formatting + * + * @param component the component to append + */ + public void addExtra(BaseComponent component) { + if (extra == null) { + extra = new ArrayList<>(); + } + component.parent = this; + extra.add(component); + } + + /** + * Returns whether the component has any formatting or events applied to it + * + * @return Whether any formatting or events are applied + */ + public boolean hasFormatting() { + return color != null || italic != null || bold != null || underlined != null || strikethrough != null || obfuscated != null || insertion != null || hoverEvent != null || clickEvent != null; + } + + /** + * Converts the component into a string without any formatting + * + * @return the string as plain text + */ + public String toPlainText() { + StringBuilder builder = new StringBuilder(); + toPlainText(builder); + return builder.toString(); + } + + void toPlainText(StringBuilder builder) { + if (extra != null) { + extra.forEach(e -> e.toPlainText(builder)); + } + } + + /** + * Converts the component to a string that uses the old formatting codes + * ({@link ChatColor#COLOR_CHAR} + * + * @return the string in the old format + */ + public String toLegacyText() { + StringBuilder builder = new StringBuilder(); + toLegacyText(builder); + return builder.toString(); + } + + void toLegacyText(StringBuilder builder) { + if (extra != null) { + extra.forEach(e -> e.toLegacyText(builder)); + } + } +} diff --git a/src/main/java/com/ilummc/tlib/bungee/api/chat/ClickEvent.java b/src/main/java/com/ilummc/tlib/bungee/api/chat/ClickEvent.java new file mode 100644 index 0000000..c7124e8 --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/api/chat/ClickEvent.java @@ -0,0 +1,61 @@ +package com.ilummc.tlib.bungee.api.chat; + +/** + * @author md_5 + */ +public final class ClickEvent { + + /** + * The type of action to perform on click + */ + private final Action action; + /** + * Depends on action + * + * @see Action + */ + private final String value; + + public ClickEvent(Action action, String value) { + this.action = action; + this.value = value; + } + + public Action getAction() { + return action; + } + + public String getValue() { + return value; + } + + public enum Action { + + /** + * Open a url at the path given by + * {@link ClickEvent#value} + */ + OPEN_URL, + /** + * Open a file at the path given by + * {@link ClickEvent#value} + */ + OPEN_FILE, + /** + * Run the command given by + * {@link ClickEvent#value} + */ + RUN_COMMAND, + /** + * Inserts the string given by + * {@link ClickEvent#value} into the players + * text box + */ + SUGGEST_COMMAND, + /** + * Change to the page number given by + * {@link ClickEvent#value} in a book + */ + CHANGE_PAGE + } +} diff --git a/src/main/java/com/ilummc/tlib/bungee/api/chat/ComponentBuilder.java b/src/main/java/com/ilummc/tlib/bungee/api/chat/ComponentBuilder.java new file mode 100644 index 0000000..1b0100f --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/api/chat/ComponentBuilder.java @@ -0,0 +1,311 @@ +package com.ilummc.tlib.bungee.api.chat; + +import com.google.common.base.Preconditions; +import com.ilummc.tlib.bungee.api.ChatColor; + +import java.util.ArrayList; +import java.util.List; + +/** + *

+ * ComponentBuilder simplifies creating basic messages by allowing the use of a + * chainable builder. + *

+ *
+ * new ComponentBuilder("Hello ").color(ChatColor.RED).
+ * append("World").color(ChatColor.BLUE). append("!").bold(true).create();
+ * 
+ *

+ * All methods (excluding {@link #append(String)} and {@link #create()} work on + * the last part appended to the builder, so in the example above "Hello " would + * be {@link ChatColor#RED} and "World" would be + * {@link ChatColor#BLUE} but "!" would be bold and + * {@link ChatColor#BLUE} because append copies the previous + * part's formatting + *

+ * + * @author md_5 + */ +public final class ComponentBuilder { + + private BaseComponent current; + private final List parts = new ArrayList<>(); + + /** + * Creates a ComponentBuilder from the other given ComponentBuilder to clone + * it. + * + * @param original the original for the new ComponentBuilder. + */ + public ComponentBuilder(ComponentBuilder original) { + current = original.current.duplicate(); + original.parts.stream().map(BaseComponent::duplicate).forEach(parts::add); + } + + /** + * Creates a ComponentBuilder with the given text as the first part. + * + * @param text the first text element + */ + public ComponentBuilder(String text) { + current = new TextComponent(text); + } + + /** + * Creates a ComponentBuilder with the given component as the first part. + * + * @param component the first component element + */ + public ComponentBuilder(BaseComponent component) { + current = component.duplicate(); + } + + /** + * Appends a component to the builder and makes it the current target for + * formatting. The component will have all the formatting from previous + * part. + * + * @param component the component to append + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder append(BaseComponent component) { + return append(component, FormatRetention.ALL); + } + + /** + * Appends a component to the builder and makes it the current target for + * formatting. You can specify the amount of formatting retained from + * previous part. + * + * @param component the component to append + * @param retention the formatting to retain + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder append(BaseComponent component, FormatRetention retention) { + parts.add(current); + + BaseComponent previous = current; + current = component.duplicate(); + current.copyFormatting(previous, retention, false); + return this; + } + + /** + * Appends the components to the builder and makes the last element the + * current target for formatting. The components will have all the + * formatting from previous part. + * + * @param components the components to append + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder append(BaseComponent[] components) { + return append(components, FormatRetention.ALL); + } + + /** + * Appends the components to the builder and makes the last element the + * current target for formatting. You can specify the amount of formatting + * retained from previous part. + * + * @param components the components to append + * @param retention the formatting to retain + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder append(BaseComponent[] components, FormatRetention retention) { + Preconditions.checkArgument(components.length != 0, "No components to append"); + + BaseComponent previous = current; + for (BaseComponent component : components) { + parts.add(current); + + current = component.duplicate(); + current.copyFormatting(previous, retention, false); + } + + return this; + } + + /** + * Appends the text to the builder and makes it the current target for + * formatting. The text will have all the formatting from previous part. + * + * @param text the text to append + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder append(String text) { + return append(text, FormatRetention.ALL); + } + + /** + * Appends the text to the builder and makes it the current target for + * formatting. You can specify the amount of formatting retained from + * previous part. + * + * @param text the text to append + * @param retention the formatting to retain + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder append(String text, FormatRetention retention) { + parts.add(current); + + BaseComponent old = current; + current = new TextComponent(text); + current.copyFormatting(old, retention, false); + + return this; + } + + /** + * Sets the color of the current part. + * + * @param color the new color + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder color(ChatColor color) { + current.setColor(color); + return this; + } + + /** + * Sets whether the current part is bold. + * + * @param bold whether this part is bold + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder bold(boolean bold) { + current.setBold(bold); + return this; + } + + /** + * Sets whether the current part is italic. + * + * @param italic whether this part is italic + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder italic(boolean italic) { + current.setItalic(italic); + return this; + } + + /** + * Sets whether the current part is underlined. + * + * @param underlined whether this part is underlined + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder underlined(boolean underlined) { + current.setUnderlined(underlined); + return this; + } + + /** + * Sets whether the current part is strikethrough. + * + * @param strikethrough whether this part is strikethrough + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder strikethrough(boolean strikethrough) { + current.setStrikethrough(strikethrough); + return this; + } + + /** + * Sets whether the current part is obfuscated. + * + * @param obfuscated whether this part is obfuscated + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder obfuscated(boolean obfuscated) { + current.setObfuscated(obfuscated); + return this; + } + + /** + * Sets the insertion text for the current part. + * + * @param insertion the insertion text + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder insertion(String insertion) { + current.setInsertion(insertion); + return this; + } + + /** + * Sets the click event for the current part. + * + * @param clickEvent the click event + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder event(ClickEvent clickEvent) { + current.setClickEvent(clickEvent); + return this; + } + + /** + * Sets the hover event for the current part. + * + * @param hoverEvent the hover event + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder event(HoverEvent hoverEvent) { + current.setHoverEvent(hoverEvent); + return this; + } + + /** + * Sets the current part back to normal settings. Only text is kept. + * + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder reset() { + return retain(FormatRetention.NONE); + } + + /** + * Retains only the specified formatting. Text is not modified. + * + * @param retention the formatting to retain + * @return this ComponentBuilder for chaining + */ + public ComponentBuilder retain(FormatRetention retention) { + current.retain(retention); + return this; + } + + /** + * Returns the components needed to display the message created by this + * builder. + * + * @return the created components + */ + public BaseComponent[] create() { + BaseComponent[] result = parts.toArray(new BaseComponent[parts.size() + 1]); + result[parts.size()] = current; + return result; + } + + public enum FormatRetention { + + /** + * Specify that we do not want to retain anything from the previous + * component. + */ + NONE, + /** + * Specify that we want the formatting retained from the previous + * component. + */ + FORMATTING, + /** + * Specify that we want the events retained from the previous component. + */ + EVENTS, + /** + * Specify that we want to retain everything from the previous + * component. + */ + ALL + } +} diff --git a/src/main/java/com/ilummc/tlib/bungee/api/chat/HoverEvent.java b/src/main/java/com/ilummc/tlib/bungee/api/chat/HoverEvent.java new file mode 100644 index 0000000..1825ce4 --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/api/chat/HoverEvent.java @@ -0,0 +1,38 @@ +package com.ilummc.tlib.bungee.api.chat; + +import java.util.Arrays; + +/** + * @author md_5 + */ +public final class HoverEvent { + + private final Action action; + private final BaseComponent[] value; + + public HoverEvent(Action action, BaseComponent[] value) { + this.action = action; + this.value = value; + } + + public Action getAction() { + return action; + } + + public BaseComponent[] getValue() { + return value; + } + + @Override + public String toString() { + return "action=" + "HoverEvent{" + action + ", value=" + Arrays.toString(value) + '}'; + } + + public enum Action { + + SHOW_TEXT, + SHOW_ACHIEVEMENT, + SHOW_ITEM, + SHOW_ENTITY + } +} diff --git a/src/main/java/com/ilummc/tlib/bungee/api/chat/TextComponent.java b/src/main/java/com/ilummc/tlib/bungee/api/chat/TextComponent.java new file mode 100644 index 0000000..eadaef7 --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/api/chat/TextComponent.java @@ -0,0 +1,184 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by Fernflower decompiler) +// + +package com.ilummc.tlib.bungee.api.chat; + +import com.ilummc.tlib.bungee.api.*; + +import java.beans.ConstructorProperties; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author md_5 + */ +public class TextComponent extends BaseComponent { + + private static final Pattern url = Pattern.compile("^(?:(https?)://)?([-\\w_\\.]{2,}\\.[a-z]{2,4})(/\\S*)?$"); + private String text; + + public static BaseComponent[] fromLegacyText(String message) { + ArrayList components = new ArrayList(); + StringBuilder builder = new StringBuilder(); + TextComponent component = new TextComponent(); + Matcher matcher = url.matcher(message); + + for(int i = 0; i < message.length(); ++i) { + char c = message.charAt(i); + TextComponent old; + if (c == 167) { + ++i; + c = message.charAt(i); + if (c >= 'A' && c <= 'Z') { + c = (char)(c + 32); + } + + ChatColor format = ChatColor.getByChar(c); + if (format != null) { + if (builder.length() > 0) { + old = component; + component = new TextComponent(component); + old.setText(builder.toString()); + builder = new StringBuilder(); + components.add(old); + } + + switch(format) { + case BOLD: + component.setBold(true); + break; + case ITALIC: + component.setItalic(true); + break; + case UNDERLINE: + component.setUnderlined(true); + break; + case STRIKETHROUGH: + component.setStrikethrough(true); + break; + case MAGIC: + component.setObfuscated(true); + break; + case RESET: + format = ChatColor.WHITE; + default: + component = new TextComponent(); + component.setColor(format); + break; + } + } + } else { + int pos = message.indexOf(32, i); + if (pos == -1) { + pos = message.length(); + } + + if (matcher.region(i, pos).find()) { + if (builder.length() > 0) { + old = component; + component = new TextComponent(component); + old.setText(builder.toString()); + builder = new StringBuilder(); + components.add(old); + } + + old = component; + component = new TextComponent(component); + String urlString = message.substring(i, pos); + component.setText(urlString); + component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, urlString.startsWith("http") ? urlString : "http://" + urlString)); + components.add(component); + i += pos - i - 1; + component = old; + } else { + builder.append(c); + } + } + } + + if (builder.length() > 0) { + component.setText(builder.toString()); + components.add(component); + } + + if (components.isEmpty()) { + components.add(new TextComponent("")); + } + + return components.toArray(new BaseComponent[0]); + } + + public TextComponent() { + this.text = ""; + } + + public TextComponent(TextComponent textComponent) { + super(textComponent); + this.setText(textComponent.getText()); + } + + public TextComponent(BaseComponent... extras) { + this.setText(""); + this.setExtra(new ArrayList(Arrays.asList(extras))); + } + + @Override + public BaseComponent duplicate() { + return new TextComponent(this); + } + + @Override + protected void toPlainText(StringBuilder builder) { + builder.append(this.text); + super.toPlainText(builder); + } + + @Override + protected void toLegacyText(StringBuilder builder) { + builder.append(this.getColor()); + if (this.isBold()) { + builder.append(ChatColor.BOLD); + } + + if (this.isItalic()) { + builder.append(ChatColor.ITALIC); + } + + if (this.isUnderlined()) { + builder.append(ChatColor.UNDERLINE); + } + + if (this.isStrikethrough()) { + builder.append(ChatColor.STRIKETHROUGH); + } + + if (this.isObfuscated()) { + builder.append(ChatColor.MAGIC); + } + + builder.append(this.text); + super.toLegacyText(builder); + } + + @Override + public String toString() { + return String.format("TextComponent{text=%s, %s}", this.text, super.toString()); + } + + public String getText() { + return this.text; + } + + public void setText(String text) { + this.text = text; + } + + @ConstructorProperties({"text"}) + public TextComponent(String text) { + this.text = text; + } +} diff --git a/src/main/java/com/ilummc/tlib/bungee/api/chat/TranslatableComponent.java b/src/main/java/com/ilummc/tlib/bungee/api/chat/TranslatableComponent.java new file mode 100644 index 0000000..796b749 --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/api/chat/TranslatableComponent.java @@ -0,0 +1,242 @@ +package com.ilummc.tlib.bungee.api.chat; + +import com.ilummc.tlib.bungee.api.ChatColor; + +import java.util.ArrayList; +import java.util.List; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * @author md_5 + */ +public final class TranslatableComponent extends BaseComponent { + + private final ResourceBundle locales = ResourceBundle.getBundle("mojang-translations/en_US"); + private final Pattern format = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)"); + + /** + * The key into the Minecraft locale files to use for the translation. The + * text depends on the client's locale setting. The console is always en_US + */ + private String translate; + /** + * The components to substitute into the translation + */ + private List with; + + public ResourceBundle getLocales() { + return locales; + } + + public Pattern getFormat() { + return format; + } + + public String getTranslate() { + return translate; + } + + public void setTranslate(String translate) { + this.translate = translate; + } + + public List getWith() { + return with; + } + + public TranslatableComponent() { + } + + /** + * Creates a translatable component from the original to clone it. + * + * @param original the original for the new translatable component. + */ + public TranslatableComponent(TranslatableComponent original) { + super(original); + setTranslate(original.getTranslate()); + + if (original.getWith() != null) { + setWith(original.getWith().stream().map(BaseComponent::duplicate).collect(Collectors.toList())); + } + } + + /** + * Creates a translatable component with the passed substitutions + * + * @param translate the translation key + * @param with the {@link java.lang.String}s and + * {@link BaseComponent}s to use into the + * translation + * @see #translate + * @see #setWith(java.util.List) + */ + public TranslatableComponent(String translate, Object... with) { + setTranslate(translate); + if (with != null && with.length != 0) { + List temp = new ArrayList<>(); + for (Object w : with) { + if (w instanceof String) { + temp.add(new TextComponent((String) w)); + } else { + temp.add((BaseComponent) w); + } + } + setWith(temp); + } + } + + /** + * Creates a duplicate of this TranslatableComponent. + * + * @return the duplicate of this TranslatableComponent. + */ + @Override + public BaseComponent duplicate() { + return new TranslatableComponent(this); + } + + @Override + public String toString() { + return "locales=" + "TranslatableComponent{" + locales + ", format=" + format + ", translate='" + translate + '\'' + ", with=" + with + '}'; + } + + /** + * Sets the translation substitutions to be used in this component. Removes + * any previously set substitutions + * + * @param components the components to substitute + */ + public void setWith(List components) { + components.forEach(component -> component.parent = this); + with = components; + } + + /** + * Adds a text substitution to the component. The text will inherit this + * component's formatting + * + * @param text the text to substitute + */ + public void addWith(String text) { + addWith(new TextComponent(text)); + } + + /** + * Adds a component substitution to the component. The text will inherit + * this component's formatting + * + * @param component the component to substitute + */ + public void addWith(BaseComponent component) { + if (with == null) { + with = new ArrayList<>(); + } + component.parent = this; + with.add(component); + } + + @Override + protected void toPlainText(StringBuilder builder) { + String trans; + try { + trans = locales.getString(translate); + } catch (MissingResourceException ex) { + trans = translate; + } + + Matcher matcher = format.matcher(trans); + int position = 0; + int i = 0; + while (matcher.find(position)) { + int pos = matcher.start(); + if (pos != position) { + builder.append(trans, position, pos); + } + position = matcher.end(); + + String formatCode = matcher.group(2); + switch (formatCode.charAt(0)) { + case 's': + case 'd': + String withIndex = matcher.group(1); + with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toPlainText(builder); + break; + case '%': + builder.append('%'); + break; + default: + break; + } + } + if (trans.length() != position) { + builder.append(trans, position, trans.length()); + } + super.toPlainText(builder); + } + + @Override + protected void toLegacyText(StringBuilder builder) { + String trans; + try { + trans = locales.getString(translate); + } catch (MissingResourceException e) { + trans = translate; + } + + Matcher matcher = format.matcher(trans); + int position = 0; + int i = 0; + while (matcher.find(position)) { + int pos = matcher.start(); + if (pos != position) { + addFormat(builder); + builder.append(trans, position, pos); + } + position = matcher.end(); + + String formatCode = matcher.group(2); + switch (formatCode.charAt(0)) { + case 's': + case 'd': + String withIndex = matcher.group(1); + with.get(withIndex != null ? Integer.parseInt(withIndex) - 1 : i++).toLegacyText(builder); + break; + case '%': + addFormat(builder); + builder.append('%'); + break; + default: + break; + } + } + if (trans.length() != position) { + addFormat(builder); + builder.append(trans, position, trans.length()); + } + super.toLegacyText(builder); + } + + private void addFormat(StringBuilder builder) { + builder.append(getColor()); + if (isBold()) { + builder.append(ChatColor.BOLD); + } + if (isItalic()) { + builder.append(ChatColor.ITALIC); + } + if (isUnderlined()) { + builder.append(ChatColor.UNDERLINE); + } + if (isStrikethrough()) { + builder.append(ChatColor.STRIKETHROUGH); + } + if (isObfuscated()) { + builder.append(ChatColor.MAGIC); + } + } +} diff --git a/src/main/java/com/ilummc/tlib/bungee/chat/BaseComponentSerializer.java b/src/main/java/com/ilummc/tlib/bungee/chat/BaseComponentSerializer.java new file mode 100644 index 0000000..e01e51a --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/chat/BaseComponentSerializer.java @@ -0,0 +1,121 @@ +package com.ilummc.tlib.bungee.chat; + +import com.google.common.base.Preconditions; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; +import com.ilummc.tlib.bungee.api.ChatColor; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; +import com.ilummc.tlib.bungee.api.chat.ClickEvent; +import com.ilummc.tlib.bungee.api.chat.HoverEvent; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Locale; + +/** + * @author md_5 + */ +public class BaseComponentSerializer { + + protected void deserialize(JsonObject object, BaseComponent component, JsonDeserializationContext context) { + if (object.has("color")) { + component.setColor(ChatColor.valueOf(object.get("color").getAsString().toUpperCase(Locale.ROOT))); + } + if (object.has("bold")) { + component.setBold(object.get("bold").getAsBoolean()); + } + if (object.has("italic")) { + component.setItalic(object.get("italic").getAsBoolean()); + } + if (object.has("underlined")) { + component.setUnderlined(object.get("underlined").getAsBoolean()); + } + if (object.has("strikethrough")) { + component.setStrikethrough(object.get("strikethrough").getAsBoolean()); + } + if (object.has("obfuscated")) { + component.setObfuscated(object.get("obfuscated").getAsBoolean()); + } + if (object.has("insertion")) { + component.setInsertion(object.get("insertion").getAsString()); + } + if (object.has("extra")) { + component.setExtra(Arrays.asList(context.deserialize(object.get("extra"), BaseComponent[].class))); + } + + //Events + if (object.has("clickEvent")) { + JsonObject event = object.getAsJsonObject("clickEvent"); + component.setClickEvent(new ClickEvent( + ClickEvent.Action.valueOf(event.get("action").getAsString().toUpperCase(Locale.ROOT)), + event.get("value").getAsString())); + } + if (object.has("hoverEvent")) { + JsonObject event = object.getAsJsonObject("hoverEvent"); + BaseComponent[] res; + if (event.get("value").isJsonArray()) { + res = context.deserialize(event.get("value"), BaseComponent[].class); + } else { + res = new BaseComponent[]{context.deserialize(event.get("value"), BaseComponent.class)}; + } + component.setHoverEvent(new HoverEvent(HoverEvent.Action.valueOf(event.get("action").getAsString().toUpperCase(Locale.ROOT)), res)); + } + } + + protected void serialize(JsonObject object, BaseComponent component, JsonSerializationContext context) { + boolean first = false; + if (ComponentSerializer.serializedComponents.get() == null) { + first = true; + ComponentSerializer.serializedComponents.set(new HashSet<>()); + } + try { + Preconditions.checkArgument(!ComponentSerializer.serializedComponents.get().contains(component), "Component loop"); + ComponentSerializer.serializedComponents.get().add(component); + if (component.getColorRaw() != null) { + object.addProperty("color", component.getColorRaw().getName()); + } + if (component.isBoldRaw() != null) { + object.addProperty("bold", component.isBoldRaw()); + } + if (component.isItalicRaw() != null) { + object.addProperty("italic", component.isItalicRaw()); + } + if (component.isUnderlinedRaw() != null) { + object.addProperty("underlined", component.isUnderlinedRaw()); + } + if (component.isStrikethroughRaw() != null) { + object.addProperty("strikethrough", component.isStrikethroughRaw()); + } + if (component.isObfuscatedRaw() != null) { + object.addProperty("obfuscated", component.isObfuscatedRaw()); + } + if (component.getInsertion() != null) { + object.addProperty("insertion", component.getInsertion()); + } + + if (component.getExtra() != null) { + object.add("extra", context.serialize(component.getExtra())); + } + + //Events + if (component.getClickEvent() != null) { + JsonObject clickEvent = new JsonObject(); + clickEvent.addProperty("action", component.getClickEvent().getAction().toString().toLowerCase(Locale.ROOT)); + clickEvent.addProperty("value", component.getClickEvent().getValue()); + object.add("clickEvent", clickEvent); + } + if (component.getHoverEvent() != null) { + JsonObject hoverEvent = new JsonObject(); + hoverEvent.addProperty("action", component.getHoverEvent().getAction().toString().toLowerCase(Locale.ROOT)); + hoverEvent.add("value", context.serialize(component.getHoverEvent().getValue())); + object.add("hoverEvent", hoverEvent); + } + } finally { + ComponentSerializer.serializedComponents.get().remove(component); + if (first) { + ComponentSerializer.serializedComponents.set(null); + } + } + } +} diff --git a/src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java b/src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java new file mode 100644 index 0000000..b6165db --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java @@ -0,0 +1,58 @@ +package com.ilummc.tlib.bungee.chat; + +import com.google.gson.*; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; +import com.ilummc.tlib.bungee.api.chat.TextComponent; +import com.ilummc.tlib.bungee.api.chat.TranslatableComponent; + +import java.lang.reflect.Type; +import java.util.HashSet; + +/** + * @author md_5 + */ +public class ComponentSerializer implements JsonDeserializer { + + private final static JsonParser JSON_PARSER = new JsonParser(); + private final static Gson gson = new GsonBuilder(). + registerTypeAdapter(BaseComponent.class, new ComponentSerializer()). + registerTypeAdapter(TextComponent.class, new TextComponentSerializer()). + registerTypeAdapter(TranslatableComponent.class, new TranslatableComponentSerializer()). + create(); + + public final static ThreadLocal> serializedComponents = new ThreadLocal<>(); + + public static BaseComponent[] parse(String json) { + JsonElement jsonElement = JSON_PARSER.parse(json); + + if (jsonElement.isJsonArray()) { + return gson.fromJson(jsonElement, BaseComponent[].class); + } else { + return new BaseComponent[]{gson.fromJson(jsonElement, BaseComponent.class)}; + } + } + + public static String toString(BaseComponent component) { + return gson.toJson(component); + } + + public static String toString(BaseComponent... components) { + if (components.length == 1) { + return gson.toJson(components[0]); + } else { + return gson.toJson(new TextComponent(components)); + } + } + + @Override + public BaseComponent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + if (json.isJsonPrimitive()) { + return new TextComponent(json.getAsString()); + } + JsonObject object = json.getAsJsonObject(); + if (object.has("translate")) { + return context.deserialize(json, TranslatableComponent.class); + } + return context.deserialize(json, TextComponent.class); + } +} diff --git a/src/main/java/com/ilummc/tlib/bungee/chat/TextComponentSerializer.java b/src/main/java/com/ilummc/tlib/bungee/chat/TextComponentSerializer.java new file mode 100644 index 0000000..bd9b53f --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/chat/TextComponentSerializer.java @@ -0,0 +1,47 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by Fernflower decompiler) +// + +package com.ilummc.tlib.bungee.chat; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.ilummc.tlib.bungee.api.chat.*; + +import java.lang.reflect.Type; +import java.util.List; + +/** + * @author md_5 + */ +public class TextComponentSerializer extends BaseComponentSerializer implements JsonSerializer, JsonDeserializer { + + public TextComponentSerializer() { + } + + @Override + public TextComponent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + TextComponent component = new TextComponent(); + JsonObject object = json.getAsJsonObject(); + this.deserialize(object, component, context); + component.setText(object.get("text").getAsString()); + return component; + } + + @Override + public JsonElement serialize(TextComponent src, Type typeOfSrc, JsonSerializationContext context) { + List extra = src.getExtra(); + JsonObject object = new JsonObject(); + if (src.hasFormatting() || extra != null && !extra.isEmpty()) { + this.serialize(object, src, context); + } + object.addProperty("text", src.getText()); + return object; + } +} diff --git a/src/main/java/com/ilummc/tlib/bungee/chat/TranslatableComponentSerializer.java b/src/main/java/com/ilummc/tlib/bungee/chat/TranslatableComponentSerializer.java new file mode 100644 index 0000000..e2be31f --- /dev/null +++ b/src/main/java/com/ilummc/tlib/bungee/chat/TranslatableComponentSerializer.java @@ -0,0 +1,46 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by Fernflower decompiler) +// + +package com.ilummc.tlib.bungee.chat; + +import com.google.gson.*; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; +import com.ilummc.tlib.bungee.api.chat.TranslatableComponent; + +import java.lang.reflect.Type; +import java.util.Arrays; + +/** + * @author md_5 + */ +public class TranslatableComponentSerializer extends BaseComponentSerializer implements JsonSerializer, JsonDeserializer { + + public TranslatableComponentSerializer() { + } + + @Override + public TranslatableComponent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + TranslatableComponent component = new TranslatableComponent(); + JsonObject object = json.getAsJsonObject(); + this.deserialize(object, component, context); + component.setTranslate(object.get("translate").getAsString()); + if (object.has("with")) { + component.setWith(Arrays.asList((BaseComponent[]) context.deserialize(object.get("with"), BaseComponent[].class))); + } + + return component; + } + + @Override + public JsonElement serialize(TranslatableComponent src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject object = new JsonObject(); + this.serialize(object, src, context); + object.addProperty("translate", src.getTranslate()); + if (src.getWith() != null) { + object.add("with", context.serialize(src.getWith())); + } + return object; + } +} diff --git a/src/main/java/com/ilummc/tlib/compat/PlaceholderHook.java b/src/main/java/com/ilummc/tlib/compat/PlaceholderHook.java index 520044e..e5ee889 100644 --- a/src/main/java/com/ilummc/tlib/compat/PlaceholderHook.java +++ b/src/main/java/com/ilummc/tlib/compat/PlaceholderHook.java @@ -11,9 +11,11 @@ public abstract class PlaceholderHook { private static PlaceholderHook impl; public static void init() { - if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) + if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { impl = new PlaceholderImpl(); - else impl = new AbstractImpl(); + } else { + impl = new AbstractImpl(); + } } public static String replace(CommandSender sender, String text) { diff --git a/src/main/java/com/ilummc/tlib/db/Pool.java b/src/main/java/com/ilummc/tlib/db/Pool.java index af32b0a..82ccbfc 100644 --- a/src/main/java/com/ilummc/tlib/db/Pool.java +++ b/src/main/java/com/ilummc/tlib/db/Pool.java @@ -55,7 +55,9 @@ public final class Pool extends ThreadPoolExecutor { @Override protected void afterExecute(Runnable r, Throwable t) { - if (t != null) Base.close(); + if (t != null) { + Base.close(); + } } } diff --git a/src/main/java/com/ilummc/tlib/filter/TLoggerFilter.java b/src/main/java/com/ilummc/tlib/filter/TLoggerFilter.java index a3db470..140347a 100644 --- a/src/main/java/com/ilummc/tlib/filter/TLoggerFilter.java +++ b/src/main/java/com/ilummc/tlib/filter/TLoggerFilter.java @@ -1,11 +1,11 @@ package com.ilummc.tlib.filter; +import org.bukkit.Bukkit; + import java.util.Arrays; import java.util.logging.Filter; import java.util.logging.LogRecord; -import org.bukkit.Bukkit; - /** * @author Bkm016 * @since 2018-04-22 @@ -27,6 +27,9 @@ public class TLoggerFilter implements Filter { } return false; } + else if (e.getMessage().contains("Enabled plugin with unregistered PluginClassLoader")) { + return false; + } return true; } } diff --git a/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java b/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java index 624d2a7..d7f788d 100644 --- a/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java +++ b/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java @@ -55,10 +55,17 @@ public class TConfigInjector { TConfig config = clazz.getAnnotation(TConfig.class); Validate.notNull(config); File file = new File(plugin.getDataFolder(), config.name()); - if (!file.exists()) if (config.fromJar()) plugin.saveResource(config.name(), true); - else saveConfig(plugin, clazz.newInstance()); + if (!file.exists()) { + if (config.fromJar()) { + plugin.saveResource(config.name(), true); + } else { + saveConfig(plugin, clazz.newInstance()); + } + } Object obj = unserialize(plugin, clazz); - if (config.readOnly()) saveConfig(plugin, obj); + if (config.readOnly()) { + saveConfig(plugin, obj); + } return obj; } catch (NullPointerException e) { TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), clazz.getSimpleName()); @@ -75,7 +82,9 @@ public class TConfigInjector { File file = new File(plugin.getDataFolder(), config.name()); Map map = ConfigUtils.confToMap(ConfigUtils.loadYaml(plugin, file)); Object obj = ConfigUtils.mapToObj(map, object); - if (config.readOnly()) saveConfig(plugin, obj); + if (config.readOnly()) { + saveConfig(plugin, obj); + } } catch (NullPointerException e) { TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName()); } catch (Exception e) { @@ -124,7 +133,9 @@ public class TConfigInjector { Map map = gson.fromJson(gson.toJson(object), HashMap.class); YamlConfiguration configuration = (YamlConfiguration) ConfigUtils.mapToConf(map); File target = new File(plugin.getDataFolder(), config.name()); - if (!target.exists()) target.createNewFile(); + if (!target.exists()) { + target.createNewFile(); + } byte[] arr = configuration.saveToString().getBytes(config.charset()); Files.write(arr, target); } diff --git a/src/main/java/com/ilummc/tlib/inject/TConfigWatcher.java b/src/main/java/com/ilummc/tlib/inject/TConfigWatcher.java index faab770..f364ada 100644 --- a/src/main/java/com/ilummc/tlib/inject/TConfigWatcher.java +++ b/src/main/java/com/ilummc/tlib/inject/TConfigWatcher.java @@ -1,5 +1,6 @@ package com.ilummc.tlib.inject; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.commons.lang3.tuple.Triple; import java.io.File; @@ -10,12 +11,16 @@ import java.util.Map; import java.util.Objects; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; +/** + * @author lzzelAliz + */ public class TConfigWatcher { - private final ScheduledExecutorService service = Executors.newScheduledThreadPool(1); + private final ScheduledExecutorService service = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("tconfig-watcher-schedule-pool-%d").daemon(true).build()); private final Map>> map = new HashMap<>(); @@ -24,8 +29,9 @@ public class TConfigWatcher { WatchKey key; while ((key = service.poll()) != null) { for (WatchEvent watchEvent : key.pollEvents()) { - if (triple.getLeft().getName().equals(Objects.toString(watchEvent.context()))) + if (triple.getLeft().getName().equals(Objects.toString(watchEvent.context()))) { triple.getRight().accept(triple.getMiddle()); + } } key.reset(); } diff --git a/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java b/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java index ea6fc35..def8e07 100644 --- a/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java +++ b/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java @@ -96,8 +96,9 @@ public class TDependencyInjector { if ((logger = field.getAnnotation(Logger.class)) != null) { field.getType().asSubclass(com.ilummc.tlib.logger.TLogger.class); com.ilummc.tlib.logger.TLogger tLogger = new com.ilummc.tlib.logger.TLogger(logger.value(), plugin, logger.level()); - if (!field.isAccessible()) + if (!field.isAccessible()) { field.setAccessible(true); + } field.set(o, tLogger); TLoggerManager.setDefaultLogger(plugin, tLogger); } @@ -111,8 +112,9 @@ public class TDependencyInjector { try { PluginInstance instance; if ((instance = field.getAnnotation(PluginInstance.class)) != null) { - if (!field.isAccessible()) + if (!field.isAccessible()) { field.setAccessible(true); + } field.getType().asSubclass(JavaPlugin.class); Plugin pl; if ((pl = Bukkit.getPluginManager().getPlugin(instance.value())) == null) { @@ -123,8 +125,9 @@ public class TDependencyInjector { pl = Bukkit.getPluginManager().getPlugin(instance.value()); } } - if (pl != null) + if (pl != null) { field.set(o, pl); + } } } catch (Exception ignored) { } diff --git a/src/main/java/com/ilummc/tlib/inject/TPluginManager.java b/src/main/java/com/ilummc/tlib/inject/TPluginManager.java index bb1aa46..67832c5 100644 --- a/src/main/java/com/ilummc/tlib/inject/TPluginManager.java +++ b/src/main/java/com/ilummc/tlib/inject/TPluginManager.java @@ -104,7 +104,9 @@ public class TPluginManager implements PluginManager { @Override public void disablePlugins() { for (Plugin plugin : getPlugins()) { - if (plugin != main) disablePlugin(plugin); + if (plugin != main) { + disablePlugin(plugin); + } } disablePlugin(main); } diff --git a/src/main/java/com/ilummc/tlib/logger/TLogger.java b/src/main/java/com/ilummc/tlib/logger/TLogger.java index dd07bd4..0feee53 100644 --- a/src/main/java/com/ilummc/tlib/logger/TLogger.java +++ b/src/main/java/com/ilummc/tlib/logger/TLogger.java @@ -42,38 +42,45 @@ public class TLogger { } public void verbose(String msg) { - if (level <= VERBOSE) + if (level <= VERBOSE) { Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§f全部", ChatColor.translateAlternateColorCodes('&', msg))); + } } public void finest(String msg) { - if (level <= FINEST) + if (level <= FINEST) { Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§e良好", ChatColor.translateAlternateColorCodes('&', msg))); + } } public void fine(String msg) { - if (level <= FINE) + if (level <= FINE) { Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§a正常", ChatColor.translateAlternateColorCodes('&', msg))); + } } public void info(String msg) { - if (level <= INFO) + if (level <= INFO) { Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§b信息", ChatColor.translateAlternateColorCodes('&', msg))); + } } public void warn(String msg) { - if (level <= WARN) + if (level <= WARN) { Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§6警告", "§6" + ChatColor.translateAlternateColorCodes('&', msg))); + } } public void error(String msg) { - if (level <= ERROR) + if (level <= ERROR) { Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§c错误", "§c" + ChatColor.translateAlternateColorCodes('&', msg))); + } } public void fatal(String msg) { - if (level <= FATAL) + if (level <= FATAL) { Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§4致命错误", "§4" + ChatColor.translateAlternateColorCodes('&', msg))); + } } public static TLogger getUnformatted(Plugin plugin) { diff --git a/src/main/java/com/ilummc/tlib/resources/TLocale.java b/src/main/java/com/ilummc/tlib/resources/TLocale.java index daee4af..982671e 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocale.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocale.java @@ -47,8 +47,8 @@ public class TLocale { try { return asString(path, Ref.getCallerClassNotOptional(3), args); } catch (Exception e) { - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("FETCH-LOCALE-ERROR"), path)); - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.getMessage())); + TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("FETCH-LOCALE-ERROR"), path)); + TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.getMessage())); return "§4<" + path + "§4>"; } } @@ -57,8 +57,8 @@ public class TLocale { try { return asStringList(path, Ref.getCallerClassNotOptional(3), args); } catch (Exception e) { - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("FETCH-LOCALE-ERROR"), path)); - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.getMessage())); + TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("FETCH-LOCALE-ERROR"), path)); + TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.getMessage())); return Collections.singletonList("§4<" + path + "§4>"); } } diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java b/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java index 0258710..010dc14 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java @@ -62,8 +62,8 @@ class TLocaleInstance { } }); } catch (Exception | Error e) { - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("SEND-LOCALE-ERROR"), path)); - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.toString())); + TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("SEND-LOCALE-ERROR"), path)); + TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.toString())); e.printStackTrace(); } } diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java index 704b982..44822a0 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java @@ -37,10 +37,12 @@ public class TLocaleLoader { } public static void sendTo(Plugin plugin, String path, CommandSender sender, String... args) { - if (Bukkit.isPrimaryThread()) - Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args)); - else synchronized (TLocaleLoader.class) { + if (Bukkit.isPrimaryThread()) { Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args)); + } else { + synchronized (TLocaleLoader.class) { + Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args)); + } } } diff --git a/src/main/java/com/ilummc/tlib/resources/type/TLocaleActionBar.java b/src/main/java/com/ilummc/tlib/resources/type/TLocaleActionBar.java index 1f7965b..1a0f255 100644 --- a/src/main/java/com/ilummc/tlib/resources/type/TLocaleActionBar.java +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleActionBar.java @@ -35,8 +35,9 @@ public class TLocaleActionBar implements TLocaleSendable, ConfigurationSerializa @Override public void sendTo(CommandSender sender, String... args) { - if (sender instanceof Player) + if (sender instanceof Player) { ActionBar.sendActionBar(((Player) sender), replace(sender, text, args)); + } } private String replace(CommandSender sender, String text, String[] args) { diff --git a/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java b/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java index fcde732..f4632b9 100644 --- a/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java @@ -4,13 +4,13 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.ilummc.tlib.TLib; +import com.ilummc.tlib.bungee.api.chat.*; +import com.ilummc.tlib.bungee.chat.ComponentSerializer; import com.ilummc.tlib.compat.PlaceholderHook; import com.ilummc.tlib.resources.TLocaleSendable; import com.ilummc.tlib.util.Strings; import me.skymc.taboolib.Main; import me.skymc.taboolib.jsonformatter.JSONFormatter; -import net.md_5.bungee.api.chat.*; -import net.md_5.bungee.chat.ComponentSerializer; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.ConfigurationSerializable; @@ -52,7 +52,9 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable { List builder = template.length > index ? new ArrayList<>(Arrays.asList(TextComponent.fromLegacyText(template[index++]))) : new ArrayList<>(); while (matcher.find()) { String replace = matcher.group(); - if (replace.length() <= 2) continue; + if (replace.length() <= 2) { + continue; + } replace = replace.substring(1, replace.length() - 1); String[] split = replace.split("@"); String text = split.length > 1 ? split[0] : ""; @@ -73,7 +75,7 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable { builder.addAll(Arrays.asList(component)); } else { builder.addAll(Arrays.asList(TextComponent.fromLegacyText(text))); - TLib.getTLib().getLogger().warn(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("MISSING-ARGUMENT"), node)); + TLib.getTLib().getLogger().warn(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("MISSING-ARGUMENT"), node)); } if (index < template.length) { builder.addAll(Arrays.asList(TextComponent.fromLegacyText(template[index++]))); diff --git a/src/main/java/com/ilummc/tlib/util/Ref.java b/src/main/java/com/ilummc/tlib/util/Ref.java index 2b68dc8..866cdfc 100644 --- a/src/main/java/com/ilummc/tlib/util/Ref.java +++ b/src/main/java/com/ilummc/tlib/util/Ref.java @@ -37,11 +37,14 @@ public class Ref { try { // 特殊判断 - if (clazz == TLib.class) + if (clazz == TLib.class) { return Arrays.asList(clazz.getDeclaredFields()); + } List fields; - if ((fields = cachedFields.get(clazz.getName())) != null) return fields; + if ((fields = cachedFields.get(clazz.getName())) != null) { + return fields; + } ClassReader classReader = new ClassReader(clazz.getResourceAsStream("/" + clazz.getName().replace('.', '/') + ".class")); AsmAnalyser analyser = new AsmAnalyser(new ClassWriter(ClassWriter.COMPUTE_MAXS), excludeModifiers); classReader.accept(analyser, ClassReader.SKIP_DEBUG); @@ -52,7 +55,9 @@ public class Ref { return null; } }).filter(Objects::nonNull).collect(Collectors.toList()); - if (cache) cachedFields.putIfAbsent(clazz.getName(), fields); + if (cache) { + cachedFields.putIfAbsent(clazz.getName(), fields); + } return fields; } catch (Exception | Error e) { try { @@ -80,9 +85,13 @@ public class Ref { public static Optional getFieldBySerializedName(Class clazz, String name) { for (Field field : Ref.getDeclaredFields(clazz, 0, false)) { - if (field.isAnnotationPresent(SerializedName.class)) - if (field.getAnnotation(SerializedName.class).value().equals(name)) return Optional.of(field); - else if (field.getName().equals(name)) return Optional.of(field); + if (field.isAnnotationPresent(SerializedName.class)) { + if (field.getAnnotation(SerializedName.class).value().equals(name)) { + return Optional.of(field); + } else if (field.getName().equals(name)) { + return Optional.of(field); + } + } } return Optional.empty(); } diff --git a/src/main/java/com/ilummc/tlib/util/Strings.java b/src/main/java/com/ilummc/tlib/util/Strings.java index 95fe02a..4aff5d5 100644 --- a/src/main/java/com/ilummc/tlib/util/Strings.java +++ b/src/main/java/com/ilummc/tlib/util/Strings.java @@ -9,8 +9,10 @@ public class Strings { * @param args 替换的参数 * @return 替换好的字符串 */ - public static String replaceWithOrder(String template, String... args) { - if (args.length == 0 || template.length() == 0) return template; + public static String replaceWithOrder(String template, Object... args) { + if (args.length == 0 || template.length() == 0) { + return template; + } char[] arr = template.toCharArray(); StringBuilder stringBuilder = new StringBuilder(template.length()); for (int i = 0; i < arr.length; i++) { @@ -19,8 +21,9 @@ public class Strings { && arr[Math.min(i + 2, arr.length - 1)] == '}') { stringBuilder.append(args[arr[i + 1] - '0']); i += 2; - } else + } else { stringBuilder.append(arr[i]); + } } return stringBuilder.toString(); } diff --git a/src/main/java/com/ilummc/tlib/util/asm/AsmAnalyser.java b/src/main/java/com/ilummc/tlib/util/asm/AsmAnalyser.java index 9a42734..2cb58b8 100644 --- a/src/main/java/com/ilummc/tlib/util/asm/AsmAnalyser.java +++ b/src/main/java/com/ilummc/tlib/util/asm/AsmAnalyser.java @@ -20,8 +20,9 @@ public class AsmAnalyser extends ClassVisitor implements Opcodes { @Override public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) { - if ((access & excludeModifier) == 0) + if ((access & excludeModifier) == 0) { fields.add(name); + } return super.visitField(access, name, descriptor, signature, value); } diff --git a/src/main/java/com/ilummc/tlib/util/asm/AsmClassTransformer.java b/src/main/java/com/ilummc/tlib/util/asm/AsmClassTransformer.java index 1c5f3a0..fcb98b9 100644 --- a/src/main/java/com/ilummc/tlib/util/asm/AsmClassTransformer.java +++ b/src/main/java/com/ilummc/tlib/util/asm/AsmClassTransformer.java @@ -68,11 +68,13 @@ public class AsmClassTransformer extends ClassVisitor implements Opcodes { } private String replace(String text) { - if (text != null) + if (text != null) { return text.replace("net/minecraft/server/" + fromVer, "net/minecraft/server/" + toVer) .replace("org/bukkit/craftbukkit/" + fromVer, "org/bukkit/craftbukkit/" + toVer) .replace(prevName, newClassName.replace('.', '/')); - else return null; + } else { + return null; + } } private String[] replace(String[] text) { @@ -81,7 +83,9 @@ public class AsmClassTransformer extends ClassVisitor implements Opcodes { text[i] = replace(text[i]); } return text; - } else return null; + } else { + return null; + } } @Override @@ -103,9 +107,11 @@ public class AsmClassTransformer extends ClassVisitor implements Opcodes { @Override public void visitLdcInsn(Object value) { - if (value instanceof String) + if (value instanceof String) { super.visitLdcInsn(replace((String) value)); - else super.visitLdcInsn(value); + } else { + super.visitLdcInsn(value); + } } @Override diff --git a/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java b/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java index 584856d..ca86796 100644 --- a/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java +++ b/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java @@ -88,7 +88,7 @@ public class AnvilContainerAPI implements Listener { @EventHandler public void example(PlayerCommandPreprocessEvent e) { - if (e.getMessage().equals("/anvilexample")) { + if ("/anvilexample".equals(e.getMessage())) { if (e.getPlayer().hasPermission("taboolib.admin")) { e.setCancelled(true); AnvilContainerAPI.send(e.getPlayer(), "EXAMPLE", "在这里输入文本", null); @@ -98,7 +98,7 @@ public class AnvilContainerAPI implements Listener { @EventHandler public void example2(AnvilContainerAPIEvent e) { - if (e.type.equals("EXAMPLE")) { + if ("EXAMPLE".equals(e.type)) { e.event.getWhoClicked().sendMessage(e.string); } } diff --git a/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java b/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java index acdcff2..ee2b4a2 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java @@ -19,6 +19,7 @@ import java.util.regex.Pattern; /** * The NMS helper for all the Book-API */ +@SuppressWarnings({"ALL", "AliControlFlowStatementWithoutBraces"}) public final class BookReflection { private static final String version; @@ -66,8 +67,10 @@ public final class BookReflection { craftMetaBookField = craftMetaBookClass.getDeclaredField("pages"); craftMetaBookField.setAccessible(true); Class chatSerializer = getNmsClass("IChatBaseComponent$ChatSerializer", false); - if (chatSerializer == null) + //noinspection AliControlFlowStatementWithoutBraces + if (chatSerializer == null) { chatSerializer = getNmsClass("ChatSerializer"); + } chatSerializerA = chatSerializer.getDeclaredMethod("a", String.class); @@ -281,12 +284,15 @@ public final class BookReflection { return craftItemStackAsNMSCopy.invoke(null, item); } + @SuppressWarnings("AliControlFlowStatementWithoutBraces") public static Class getNmsClass(String className, boolean log) { try { return Class.forName("net.minecraft.server." + version + "." + className); } catch (ClassNotFoundException e) { - if (log) + //noinspection AliControlFlowStatementWithoutBraces + if (log) { e.printStackTrace(); + } return null; } } diff --git a/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java b/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java index 5851a0b..bc86bef 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java @@ -50,10 +50,11 @@ public interface ClickAction { * @return a new ClickAction */ static ClickAction openUrl(String url) { - if (url.startsWith("http://") || url.startsWith("https://")) + if (url.startsWith("http://") || url.startsWith("https://")) { return new SimpleClickAction(ClickEvent.Action.OPEN_URL, url); - else + } else { throw new IllegalArgumentException("Invalid url: \"" + url + "\", it should start with http:// or https://"); + } } /** diff --git a/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java b/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java index 7411fc2..cf0861b 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java @@ -107,8 +107,9 @@ public class PageBuilder { */ public static PageBuilder of(BaseComponent... text) { PageBuilder res = new PageBuilder(); - for(BaseComponent b : text) + for(BaseComponent b : text) { res.add(b); + } return res; } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/bstats/Metrics.java b/src/main/java/me/skymc/taboolib/bstats/Metrics.java index cb2f721..da4da6a 100644 --- a/src/main/java/me/skymc/taboolib/bstats/Metrics.java +++ b/src/main/java/me/skymc/taboolib/bstats/Metrics.java @@ -1,25 +1,6 @@ package me.skymc.taboolib.bstats; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.concurrent.Callable; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -import javax.net.ssl.HttpsURLConnection; - +import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; @@ -29,16 +10,29 @@ import org.bukkit.plugin.java.JavaPlugin; import org.json.simple.JSONArray; import org.json.simple.JSONObject; +import javax.net.ssl.HttpsURLConnection; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.util.*; +import java.util.concurrent.*; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + /** * bStats collects some data for plugin authors. - * + *

* Check out https://bStats.org/ to learn more about bStats! */ public class Metrics { static { // You can use the property to disable the check in your test environment - if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { + if (System.getProperty("bstats.relocatecheck") == null || !"false".equals(System.getProperty("bstats.relocatecheck"))) { // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D final String defaultPackage = new String( new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); @@ -50,22 +44,34 @@ public class Metrics { } } - // The version of this bStats class + /** + * The version of this bStats class + */ public static final int B_STATS_VERSION = 1; - // The url to which the data is sent + /** + * The url to which the data is sent + */ private static final String URL = "https://bStats.org/submitData/bukkit"; - // Should failed requests be logged? + /** + * Should failed requests be logged? + */ private static boolean logFailedRequests; - // The uuid of the server + /** + * The uuid of the server + */ private static String serverUUID; - // The plugin + /** + * The plugin + */ private final JavaPlugin plugin; - // A list with all custom charts + /** + * A list with all custom charts + */ private final List charts = new ArrayList<>(); /** @@ -103,7 +109,8 @@ public class Metrics { ).copyDefaults(true); try { config.save(configFile); - } catch (IOException ignored) { } + } catch (IOException ignored) { + } } // Load the data @@ -114,10 +121,13 @@ public class Metrics { // Search for all other bStats Metrics classes to see if we are the first one for (Class service : Bukkit.getServicesManager().getKnownServices()) { try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first + // Our identifier :) + service.getField("B_STATS_VERSION"); + // We aren't the first + found = true; break; - } catch (NoSuchFieldException ignored) { } + } catch (NoSuchFieldException ignored) { + } } // Register our service Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); @@ -144,22 +154,23 @@ public class Metrics { * Starts the Scheduler which submits our data every 30 minutes. */ private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, () -> submitData()); + ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("metrics-schedule-pool-%d").daemon(true).build()); + executorService.scheduleAtFixedRate(() -> { + if (!plugin.isEnabled()) { + executorService.shutdown(); + return; } - }, 1000*60*5, 1000*60*30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! - // WARNING: Just don't do it! + /* + * Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + * Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + */ + Bukkit.getScheduler().runTask(plugin, this::submitData); + /* + * Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + * WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + * WARNING: Just don't do it! + */ + }, 5, 30, TimeUnit.MINUTES); } /** @@ -174,13 +185,16 @@ public class Metrics { String pluginName = plugin.getDescription().getName(); String pluginVersion = plugin.getDescription().getVersion(); - data.put("pluginName", pluginName); // Append the name of the plugin - data.put("pluginVersion", pluginVersion); // Append the version of the plugin + // Append the name of the plugin + data.put("pluginName", pluginName); + // Append the version of the plugin + data.put("pluginVersion", pluginVersion); JSONArray customCharts = new JSONArray(); for (CustomChart customChart : charts) { // Add the data of the custom charts JSONObject chart = customChart.getRequestJsonObject(); - if (chart == null) { // If the chart is null, we skip it + // If the chart is null, we skip it + if (chart == null) { continue; } customCharts.add(chart); @@ -206,7 +220,8 @@ public class Metrics { ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; } catch (Exception e) { - playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed + // Just use the new method if the Reflection failed + playerAmount = Bukkit.getOnlinePlayers().size(); } int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; String bukkitVersion = org.bukkit.Bukkit.getVersion(); @@ -246,20 +261,23 @@ public class Metrics { // Search for all other bStats Metrics classes to get their plugin data for (Class service : Bukkit.getServicesManager().getKnownServices()) { try { - service.getField("B_STATS_VERSION"); // Our identifier :) + // Our identifier :) + service.getField("B_STATS_VERSION"); for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { try { pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider())); - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } } - } catch (NoSuchFieldException ignored) { } + } catch (NoSuchFieldException ignored) { + } } data.put("plugins", pluginData); // Create a new thread for the connection to the bStats server - new Thread(() -> { + Executors.newSingleThreadExecutor().execute(() -> { try { // Send the data sendData(data); @@ -269,7 +287,7 @@ public class Metrics { plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); } } - }).start(); + }); } /** @@ -294,9 +312,11 @@ public class Metrics { connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + // We gzip our request + connection.addRequestProperty("Content-Encoding", "gzip"); connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + // We send our data in JSON format + connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); // Send data @@ -306,7 +326,8 @@ public class Metrics { outputStream.flush(); outputStream.close(); - connection.getInputStream().close(); // We don't care about the response - Just send our data :) + // We don't care about the response - Just send our data :) + connection.getInputStream().close(); } /** @@ -332,7 +353,9 @@ public class Metrics { */ public static abstract class CustomChart { - // The id of the chart + /** + * The id of the chart + */ final String chartId; /** @@ -380,7 +403,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SimplePie(String chartId, Callable callable) { @@ -411,7 +434,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public AdvancedPie(String chartId, Callable> callable) { @@ -455,7 +478,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public DrilldownPie(String chartId, Callable>> callable) { @@ -504,7 +527,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SingleLineChart(String chartId, Callable callable) { @@ -536,7 +559,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public MultiLineChart(String chartId, Callable> callable) { @@ -581,7 +604,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SimpleBarChart(String chartId, Callable> callable) { @@ -619,7 +642,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public AdvancedBarChart(String chartId, Callable> callable) { diff --git a/src/main/java/me/skymc/taboolib/commands/MainCommands.java b/src/main/java/me/skymc/taboolib/commands/MainCommands.java index 460c080..dc9b0e8 100644 --- a/src/main/java/me/skymc/taboolib/commands/MainCommands.java +++ b/src/main/java/me/skymc/taboolib/commands/MainCommands.java @@ -17,45 +17,45 @@ public class MainCommands implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (args.length == 0 || args[0].equalsIgnoreCase("help")) { + if (args.length == 0 || "help".equalsIgnoreCase(args[0])) { TLocale.sendTo(sender, "COMMANDS.TABOOLIB.HELP", label); - } else if (args[0].equalsIgnoreCase("save")) { + } else if ("save".equalsIgnoreCase(args[0])) { new SaveCommand(sender, args); - } else if (args[0].equalsIgnoreCase("enchants")) { + } else if ("enchants".equalsIgnoreCase(args[0])) { new EnchantCommand(sender, args); - } else if (args[0].equalsIgnoreCase("potions")) { + } else if ("potions".equalsIgnoreCase(args[0])) { new PotionCommand(sender, args); - } else if (args[0].equalsIgnoreCase("flags")) { + } else if ("flags".equalsIgnoreCase(args[0])) { new FlagCommand(sender, args); - } else if (args[0].equalsIgnoreCase("attributes")) { + } else if ("attributes".equalsIgnoreCase(args[0])) { new AttributesCommand(sender, args); - } else if (args[0].equalsIgnoreCase("slots")) { + } else if ("slots".equalsIgnoreCase(args[0])) { new SlotCommand(sender, args); - } else if (args[0].equalsIgnoreCase("importdata")) { + } else if ("importdata".equalsIgnoreCase(args[0])) { new ImportCommand(sender, args); - } else if (args[0].equalsIgnoreCase("iteminfo")) { + } else if ("iteminfo".equalsIgnoreCase(args[0])) { new InfoCommand(sender, args); - } else if (args[0].equalsIgnoreCase("itemlist")) { + } else if ("itemlist".equalsIgnoreCase(args[0])) { new ItemListCommand(sender, args); - } else if (args[0].equalsIgnoreCase("item") || args[0].equalsIgnoreCase("i")) { + } else if ("item".equalsIgnoreCase(args[0]) || "i".equalsIgnoreCase(args[0])) { new ItemCommand(sender, args); - } else if (args[0].equalsIgnoreCase("setvariable")) { + } else if ("setvariable".equalsIgnoreCase(args[0])) { new VariableSetCommand(sender, args); - } else if (args[0].equalsIgnoreCase("getvariable")) { + } else if ("getvariable".equalsIgnoreCase(args[0])) { new VariableGetCommand(sender, args); - } else if (args[0].equalsIgnoreCase("shell") || args[0].equalsIgnoreCase("s")) { + } else if ("shell".equalsIgnoreCase(args[0]) || "s".equalsIgnoreCase(args[0])) { new ShellCommand(sender, args); - } else if (args[0].equalsIgnoreCase("cycle") || args[0].equalsIgnoreCase("c")) { + } else if ("cycle".equalsIgnoreCase(args[0]) || "c".equalsIgnoreCase(args[0])) { new CycleCommand(sender, args); - } else if (args[0].equalsIgnoreCase("sounds")) { + } else if ("sounds".equalsIgnoreCase(args[0])) { new SoundsCommand(sender, args); - } else if (args[0].equalsIgnoreCase("tagprefix")) { + } else if ("tagprefix".equalsIgnoreCase(args[0])) { new TagPrefixCommand(sender, args); - } else if (args[0].equalsIgnoreCase("tagsuffix")) { + } else if ("tagsuffix".equalsIgnoreCase(args[0])) { new TagSuffixCommand(sender, args); - } else if (args[0].equalsIgnoreCase("tagdelete")) { + } else if ("tagdelete".equalsIgnoreCase(args[0])) { new TagDeleteCommand(sender, args); - } else if (args[0].equalsIgnoreCase("itemreload") || args[0].equalsIgnoreCase("ireload")) { + } else if ("itemreload".equalsIgnoreCase(args[0]) || "ireload".equalsIgnoreCase(args[0])) { ItemUtils.reloadItemCache(); ItemUtils.reloadItemName(); TLocale.sendTo(sender, "COMMANDS.RELOAD.SUCCESS-NORMAL"); diff --git a/src/main/java/me/skymc/taboolib/commands/internal/InternalArgument.java b/src/main/java/me/skymc/taboolib/commands/internal/InternalArgument.java index c1ba9d2..d03869b 100644 --- a/src/main/java/me/skymc/taboolib/commands/internal/InternalArgument.java +++ b/src/main/java/me/skymc/taboolib/commands/internal/InternalArgument.java @@ -22,6 +22,7 @@ public class InternalArgument { this.required = required; } + @Override public String toString() { return required ? "§7[§8" + name + "§7]" : "§7<§8" + name + "§7>"; } 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 b1bf0e0..f07b808 100644 --- a/src/main/java/me/skymc/taboolib/commands/language/Language2Command.java +++ b/src/main/java/me/skymc/taboolib/commands/language/Language2Command.java @@ -20,9 +20,9 @@ public class Language2Command implements CommandExecutor { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (args.length == 0) { TLocale.sendTo(sender, "COMMANDS.LANGUAGE2.HELP", label); - } else if (args[0].equalsIgnoreCase("reload")) { + } else if ("reload".equalsIgnoreCase(args[0])) { reload(sender); - } else if (args[0].equalsIgnoreCase("send")) { + } else if ("send".equalsIgnoreCase(args[0])) { send(sender, args); } return true; @@ -35,7 +35,7 @@ public class Language2Command implements CommandExecutor { long time = System.currentTimeMillis(); Language2Value value = getLanguage2Value(args); - if (args[1].equalsIgnoreCase("ALL")) { + if ("ALL".equalsIgnoreCase(args[1])) { value.broadcast(); } else { Player player = Bukkit.getPlayerExact(args[1]); diff --git a/src/main/java/me/skymc/taboolib/commands/locale/TabooLibLocaleCommand.java b/src/main/java/me/skymc/taboolib/commands/locale/TabooLibLocaleCommand.java index 6ba02fd..f7f4231 100644 --- a/src/main/java/me/skymc/taboolib/commands/locale/TabooLibLocaleCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/locale/TabooLibLocaleCommand.java @@ -1,7 +1,6 @@ package me.skymc.taboolib.commands.locale; import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.message.MsgUtils; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; @@ -22,9 +21,9 @@ public class TabooLibLocaleCommand implements CommandExecutor { public boolean onCommand(CommandSender sender, Command arg1, String label, String[] args) { if (args.length == 0) { TLocale.sendTo(sender, "COMMANDS.TLOCALE.HELP", label); - } else if (args[0].equalsIgnoreCase("send")) { + } else if ("send".equalsIgnoreCase(args[0])) { send(sender, args); - } else if (args[0].equalsIgnoreCase("reload")) { + } else if ("reload".equalsIgnoreCase(args[0])) { reload(sender); } else { TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); @@ -40,7 +39,7 @@ public class TabooLibLocaleCommand implements CommandExecutor { long time = System.currentTimeMillis(); List target = new ArrayList<>(); - if (args[1].equalsIgnoreCase("all")) { + if ("all".equalsIgnoreCase(args[1])) { target.addAll(Bukkit.getOnlinePlayers()); } else { Player player = Bukkit.getPlayerExact(args[1]); diff --git a/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginCommand.java b/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginCommand.java index ed29dd5..e5f348a 100644 --- a/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginCommand.java @@ -141,6 +141,7 @@ public class TabooLibPluginCommand extends InternalCommandExecutor { } else if (PluginUtils.isIgnored(plugin)) { TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.INVALID-PLUGIN-IGNORED", name); } else { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.TRY-RELOAD"); PluginUtils.reload(plugin); } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/SaveCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/SaveCommand.java index d8914af..bc8da08 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/SaveCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/SaveCommand.java @@ -62,7 +62,7 @@ public class SaveCommand extends SubCommand { @SuppressWarnings("deprecation") @Override public boolean after(String message) { - if (message.equalsIgnoreCase("yes")) { + if ("yes".equalsIgnoreCase(message)) { saveItem(args[1], ((Player) sender).getItemInHand()); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.SUCCESS", args[1]); } else { diff --git a/src/main/java/me/skymc/taboolib/commands/sub/VariableGetCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/VariableGetCommand.java index 30da0a5..836718c 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/VariableGetCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/VariableGetCommand.java @@ -1,38 +1,38 @@ package me.skymc.taboolib.commands.sub; import com.ilummc.tlib.resources.TLocale; -import org.bukkit.command.CommandSender; - import me.skymc.taboolib.commands.SubCommand; import me.skymc.taboolib.database.GlobalDataManager; -import me.skymc.taboolib.message.MsgUtils; +import org.bukkit.command.CommandSender; +/** + * @author sky + */ public class VariableGetCommand extends SubCommand { - public VariableGetCommand(CommandSender sender, String[] args) { - super(sender, args); - - if (args.length < 3) { - TLocale.sendTo(sender, "COAMMNDS.PARAMETER.INSUFFICIENT"); - return; - } + public VariableGetCommand(CommandSender sender, String[] args) { + super(sender, args); - if (!(args[1].equals("-a") || args[1].equals("-s"))) { - TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-ERROR-TYPE"); - return; - } - - Long time = System.currentTimeMillis(); - String value = null; - - if (args[1].equals("-s")) { - value = GlobalDataManager.getVariable(args[2], null); - } - else if (args[1].equals("-a")) { - value = GlobalDataManager.getVariableAsynchronous(args[2], null); - } + if (args.length < 3) { + TLocale.sendTo(sender, "COAMMNDS.PARAMETER.INSUFFICIENT"); + return; + } - TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-SUCCESS", String.valueOf(System.currentTimeMillis() - time)); - TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-RESULT", value == null ? "null" : value); - } + if (!("-a".equals(args[1]) || "-s".equals(args[1]))) { + TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-ERROR-TYPE"); + return; + } + + Long time = System.currentTimeMillis(); + String value = null; + + if ("-s".equals(args[1])) { + value = GlobalDataManager.getVariable(args[2], null); + } else if ("-a".equals(args[1])) { + value = GlobalDataManager.getVariableAsynchronous(args[2], null); + } + + TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-SUCCESS", String.valueOf(System.currentTimeMillis() - time)); + TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-RESULT", value == null ? "null" : value); + } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/VariableSetCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/VariableSetCommand.java index 202e7e0..543adfc 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/VariableSetCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/VariableSetCommand.java @@ -1,38 +1,35 @@ package me.skymc.taboolib.commands.sub; import com.ilummc.tlib.resources.TLocale; -import org.bukkit.command.CommandSender; - import me.skymc.taboolib.commands.SubCommand; import me.skymc.taboolib.database.GlobalDataManager; -import me.skymc.taboolib.message.MsgUtils; +import org.bukkit.command.CommandSender; public class VariableSetCommand extends SubCommand { - public VariableSetCommand(CommandSender sender, String[] args) { - super(sender, args); - - if (args.length < 4) { - TLocale.sendTo(sender, "COAMMNDS.PARAMETER.INSUFFICIENT"); - return; - } + public VariableSetCommand(CommandSender sender, String[] args) { + super(sender, args); - if (!(args[1].equals("-a") || args[1].equals("-s"))) { + if (args.length < 4) { + TLocale.sendTo(sender, "COAMMNDS.PARAMETER.INSUFFICIENT"); + return; + } + + if (!("-a".equals(args[1]) || "-s".equals(args[1]))) { TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.WRITE-ERROR-TYPE"); - return; - } - - Long time = System.currentTimeMillis(); - String value = getArgs(3); - - if (args[1].equals("-s")) { - GlobalDataManager.setVariable(args[2], value); - } - else if (args[1].equals("-a")) { - GlobalDataManager.setVariableAsynchronous(args[2], value); - } + return; + } + + Long time = System.currentTimeMillis(); + String value = getArgs(3); + + if ("-s".equals(args[1])) { + GlobalDataManager.setVariable(args[2], value); + } else if ("-a".equals(args[1])) { + GlobalDataManager.setVariableAsynchronous(args[2], value); + } TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.WRITE-SUCCESS", String.valueOf(System.currentTimeMillis() - time)); - setReturn(true); - } + setReturn(true); + } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/cycle/CycleCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/cycle/CycleCommand.java index 2c06f76..890fd82 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/cycle/CycleCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/cycle/CycleCommand.java @@ -9,13 +9,13 @@ public class CycleCommand extends SubCommand { public CycleCommand(CommandSender sender, String[] args) { super(sender, args); if (args.length > 1) { - if (args[1].equalsIgnoreCase("list")) { + if ("list".equalsIgnoreCase(args[1])) { new CycleListCommand(sender, args); - } else if (args[1].equalsIgnoreCase("info")) { + } else if ("info".equalsIgnoreCase(args[1])) { new CycleInfoCommand(sender, args); - } else if (args[1].equalsIgnoreCase("reset")) { + } else if ("reset".equalsIgnoreCase(args[1])) { new CycleResetCommand(sender, args); - } else if (args[1].equalsIgnoreCase("update")) { + } else if ("update".equalsIgnoreCase(args[1])) { new CycleUpdateCommand(sender, args); } } else { diff --git a/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellCommand.java index 3b6b3c1..d2f417d 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellCommand.java @@ -2,7 +2,6 @@ package me.skymc.taboolib.commands.sub.shell; import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.commands.SubCommand; -import me.skymc.taboolib.message.MsgUtils; import org.bukkit.command.CommandSender; public class ShellCommand extends SubCommand { @@ -10,9 +9,9 @@ public class ShellCommand extends SubCommand { public ShellCommand(CommandSender sender, String[] args) { super(sender, args); if (args.length > 1) { - if (args[1].equalsIgnoreCase("load")) { + if ("load".equalsIgnoreCase(args[1])) { new ShellLoadCommand(sender, args); - } else if (args[1].equalsIgnoreCase("unload")) { + } else if ("unload".equalsIgnoreCase(args[1])) { new ShellUnloadCommand(sender, args); } } else { diff --git a/src/main/java/me/skymc/taboolib/database/GlobalDataManager.java b/src/main/java/me/skymc/taboolib/database/GlobalDataManager.java index e0af21f..b8a5c63 100644 --- a/src/main/java/me/skymc/taboolib/database/GlobalDataManager.java +++ b/src/main/java/me/skymc/taboolib/database/GlobalDataManager.java @@ -29,7 +29,7 @@ public class GlobalDataManager { public static String getVariable(String name, String defaultVariable) { if (Main.getStorageType() == StorageType.SQL) { Object obj = Main.getConnection().getValueLast(Main.getTablePrefix() + "_plugindata", "name", name, "variable"); - return obj != null ? obj.toString().equals("null") ? defaultVariable : obj.toString() : defaultVariable; + return obj != null ? "null".equals(obj.toString()) ? defaultVariable : obj.toString() : defaultVariable; } else { return data.contains(name) ? data.getString(name) : defaultVariable; @@ -46,7 +46,7 @@ public class GlobalDataManager { public static String getVariableAsynchronous(String name, String defaultVariable) { if (Main.getStorageType() == StorageType.SQL) { SQLVariable variable = SQLMethod.getSQLVariable(name); - return variable == null ? defaultVariable : variable.getVariable().equals("null") ? defaultVariable : variable.getVariable(); + return variable == null ? defaultVariable : "null".equals(variable.getVariable()) ? defaultVariable : variable.getVariable(); } else { return getVariable(name, defaultVariable); @@ -138,7 +138,7 @@ public class GlobalDataManager { if (Main.getStorageType() == StorageType.SQL) { LinkedList> list = Main.getConnection().getValues(Main.getTablePrefix() + "_plugindata", "id", -1, false, "name", "variable"); for (HashMap _map : list) { - if (!_map.get("variable").toString().equals("null")) { + if (!"null".equals(_map.get("variable").toString())) { map.put(_map.get("name").toString(), _map.get("variable").toString()); } } @@ -160,7 +160,7 @@ public class GlobalDataManager { if (Main.getStorageType() == StorageType.SQL) { HashMap map = new HashMap<>(); for (SQLVariable variable : SQLMethod.getSQLVariables()) { - if (!variable.getVariable().equals("null")) { + if (!"null".equals(variable.getVariable())) { map.put(variable.getName(), variable.getVariable()); } } @@ -287,7 +287,7 @@ public class GlobalDataManager { public void run() { LinkedList> list = Main.getConnection().getValues(Main.getTablePrefix() + "_plugindata", "id", -1, false, "name", "variable", "upgrade"); for (HashMap _map : list) { - if (!_map.get("variable").toString().equals("null")) { + if (!"null".equals(_map.get("variable").toString())) { variables.put(_map.get("name").toString(), new SQLVariable(_map.get("name").toString(), _map.get("variable").toString(), _map.get("upgrade").toString())); } } @@ -326,7 +326,7 @@ public class GlobalDataManager { // 如果变量不是由本服更新 if (!value.get("upgrade").equals(variables.get(name).getUpgradeUID())) { // 如果变量是空 - if (value.get("variable").equals("null")) { + if ("null".equals(value.get("variable"))) { // 删除变量 variables.remove(name); } @@ -337,7 +337,7 @@ public class GlobalDataManager { } } // 如果变量存在则下载到本地 - else if (!value.get("variable").equals("null")) { + else if (!"null".equals(value.get("variable"))) { variables.put(value.get("name").toString(), new SQLVariable(value.get("name").toString(), value.get("variable").toString(), value.get("upgrade").toString())); } } diff --git a/src/main/java/me/skymc/taboolib/display/ActionUtils.java b/src/main/java/me/skymc/taboolib/display/ActionUtils.java index aa99905..b80e2b3 100644 --- a/src/main/java/me/skymc/taboolib/display/ActionUtils.java +++ b/src/main/java/me/skymc/taboolib/display/ActionUtils.java @@ -10,8 +10,9 @@ import org.bukkit.entity.Player; public class ActionUtils { public static void send(Player player, String action) { - if (player == null) + if (player == null) { return; + } try { ActionBar.sendActionBar(player, action); } catch (Throwable ignored) { diff --git a/src/main/java/me/skymc/taboolib/entity/EntityTag.java b/src/main/java/me/skymc/taboolib/entity/EntityTag.java index 49ff915..f24ea66 100644 --- a/src/main/java/me/skymc/taboolib/entity/EntityTag.java +++ b/src/main/java/me/skymc/taboolib/entity/EntityTag.java @@ -68,7 +68,9 @@ public class EntityTag { * @param value 值 */ public void set(String key, Object value, Entity... entities) { - for (Entity entity : entities) set(key, value, entity); + for (Entity entity : entities) { + set(key, value, entity); + } } /** @@ -78,7 +80,9 @@ public class EntityTag { * @param value 值 */ public void set(String key, Object value, List entities) { - for (Entity entity : entities) set(key, value, entity); + for (Entity entity : entities) { + set(key, value, entity); + } } /** @@ -104,7 +108,9 @@ public class EntityTag { * @param entities 实体 */ public void remove(String key, Entity... entities) { - for (Entity entity : entities) remove(key, entity); + for (Entity entity : entities) { + remove(key, entity); + } } /** @@ -114,7 +120,9 @@ public class EntityTag { * @param entities 实体 */ public void remove(String key, List entities) { - for (Entity entity : entities) remove(key, entity); + for (Entity entity : entities) { + remove(key, entity); + } } /** diff --git a/src/main/java/me/skymc/taboolib/fileutils/ConfigUtils.java b/src/main/java/me/skymc/taboolib/fileutils/ConfigUtils.java index bdd04e7..c076fc1 100644 --- a/src/main/java/me/skymc/taboolib/fileutils/ConfigUtils.java +++ b/src/main/java/me/skymc/taboolib/fileutils/ConfigUtils.java @@ -61,7 +61,7 @@ public class ConfigUtils { public static String mapToYaml(Map map) { String dump = YAML.dump(map); - if (dump.equals("{}\n")) { + if ("{}\n".equals(dump)) { dump = ""; } return dump; @@ -92,13 +92,17 @@ public class ConfigUtils { public static T mapToObj(Map map, T obj) { Class clazz = obj.getClass(); map.forEach((string, value) -> Ref.getFieldBySerializedName(clazz, string).ifPresent(field -> { - if (!field.isAccessible()) + if (!field.isAccessible()) { field.setAccessible(true); + } try { if (Property.class.isAssignableFrom(field.getType())) { Property property = (Property) field.get(obj); - if (property != null) property.set(value); - else field.set(obj, Property.of(value)); + if (property != null) { + property.set(value); + } else { + field.set(obj, Property.of(value)); + } } else { field.set(obj, value); } @@ -125,11 +129,16 @@ public class ConfigUtils { } for (Field field : Ref.getDeclaredFields(object.getClass(), excludedModifiers, false)) { try { - if (!field.isAccessible()) field.setAccessible(true); + if (!field.isAccessible()) { + field.setAccessible(true); + } Object obj = field.get(object); - if (obj instanceof Property) obj = ((Property) obj).get(); - if (obj instanceof ConfigurationSection) + if (obj instanceof Property) { + obj = ((Property) obj).get(); + } + if (obj instanceof ConfigurationSection) { obj = objToMap(((ConfigurationSection) obj).getValues(false), excludedModifiers); + } map.put(Ref.getSerializedName(field), obj); } catch (IllegalAccessException ignored) { } diff --git a/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java b/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java index f3d02e9..0d6e03c 100644 --- a/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java +++ b/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java @@ -496,7 +496,7 @@ public class ItemUtils { _attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); _attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); _attr.setString("Name", asAttribute(name)); - if (!hand.equals("all")) { + if (!"all".equals(hand)) { _attr.setString("Slot", hand); } } catch (Exception ignored) { @@ -535,7 +535,7 @@ public class ItemUtils { _attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); _attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); _attr.setString("Name", asAttribute(name)); - if (!hand.equals("all")) { + if (!"all".equals(hand)) { _attr.setString("Slot", hand); } } catch (NumberFormatException ignored) { diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTCompound.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTCompound.java index 0fc7571..8819bf4 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTCompound.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTCompound.java @@ -149,7 +149,9 @@ public class NBTCompound { public NBTCompound getCompound(String name) { NBTCompound next = new NBTCompound(this, name); - if (NBTReflectionUtil.valideCompound(next)) return next; + if (NBTReflectionUtil.valideCompound(next)) { + return next; + } return null; } @@ -158,7 +160,9 @@ public class NBTCompound { } public NBTType getType(String name) { - if (TabooLib.getVerint() == 10700) return NBTType.NBTTagEnd; + if (TabooLib.getVerint() == 10700) { + return NBTType.NBTTagEnd; + } return NBTType.valueOf(NBTReflectionUtil.getType(this, name)); } diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTReflectionUtil.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTReflectionUtil.java index 4e2c012..01fd1ca 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTReflectionUtil.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTReflectionUtil.java @@ -303,8 +303,9 @@ public class NBTReflectionUtil { method = c.getMethod(MethodNames.getEntityNbtGetterMethodName(), getNBTTagCompound()); Object nbt = getNBTTagCompound().newInstance(); Object answer = method.invoke(nmsitem, nbt); - if (answer == null) + if (answer == null) { answer = nbt; + } return answer; } catch (Exception e) { MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); @@ -334,8 +335,9 @@ public class NBTReflectionUtil { method = getTileEntity().getMethod(MethodNames.getTileDataMethodName(), getNBTTagCompound()); Object tag = getNBTTagCompound().newInstance(); Object answer = method.invoke(o, tag); - if (answer == null) + if (answer == null) { answer = tag; + } return answer; } catch (Exception e) { MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); @@ -381,7 +383,9 @@ public class NBTReflectionUtil { if (nbttag == null) { nbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(nbttag, comp); Method method; try { @@ -421,7 +425,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -442,7 +448,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -459,7 +467,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -476,7 +486,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -497,7 +509,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -514,7 +528,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -535,7 +551,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -552,7 +570,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -573,7 +593,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -590,7 +612,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -611,7 +635,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -628,7 +654,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -649,7 +677,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -666,7 +696,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -687,7 +719,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -704,7 +738,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -725,7 +761,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -742,7 +780,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -763,7 +803,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -780,7 +822,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -797,7 +841,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return 0; + if (!valideCompound(comp)) { + return 0; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -818,7 +864,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -835,7 +883,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -876,7 +926,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -910,7 +962,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return; + if (!valideCompound(comp)) { + return; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -927,7 +981,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { @@ -945,7 +1001,9 @@ public class NBTReflectionUtil { if (rootnbttag == null) { rootnbttag = getNewNBTTag(); } - if (!valideCompound(comp)) return null; + if (!valideCompound(comp)) { + return null; + } Object workingtag = gettoCompount(rootnbttag, comp); Method method; try { diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTType.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTType.java index c208638..1d3d4e2 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTType.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTType.java @@ -26,9 +26,11 @@ public enum NBTType { } public static NBTType valueOf(int id) { - for (NBTType t : values()) - if (t.getId() == id) + for (NBTType t : values()) { + if (t.getId() == id) { return t; + } + } return NBTType.NBTTagEnd; } diff --git a/src/main/java/me/skymc/taboolib/json/Cookie.java b/src/main/java/me/skymc/taboolib/json/Cookie.java index 3022d0c..d1e014f 100644 --- a/src/main/java/me/skymc/taboolib/json/Cookie.java +++ b/src/main/java/me/skymc/taboolib/json/Cookie.java @@ -32,7 +32,7 @@ public class Cookie { while (x.more()) { name = unescape(x.nextTo("=;")); if (x.next() != '=') { - if (name.equals("secure")) { + if ("secure".equals(name)) { value = Boolean.TRUE; } else { throw x.syntaxError("Missing '=' in cookie parameter."); diff --git a/src/main/java/me/skymc/taboolib/json/JSONArray.java b/src/main/java/me/skymc/taboolib/json/JSONArray.java index 793a100..6277d3a 100644 --- a/src/main/java/me/skymc/taboolib/json/JSONArray.java +++ b/src/main/java/me/skymc/taboolib/json/JSONArray.java @@ -86,11 +86,11 @@ public class JSONArray { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && - ((String) object).equalsIgnoreCase("false"))) { + "false".equalsIgnoreCase((String) object))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && - ((String) object).equalsIgnoreCase("true"))) { + "true".equalsIgnoreCase((String) object))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); diff --git a/src/main/java/me/skymc/taboolib/json/JSONML.java b/src/main/java/me/skymc/taboolib/json/JSONML.java index 2353bfc..2a3ca14 100644 --- a/src/main/java/me/skymc/taboolib/json/JSONML.java +++ b/src/main/java/me/skymc/taboolib/json/JSONML.java @@ -46,7 +46,7 @@ public class JSONML { break; case '[': token = x.nextToken(); - if (token.equals("CDATA") && x.next() == '[') { + if ("CDATA".equals(token) && x.next() == '[') { if (ja != null) { ja.put(x.nextCDATA()); } diff --git a/src/main/java/me/skymc/taboolib/json/JSONObject.java b/src/main/java/me/skymc/taboolib/json/JSONObject.java index 70667e9..f335cf8 100644 --- a/src/main/java/me/skymc/taboolib/json/JSONObject.java +++ b/src/main/java/me/skymc/taboolib/json/JSONObject.java @@ -109,7 +109,7 @@ public class JSONObject { this.populateMap(bean); } - public JSONObject(Object object, String names[]) { + public JSONObject(Object object, String[] names) { this(); Class c = object.getClass(); for (String name : names) { @@ -210,11 +210,11 @@ public class JSONObject { Object object = this.get(key); if (object.equals(Boolean.FALSE) || (object instanceof String && - ((String) object).equalsIgnoreCase("false"))) { + "false".equalsIgnoreCase((String) object))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && - ((String) object).equalsIgnoreCase("true"))) { + "true".equalsIgnoreCase((String) object))) { return true; } throw new JSONException("JSONObject[" + quote(key) + @@ -322,16 +322,16 @@ public class JSONObject { public static Object stringToValue(String string) { Double d; - if (string.equals("")) { + if ("".equals(string)) { return string; } - if (string.equalsIgnoreCase("true")) { + if ("true".equalsIgnoreCase(string)) { return Boolean.TRUE; } - if (string.equalsIgnoreCase("false")) { + if ("false".equalsIgnoreCase(string)) { return Boolean.FALSE; } - if (string.equalsIgnoreCase("null")) { + if ("null".equalsIgnoreCase(string)) { return JSONObject.NULL; } char b = string.charAt(0); diff --git a/src/main/java/me/skymc/taboolib/json/JSONWriter.java b/src/main/java/me/skymc/taboolib/json/JSONWriter.java index 51074c0..399056d 100644 --- a/src/main/java/me/skymc/taboolib/json/JSONWriter.java +++ b/src/main/java/me/skymc/taboolib/json/JSONWriter.java @@ -11,7 +11,7 @@ public class JSONWriter { protected char mode; - private final JSONObject stack[]; + private final JSONObject[] stack; private int top; diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java b/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java index e8e7a3f..b06d456 100644 --- a/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java +++ b/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java @@ -42,8 +42,9 @@ public class JSONFormatter { } public JSONFormatter append(JSONFormatter json) { - if (json.ja.length() == 0) + if (json.ja.length() == 0) { return this; + } try { if (newline && json.newline) { all.addAll(json.all); @@ -76,8 +77,9 @@ public class JSONFormatter { } public JSONFormatter newLine(int amount) { - for (int i = 0; i < amount; i++) + for (int i = 0; i < amount; i++) { newLine(); + } return this; } @@ -104,8 +106,9 @@ public class JSONFormatter { public String toJSON() { JSONObject jo = new JSONObject(); try { - if (ja.length() > 0) + if (ja.length() > 0) { jo.put("extra", ja); + } jo.put("text", ""); } catch (Exception e) { e.printStackTrace(); @@ -118,14 +121,16 @@ public class JSONFormatter { try { for (JSONArray ja : all) { JSONObject jo = new JSONObject(); - if (ja.length() > 0) + if (ja.length() > 0) { jo.put("extra", ja); + } jo.put("text", ""); list.add(jo.toString()); } JSONObject jo = new JSONObject(); - if (ja.length() > 0) + if (ja.length() > 0) { jo.put("extra", ja); + } jo.put("text", ""); list.add(jo.toString()); return list; @@ -163,10 +168,12 @@ public class JSONFormatter { } private void add(Object jo) { - if (ja == null) + if (ja == null) { ja = new JSONArray(); - if (jo != null) + } + if (jo != null) { ja.put(jo); + } } private JSONFormatter append(String text, BuilderMaker bm) { @@ -297,8 +304,9 @@ public class JSONFormatter { private static boolean check(Object... o) { for (Object a : o) { - if (a == null) + if (a == null) { return false; + } } return true; } @@ -369,24 +377,32 @@ public class JSONFormatter { private JSONObject toString(String color, BuilderHelper bh) { String string = sb.toString(); - if (!changed) + if (!changed) { return null; - if (string.length() == 0) + } + if (string.length() == 0) { return null; + } JSONObject jo = new JSONObject(); try { - if (!color.equals("")) + if (!"".equals(color)) { jo.put("color", color); - if (bold) + } + if (bold) { jo.put("bold", true); - if (italic) + } + if (italic) { jo.put("italic", true); - if (magic) + } + if (magic) { jo.put("obfuscated", true); - if (strikethrough) + } + if (strikethrough) { jo.put("strikethrough", true); - if (underline) + } + if (underline) { jo.put("underlined", true); + } bh.add(jo); jo.put("text", string); } catch (Exception e) { @@ -407,8 +423,9 @@ public class JSONFormatter { return toString(color, new BuilderHelper() { @Override public void add(JSONObject jo) throws Exception { - if (event.getEvent().length() > 1) + if (event.getEvent().length() > 1) { jo.put("hoverEvent", event.getEvent()); + } } }); } @@ -417,8 +434,9 @@ public class JSONFormatter { return toString(color, new BuilderHelper() { @Override public void add(JSONObject jo) throws Exception { - if (event.getEvent().length() > 1) + if (event.getEvent().length() > 1) { jo.put("clickEvent", event.getEvent()); + } } }); } @@ -427,10 +445,12 @@ public class JSONFormatter { return toString(color, new BuilderHelper() { @Override public void add(JSONObject jo) throws Exception { - if (hevent.getEvent().length() > 1) + if (hevent.getEvent().length() > 1) { jo.put("hoverEvent", hevent.getEvent()); - if (cevent.getEvent().length() > 1) + } + if (cevent.getEvent().length() > 1) { jo.put("clickEvent", cevent.getEvent()); + } } }); } diff --git a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java index c1a339f..3594e56 100644 --- a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java +++ b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java @@ -18,7 +18,7 @@ public class ListenerPlayerCommand implements Listener { @EventHandler public void cmd(ServerCommandEvent e) { - if (e.getCommand().equals("savefile")) { + if ("savefile".equals(e.getCommand())) { if (TabooLib.getVerint() > 10700) { e.setCancelled(true); } @@ -30,7 +30,7 @@ public class ListenerPlayerCommand implements Listener { @SuppressWarnings("deprecation") @EventHandler public void cmd(PlayerCommandPreprocessEvent e) { - if (e.getMessage().equals("/unbreakable") && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) { + if ("/unbreakable".equals(e.getMessage()) && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) { e.setCancelled(true); NBTItem nbti = new NBTItem(e.getPlayer().getItemInHand()); diff --git a/src/main/java/me/skymc/taboolib/location/LocationUtils.java b/src/main/java/me/skymc/taboolib/location/LocationUtils.java index 6854edb..23dc1be 100644 --- a/src/main/java/me/skymc/taboolib/location/LocationUtils.java +++ b/src/main/java/me/skymc/taboolib/location/LocationUtils.java @@ -47,7 +47,9 @@ public class LocationUtils { @Deprecated public static Block findBlockByLocation(Location l) { - while (l.getY() < 255 && l.getBlock().getType() != Material.AIR) l.add(0, 1, 0); + 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; } diff --git a/src/main/java/me/skymc/taboolib/message/ChatCatcher.java b/src/main/java/me/skymc/taboolib/message/ChatCatcher.java index 125bd58..aa7f6a2 100644 --- a/src/main/java/me/skymc/taboolib/message/ChatCatcher.java +++ b/src/main/java/me/skymc/taboolib/message/ChatCatcher.java @@ -38,7 +38,7 @@ public class ChatCatcher implements Listener { if (playerdata.containsKey(e.getPlayer().getName()) && playerdata.get(e.getPlayer().getName()).size() > 0) { e.setCancelled(true); - if (e.getMessage().equalsIgnoreCase("quit()")) { + if ("quit()".equalsIgnoreCase(e.getMessage())) { // 退出引导 playerdata.get(e.getPlayer().getName()).removeFirst().cancel(); // 清理数据 diff --git a/src/main/java/me/skymc/taboolib/message/MsgUtils.java b/src/main/java/me/skymc/taboolib/message/MsgUtils.java index 2b881e8..8692de7 100644 --- a/src/main/java/me/skymc/taboolib/message/MsgUtils.java +++ b/src/main/java/me/skymc/taboolib/message/MsgUtils.java @@ -54,7 +54,7 @@ public class MsgUtils { @Deprecated public static String noPe() { String s = Main.getInst().getConfig().getString("NO-PERMISSION-MESSAGE").replaceAll("&", "§"); - if (s.equals("")) { + if ("".equals(s)) { s = "§cCONFIG ERROR §8(NO-PERMISSION-MESSAGE)"; } return s; @@ -63,7 +63,7 @@ public class MsgUtils { @Deprecated public static String noClaim(String a) { String s = Main.getInst().getConfig().getString("NO-CLAIM-MESSAGE").replaceAll("&", "§").replaceAll("%s%", a); - if (s.equals("")) { + 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 index 25f3f04..7040bf9 100644 --- a/src/main/java/me/skymc/taboolib/methods/MethodsUtils.java +++ b/src/main/java/me/skymc/taboolib/methods/MethodsUtils.java @@ -6,49 +6,44 @@ 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("未经允许的方法调用"); - } + public static boolean checkUser(String packagename, String current) { + return current.substring(0, 8).equals(packagename); + } - 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; - } + @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 index bec8274..5669936 100644 --- a/src/main/java/me/skymc/taboolib/mysql/MysqlConnection.java +++ b/src/main/java/me/skymc/taboolib/mysql/MysqlConnection.java @@ -1,347 +1,329 @@ package me.skymc.taboolib.mysql; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; +import java.sql.*; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.*; @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 数据库成功"); - - new Thread(() -> { - while (isConnection) { - try { - if (connection.isClosed()) { - connection = DriverManager.getConnection(url, user, pass); - System("数据库连接关闭, 正在重新连接... [Connection Closed]"); - } - - Thread.sleep(30000); - } catch (Exception e) { - e.printStackTrace(); - } - } - }).start(); - } - 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); - } - } - - /** - * @deprecated 即将过期 - * - * @see Example: SQL_ClearTable("tablename"); - */ - @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("\"", ""); - } - + + /** + * 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 index a1534bb..e1e73a6 100644 --- a/src/main/java/me/skymc/taboolib/mysql/MysqlUtils.java +++ b/src/main/java/me/skymc/taboolib/mysql/MysqlUtils.java @@ -1,38 +1,37 @@ package me.skymc.taboolib.mysql; -import java.util.concurrent.CopyOnWriteArrayList; - +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 me.skymc.taboolib.Main; -import me.skymc.taboolib.message.MsgUtils; -import me.skymc.taboolib.mysql.protect.MySQLConnection; +import java.util.concurrent.CopyOnWriteArrayList; public class MysqlUtils { - - public final static CopyOnWriteArrayList CONNECTIONS = new CopyOnWriteArrayList<>(); - - 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 conn = 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 (conn.isConnection()) { - CONNECTIONS.add(conn); - MsgUtils.send("已向书库注册插件 &f" + plugin.getName() + "&7 的数据库连接"); - } - return conn; - } + + public final static CopyOnWriteArrayList CONNECTIONS = new CopyOnWriteArrayList<>(); + + 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 conn = 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 (conn.isConnection()) { + CONNECTIONS.add(conn); + TLocale.Logger.info("MYSQL-CONNECTION.SUCCESS-REGISTERED", plugin.getName()); + } + return conn; + } } diff --git a/src/main/java/me/skymc/taboolib/mysql/protect/MySQLConnection.java b/src/main/java/me/skymc/taboolib/mysql/protect/MySQLConnection.java index 0069c43..384467e 100644 --- a/src/main/java/me/skymc/taboolib/mysql/protect/MySQLConnection.java +++ b/src/main/java/me/skymc/taboolib/mysql/protect/MySQLConnection.java @@ -1,14 +1,20 @@ 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.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; +/** + * @author sky + */ public class MySQLConnection { private String url; @@ -82,7 +88,7 @@ public class MySQLConnection { public MySQLConnection(String url, String user, String port, String password, String database, int recheck, Plugin plugin) { // 检查驱动 if (!loadDriverMySQL()) { - print("驱动器获取失败, 无法连接到数据库"); + TLocale.Logger.error("MYSQL-CONNECTION.FALL-NOTFOUND-DRIVE"); return; } @@ -96,7 +102,7 @@ public class MySQLConnection { this.port = port == null ? "3306" : port; this.password = password == null ? "" : password; this.database = database == null ? "test" : database; - this.connectionUrl = "jdbc:mysql://" + this.url + ":" + this.port + "/" + this.database + "?characterEncoding=utf-8&useSSL=false"; + this.connectionUrl = Strings.replaceWithOrder("jdbc:mysql://{0}:{1}/{2}?characterEncoding=utf-8&useSSL=false", this.url, this.port, this.database); // 连接数据库 connect(); @@ -108,13 +114,12 @@ public class MySQLConnection { Thread.sleep(getReCheckSeconds() * 1000); if (connection == null) { - print("警告! 数据库尚未连接, 请检查配置文件后重启服务器! (" + (plugin.getName()) + ")"); + TLocale.Logger.error("MYSQL-CONNECTION.FALL-NOTFOUND-CONNECTION", plugin.getName()); } else { isExists("taboolib"); } } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); + TLocale.Logger.error("MYSQL-CONNECTION.FALL-COMMAND-NORMAL", e.toString()); } } }); @@ -122,7 +127,7 @@ public class MySQLConnection { // 启动检测 if (isConnection()) { recheckThread.start(); - print("启动数据库连接监控"); + TLocale.Logger.info("MYSQL-CONNECTION.SUCCESS-REGISTERED-LISTENER"); } } @@ -149,13 +154,11 @@ public class MySQLConnection { public void closeConnection() { try { connection.close(); - } catch (Exception e) { - // + } catch (Exception ignored) { } try { recheckThread.stop(); - } catch (Exception e) { - // + } catch (Exception ignored) { } } @@ -166,8 +169,8 @@ public class MySQLConnection { /** * 2018年1月17日 新增, TabooLib 版本 3.25 */ - public void truncateTable(String name) { - execute("truncate table " + name); + public boolean truncateTable(String name) { + return execute("truncate table " + name); } public boolean clearTable(String name) { @@ -175,35 +178,33 @@ public class MySQLConnection { } public boolean renameTable(String name, String newName) { - return execute("rename table `" + name + "` to `" + newName + "`"); + return execute(Strings.replaceWithOrder("rename table `{0}` to `{1}`", name, newName)); } public boolean deleteColumn(String name, String column) { - return execute("alter table `" + name + "` drop `" + column + "`"); + return execute(Strings.replaceWithOrder("alter table `{0}` drop `{1}`", name, column)); } public void addColumn(String name, Column... columns) { - for (Column column : columns) { - execute("alter table " + name + " add " + column.toString()); - } + 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("alter table " + name + " add `" + column + "` text"); + return execute(Strings.replaceWithOrder("alter table {0} add `{1}` text", name, column)); } - return execute("alter table " + name + " add `" + column.split("/")[0] + "` " + column.split("/")[1]); + 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("alter table " + name + " change `" + oldColumn + "` " + newColumn.toString()); + 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("alter table " + name + " change `" + oldColumn + "` `" + newColumn + "` text"); + return execute(Strings.replaceWithOrder("alter table {0} change `{1}` `{2}` text", name, oldColumn, newColumn)); } - return execute("alter table " + name + " change `" + oldColumn + "` `" + newColumn.split("/")[0] + "` " + newColumn.split("/")[1]); + return execute(Strings.replaceWithOrder("alter table {0} change `{1}` `{2}` {3}", name, oldColumn, newColumn.split("/")[0], newColumn.split("/")[1])); } /** @@ -215,21 +216,15 @@ public class MySQLConnection { * @return boolean */ public boolean deleteValue(String name, String column, Object columnValue) { - PreparedStatement pstmt = null; - ResultSet resultSet = null; + PreparedStatement preparedStatement = null; try { - pstmt = connection.prepareStatement("delete from `" + name + "` where `" + column + "` = ?"); - pstmt.setObject(1, columnValue); - pstmt.executeUpdate(); + preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("delete from `{0}` where `{1}` = ?", name, column)); + preparedStatement.setObject(1, columnValue); + preparedStatement.executeUpdate(); } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(null, pstmt); + freeResult(null, preparedStatement); } return false; } @@ -260,26 +255,20 @@ public class MySQLConnection { * @return boolean */ public boolean setValue(String name, String column, Object columnValue, String valueColumn, Object value, boolean append) { - PreparedStatement pstmt = null; - ResultSet resultSet = null; + PreparedStatement preparedStatement = null; try { if (append) { - pstmt = connection.prepareStatement("update `" + name + "` set `" + valueColumn + "` = `" + valueColumn + "` + ? where `" + column + "` = ?"); + preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("update `{0}` set `{1}` = `{2}` + ? where `{3}` = ?", name, valueColumn, valueColumn, column)); } else { - pstmt = connection.prepareStatement("update `" + name + "` set `" + valueColumn + "` = ? where `" + column + "` = ?"); + preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("update `{0}` set `{1}` = ? where `{2}` = ?", name, valueColumn, column)); } - pstmt.setObject(1, value); - pstmt.setObject(2, columnValue); - pstmt.executeUpdate(); + preparedStatement.setObject(1, value); + preparedStatement.setObject(2, columnValue); + preparedStatement.executeUpdate(); } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(resultSet, pstmt); + freeResult(null, preparedStatement); } return false; } @@ -293,26 +282,19 @@ public class MySQLConnection { */ public boolean intoValue(String name, Object... values) { StringBuilder sb = new StringBuilder(); - for (Object value : values) { - sb.append("?, "); - } - PreparedStatement pstmt = null; + Arrays.stream(values).map(value -> "?, ").forEach(sb::append); + PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { - pstmt = connection.prepareStatement("insert into `" + name + "` values(null, " + sb.substring(0, sb.length() - 2) + ")"); + 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++) { - pstmt.setObject(i + 1, values[i]); + preparedStatement.setObject(i + 1, values[i]); } - pstmt.executeUpdate(); + preparedStatement.executeUpdate(); } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(resultSet, pstmt); + freeResult(null, preparedStatement); } return false; } @@ -326,10 +308,8 @@ public class MySQLConnection { */ public boolean createTable(String name, Column... columns) { StringBuilder sb = new StringBuilder(); - for (Column column : columns) { - sb.append(column.toString()).append(", "); - } - return execute("create table if not exists " + name + " (id int(1) not null primary key auto_increment, " + sb.substring(0, sb.length() - 2) + ")"); + 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))); } /** @@ -348,7 +328,7 @@ public class MySQLConnection { sb.append("`").append(column.split("/")[0]).append("` ").append(column.split("/")[1]).append(", "); } } - return execute("create table if not exists " + name + " (id int(1) not null primary key auto_increment, " + sb.substring(0, sb.length() - 2) + ")"); + 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))); } /** @@ -358,24 +338,19 @@ public class MySQLConnection { * @return boolean */ public boolean isExists(String name) { - PreparedStatement pstmt = null; + PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { - pstmt = connection.prepareStatement("select table_name FROM information_schema.TABLES where table_name = ?"); - pstmt.setString(1, name); - resultSet = pstmt.executeQuery(); + 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) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(resultSet, pstmt); + freeResult(resultSet, preparedStatement); } return false; } @@ -389,24 +364,19 @@ public class MySQLConnection { * @return boolean */ public boolean isExists(String name, String column, Object columnValue) { - PreparedStatement pstmt = null; + PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { - pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ?"); - pstmt.setObject(1, columnValue); - resultSet = pstmt.executeQuery(); + 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) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(resultSet, pstmt); + freeResult(resultSet, preparedStatement); } return false; } @@ -430,24 +400,19 @@ public class MySQLConnection { */ public List getColumns(String name, boolean primary) { List list = new ArrayList<>(); - PreparedStatement pstmt = null; + PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { - pstmt = connection.prepareStatement("select column_name from information_schema.COLUMNS where table_name = ?"); - pstmt.setString(1, name); - resultSet = pstmt.executeQuery(); + 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) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(resultSet, pstmt); + freeResult(resultSet, preparedStatement); } // 是否获取主键 if (!primary) { @@ -466,24 +431,19 @@ public class MySQLConnection { * @return Object */ public Object getValue(String name, String column, Object columnValue, String valueColumn) { - PreparedStatement pstmt = null; + PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { - pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? limit 1"); - pstmt.setObject(1, columnValue); - resultSet = pstmt.executeQuery(); + 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) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(resultSet, pstmt); + freeResult(resultSet, preparedStatement); } return null; } @@ -498,24 +458,19 @@ public class MySQLConnection { * @return Object */ public Object getValueLast(String name, String column, Object columnValue, String valueColumn) { - PreparedStatement pstmt = null; + PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { - pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? order by id desc limit 1"); - pstmt.setObject(1, columnValue); - resultSet = pstmt.executeQuery(); + 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) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(resultSet, pstmt); + freeResult(resultSet, preparedStatement); } return null; } @@ -531,12 +486,12 @@ public class MySQLConnection { */ public HashMap getValueLast(String name, String column, Object columnValue, String... valueColumn) { HashMap map = new HashMap<>(); - PreparedStatement pstmt = null; + PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { - pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? order by id desc limit 1"); - pstmt.setObject(1, columnValue); - resultSet = pstmt.executeQuery(); + 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)); @@ -544,14 +499,9 @@ public class MySQLConnection { break; } } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(resultSet, pstmt); + freeResult(resultSet, preparedStatement); } return map; } @@ -567,12 +517,12 @@ public class MySQLConnection { */ public HashMap getValue(String name, String column, Object columnValue, String... valueColumn) { HashMap map = new HashMap<>(); - PreparedStatement pstmt = null; + PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { - pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? limit 1"); - pstmt.setObject(1, columnValue); - resultSet = pstmt.executeQuery(); + 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)); @@ -580,14 +530,9 @@ public class MySQLConnection { break; } } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(resultSet, pstmt); + freeResult(resultSet, preparedStatement); } return map; } @@ -615,27 +560,22 @@ public class MySQLConnection { */ public List getValues(String name, String column, int size, boolean desc) { List list = new LinkedList<>(); - PreparedStatement pstmt = null; + PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { if (desc) { - pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + column + "` desc " + (size < 0 ? "" : " limit " + size)); + preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}` desc {2}", name, column, size < 0 ? "" : " limit " + size)); } else { - pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + column + "` " + (size < 0 ? "" : " limit " + size)); + preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}` {2}", name, column, size < 0 ? "" : " limit " + size)); } - resultSet = pstmt.executeQuery(); + resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { list.add(resultSet.getObject(column)); } } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(resultSet, pstmt); + freeResult(resultSet, preparedStatement); } return list; } @@ -665,15 +605,15 @@ public class MySQLConnection { */ public LinkedList> getValues(String name, String sortColumn, int size, boolean desc, String... valueColumn) { LinkedList> list = new LinkedList<>(); - PreparedStatement pstmt = null; + PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { if (desc) { - pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + sortColumn + "` desc" + (size < 0 ? "" : " limit " + size)); + preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}` desc{2}", name, sortColumn, size < 0 ? "" : " limit " + size)); } else { - pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + sortColumn + "`" + (size < 0 ? "" : " limit " + size)); + preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}`{2}", name, sortColumn, size < 0 ? "" : " limit " + size)); } - resultSet = pstmt.executeQuery(); + resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { HashMap map = new HashMap<>(); for (String _column : valueColumn) { @@ -682,56 +622,36 @@ public class MySQLConnection { list.add(map); } } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } + printException(e); } finally { - freeResult(resultSet, pstmt); + freeResult(resultSet, preparedStatement); } return list; } public boolean execute(String sql) { - PreparedStatement pstmt = null; + PreparedStatement preparedStatement = null; try { - pstmt = connection.prepareStatement(sql); - pstmt.execute(); + preparedStatement = connection.prepareStatement(sql); + preparedStatement.execute(); return true; - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - print("错误命令: " + sql); - // 重连 - if (e.getMessage().contains("closed")) { - connect(); - } + } catch (SQLException e) { + printExceptionDetail(e); return false; } finally { - try { - if (pstmt != null) { - pstmt.close(); - } - } catch (Exception e) { - // - } + freeResult(null, preparedStatement); } } public boolean connect() { + TLocale.Logger.info("MYSQL-CONNECTION.NOTIFY-CONNECTING", connectionUrl); try { - print("正在连接数据库"); - print("地址: " + connectionUrl); long time = System.currentTimeMillis(); connection = DriverManager.getConnection(connectionUrl, this.user, this.password); - print("数据库连接成功 (" + (System.currentTimeMillis() - time) + "ms)"); + TLocale.Logger.info("MYSQL-CONNECTION.NOTIFY-CONNECTED", String.valueOf(System.currentTimeMillis() - time)); return true; } catch (SQLException e) { - print("数据库连接失败"); - print("错误原因: " + e.getMessage()); - print("错误代码: " + e.getErrorCode()); + printExceptionDetail(e); return false; } } @@ -740,26 +660,19 @@ public class MySQLConnection { System.out.println("[TabooLib - MySQL] " + message); } - /** - * 释放结果集 - * - * @param resultSet 不知道叫什么 - * @param pstmt 不知道叫什么 - */ - private void freeResult(ResultSet resultSet, PreparedStatement pstmt) { - try { - if (resultSet != null) { - resultSet.close(); - } - } catch (Exception e) { - // - } - try { - if (pstmt != null) { - pstmt.close(); - } - } catch (Exception e) { - // + private void printException(Exception e) { + TLocale.Logger.error("MYSQL-CONNECTION.FALL-COMMAND-NORMAL", e.toString()); + reconnection(e); + } + + private void printExceptionDetail(SQLException e) { + TLocale.Logger.error("MYSQL-CONNECTION.FALL-COMMAND-DETAIL", String.valueOf(e.getErrorCode()), e.toString()); + reconnection(e); + } + + private void reconnection(Exception e) { + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); } } @@ -772,6 +685,21 @@ public class MySQLConnection { } } + 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 @@ -837,11 +765,11 @@ public class MySQLConnection { @Override public String toString() { if (type instanceof ColumnInteger || type instanceof ColumnChar) { - return "`" + name + "` " + type.toString().toLowerCase() + "(" + a + ")"; + return Strings.replaceWithOrder("`{0}` {1}({2})", name, type.toString().toLowerCase(), a); } else if (type instanceof ColumnFloat) { - return "`" + name + "` " + type.toString().toLowerCase() + "(" + a + "," + b + ")"; + return Strings.replaceWithOrder("`{0}` {1}({2},{3})", name, type.toString().toLowerCase(), a, b); } else { - return "`" + name + "` " + type.toString().toLowerCase(); + 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 index 7a414c7..162bef5 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java @@ -541,7 +541,9 @@ public class NMSUtil18 { } public static Object getHandle(org.bukkit.World world) { - if (world == null) return null; + if (world == null) { + return null; + } Object handle = null; try { handle = class_CraftWorld_getHandleMethod.invoke(world); @@ -552,7 +554,9 @@ public class NMSUtil18 { } public static Object getHandle(org.bukkit.entity.Entity entity) { - if (entity == null) return null; + if (entity == null) { + return null; + } Object handle = null; try { handle = class_CraftEntity_getHandleMethod.invoke(entity); @@ -563,7 +567,9 @@ public class NMSUtil18 { } public static Object getHandle(org.bukkit.entity.LivingEntity entity) { - if (entity == null) return null; + if (entity == null) { + return null; + } Object handle = null; try { handle = class_CraftLivingEntity_getHandleMethod.invoke(entity); @@ -612,7 +618,9 @@ public class NMSUtil18 { World sourceWorld = source.getWorld(); for (Player player : players) { Location location = player.getLocation(); - if (!location.getWorld().equals(sourceWorld)) continue; + if (!location.getWorld().equals(sourceWorld)) { + continue; + } if (location.distanceSquared(source) <= viewDistanceSquared) { sendPacket(player, packet); } @@ -649,11 +657,15 @@ public class NMSUtil18 { } public static org.bukkit.entity.Entity getBukkitEntity(Object entity) { - if (entity == null) return null; + if (entity == null) { + return null; + } try { Method getMethod = entity.getClass().getMethod("getBukkitEntity"); Object bukkitEntity = getMethod.invoke(entity); - if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) return null; + if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) { + return null; + } return (org.bukkit.entity.Entity) bukkitEntity; } catch (Throwable ex) { ex.printStackTrace(); @@ -683,7 +695,9 @@ public class NMSUtil18 { } public static ItemStack getCopy(ItemStack stack) { - if (stack == null) return null; + if (stack == null) { + return null; + } try { Object craft = getNMSCopy(stack); @@ -696,7 +710,9 @@ public class NMSUtil18 { } public static ItemStack makeReal(ItemStack stack) { - if (stack == null) return null; + if (stack == null) { + return null; + } Object nmsStack = getHandle(stack); if (nmsStack == null) { stack = getCopy(stack); @@ -728,13 +744,19 @@ public class NMSUtil18 { } public static Object getNode(ItemStack stack, String tag) { - if (stack == null) return null; + if (stack == null) { + return null; + } Object meta = null; try { Object craft = getHandle(stack); - if (craft == null) return null; + if (craft == null) { + return null; + } Object tagObject = getTag(craft); - if (tagObject == null) return null; + if (tagObject == null) { + return null; + } meta = class_NBTTagCompound_getMethod.invoke(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); @@ -743,7 +765,9 @@ public class NMSUtil18 { } public static boolean containsNode(Object nbtBase, String tag) { - if (nbtBase == null) return false; + if (nbtBase == null) { + return false; + } Boolean result = false; try { result = (Boolean) class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); @@ -754,7 +778,9 @@ public class NMSUtil18 { } public static Object getNode(Object nbtBase, String tag) { - if (nbtBase == null) return null; + if (nbtBase == null) { + return null; + } Object meta = null; try { meta = class_NBTTagCompound_getMethod.invoke(nbtBase, tag); @@ -765,7 +791,9 @@ public class NMSUtil18 { } public static Object createNode(Object nbtBase, String tag) { - if (nbtBase == null) return null; + if (nbtBase == null) { + return null; + } Object meta = null; try { meta = class_NBTTagCompound_getCompoundMethod.invoke(nbtBase, tag); @@ -777,14 +805,20 @@ public class NMSUtil18 { } public static Object createNode(ItemStack stack, String tag) { - if (stack == null) return null; + if (stack == null) { + return null; + } Object outputObject = getNode(stack, tag); if (outputObject == null) { try { Object craft = getHandle(stack); - if (craft == null) return null; + if (craft == null) { + return null; + } Object tagObject = getTag(craft); - if (tagObject == null) return null; + if (tagObject == null) { + return null; + } outputObject = class_NBTTagCompound.newInstance(); class_NBTTagCompound_setMethod.invoke(tagObject, tag, outputObject); } catch (Throwable ex) { @@ -800,7 +834,9 @@ public class NMSUtil18 { } public static String getMeta(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) return null; + if (node == null || !class_NBTTagCompound.isInstance(node)) { + return null; + } String meta = null; try { meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag); @@ -811,7 +847,9 @@ public class NMSUtil18 { } public static Byte getMetaByte(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) return null; + if (node == null || !class_NBTTagCompound.isInstance(node)) { + return null; + } Byte meta = null; try { meta = (Byte) class_NBTTagCompound_getByteMethod.invoke(node, tag); @@ -822,7 +860,9 @@ public class NMSUtil18 { } public static Integer getMetaInt(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) return null; + if (node == null || !class_NBTTagCompound.isInstance(node)) { + return null; + } Integer meta = null; try { meta = (Integer) class_NBTTagCompound_getIntMethod.invoke(node, tag); @@ -833,7 +873,9 @@ public class NMSUtil18 { } public static void setMeta(Object node, String tag, String value) { - if (node == null || !class_NBTTagCompound.isInstance(node)) return; + if (node == null || !class_NBTTagCompound.isInstance(node)) { + return; + } try { if (value == null || value.length() == 0) { class_NBTTagCompound_removeMethod.invoke(node, tag); @@ -846,7 +888,9 @@ public class NMSUtil18 { } public static void removeMeta(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) return; + if (node == null || !class_NBTTagCompound.isInstance(node)) { + return; + } try { class_NBTTagCompound_removeMethod.invoke(node, tag); } catch (Throwable ex) { @@ -855,13 +899,19 @@ public class NMSUtil18 { } public static void removeMeta(ItemStack stack, String tag) { - if (stack == null) return; + if (stack == null) { + return; + } try { Object craft = getHandle(stack); - if (craft == null) return; + if (craft == null) { + return; + } Object tagObject = getTag(craft); - if (tagObject == null) return; + if (tagObject == null) { + return; + } removeMeta(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); @@ -869,13 +919,19 @@ public class NMSUtil18 { } public static String getMeta(ItemStack stack, String tag) { - if (stack == null) return null; + if (stack == null) { + return null; + } String meta = null; try { Object craft = getHandle(stack); - if (craft == null) return null; + if (craft == null) { + return null; + } Object tagObject = getTag(craft); - if (tagObject == null) return null; + if (tagObject == null) { + return null; + } meta = (String) class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); @@ -884,12 +940,18 @@ public class NMSUtil18 { } public static void setMeta(ItemStack stack, String tag, String value) { - if (stack == null) return; + if (stack == null) { + return; + } try { Object craft = getHandle(stack); - if (craft == null) return; + if (craft == null) { + return; + } Object tagObject = getTag(craft); - if (tagObject == null) return; + if (tagObject == null) { + return; + } class_NBTTagCompound_setStringMethod.invoke(tagObject, tag, value); } catch (Throwable ex) { ex.printStackTrace(); @@ -897,13 +959,19 @@ public class NMSUtil18 { } public static void addGlow(ItemStack stack) { - if (stack == null) return; + if (stack == null) { + return; + } try { Object craft = getHandle(stack); - if (craft == null) return; + if (craft == null) { + return; + } Object tagObject = getTag(craft); - if (tagObject == null) return; + if (tagObject == null) { + return; + } final Object enchList = class_NBTTagList.newInstance(); class_NBTTagCompound_setMethod.invoke(tagObject, "ench", enchList); @@ -916,7 +984,9 @@ public class NMSUtil18 { } public static void removeGlow(ItemStack stack) { - if (stack == null) return; + if (stack == null) { + return; + } Collection enchants = stack.getEnchantments().keySet(); for (Enchantment enchant : enchants) { @@ -925,9 +995,13 @@ public class NMSUtil18 { try { Object craft = getHandle(stack); - if (craft == null) return; + if (craft == null) { + return; + } Object tagObject = getTag(craft); - if (tagObject == null) return; + if (tagObject == null) { + return; + } // Testing Glow API based on ItemMetadata storage Object bukkitData = getNode(stack, "bukkit"); @@ -940,13 +1014,19 @@ public class NMSUtil18 { } public static void makeUnbreakable(ItemStack stack) { - if (stack == null) return; + if (stack == null) { + return; + } try { Object craft = getHandle(stack); - if (craft == null) return; + if (craft == null) { + return; + } Object tagObject = getTag(craft); - if (tagObject == null) return; + if (tagObject == null) { + return; + } Object unbreakableFlag = null; if (class_NBTTagByte_constructor != null) { @@ -965,13 +1045,19 @@ public class NMSUtil18 { } public static void hideFlags(ItemStack stack, byte flags) { - if (stack == null) return; + if (stack == null) { + return; + } try { Object craft = getHandle(stack); - if (craft == null) return; + if (craft == null) { + return; + } Object tagObject = getTag(craft); - if (tagObject == null) return; + if (tagObject == null) { + return; + } Object hideFlag = null; if (class_NBTTagByte_constructor != null) { @@ -987,10 +1073,14 @@ public class NMSUtil18 { 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; + if (world == null) { + return false; + } try { Object worldHandle = getHandle(world); - if (worldHandle == null) return false; + 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); @@ -1059,7 +1149,9 @@ public class NMSUtil18 { } public static Object setStringList(Object nbtBase, String tag, Collection values) { - if (nbtBase == null) return null; + if (nbtBase == null) { + return null; + } Object listMeta = null; try { listMeta = class_NBTTagList.newInstance(); @@ -1078,7 +1170,9 @@ public class NMSUtil18 { } public static ItemStack getItem(Object itemTag) { - if (itemTag == null) return null; + if (itemTag == null) { + return null; + } ItemStack item = null; try { Object nmsStack = class_ItemStack_createStackMethod.invoke(null, itemTag); @@ -1138,10 +1232,14 @@ public class NMSUtil18 { } public static void clearItems(Location location) { - if (location == null) return; + if (location == null) { + return; + } try { World world = location.getWorld(); - if (world == null) return; + if (world == null) { + return; + } Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); if (tileEntity != null) { @@ -1161,13 +1259,19 @@ public class NMSUtil18 { } public static void setTileEntityData(Location location, Object data) { - if (location == null || data == null) return; + if (location == null || data == null) { + return; + } try { World world = location.getWorld(); - if (world == null) return; + if (world == null) { + return; + } Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (tileEntity == null) return; + if (tileEntity == null) { + return; + } class_NBTTagCompound_setIntMethod.invoke(data, "x", location.getBlockX()); class_NBTTagCompound_setIntMethod.invoke(data, "y", location.getBlockY()); diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java index 09b2a4c..de900f4 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java @@ -678,18 +678,24 @@ public class NMSUtil19 { 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"); + 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"); + 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"); + if (class_EntityArmorStand_disabledSlotsField.getType() != Integer.TYPE) { + throw new Exception("Looks like 1.9"); + } } catch (Throwable ignore2) { try { // 1.9.4 @@ -742,7 +748,9 @@ public class NMSUtil19 { 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"); + 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 @@ -954,7 +962,9 @@ public class NMSUtil19 { } public static Object getHandle(org.bukkit.World world) { - if (world == null) return null; + if (world == null) { + return null; + } Object handle = null; try { handle = class_CraftWorld_getHandleMethod.invoke(world); @@ -965,7 +975,9 @@ public class NMSUtil19 { } public static Object getHandle(org.bukkit.entity.Entity entity) { - if (entity == null) return null; + if (entity == null) { + return null; + } Object handle = null; try { handle = class_CraftEntity_getHandleMethod.invoke(entity); @@ -976,7 +988,9 @@ public class NMSUtil19 { } public static Object getHandle(org.bukkit.entity.LivingEntity entity) { - if (entity == null) return null; + if (entity == null) { + return null; + } Object handle = null; try { handle = class_CraftLivingEntity_getHandleMethod.invoke(entity); @@ -1025,7 +1039,9 @@ public class NMSUtil19 { World sourceWorld = source.getWorld(); for (Player player : players) { Location location = player.getLocation(); - if (!location.getWorld().equals(sourceWorld)) continue; + if (!location.getWorld().equals(sourceWorld)) { + continue; + } if (location.distanceSquared(source) <= viewDistanceSquared) { sendPacket(player, packet); } @@ -1064,11 +1080,15 @@ public class NMSUtil19 { public static org.bukkit.entity.Entity getBukkitEntity(Object entity) { - if (entity == null) return null; + if (entity == null) { + return null; + } try { Method getMethod = entity.getClass().getMethod("getBukkitEntity"); Object bukkitEntity = getMethod.invoke(entity); - if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) return null; + if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) { + return null; + } return (org.bukkit.entity.Entity)bukkitEntity; } catch (Throwable ex) { ex.printStackTrace(); @@ -1098,7 +1118,9 @@ public class NMSUtil19 { } public static ItemStack getCopy(ItemStack stack) { - if (stack == null) return null; + if (stack == null) { + return null; + } try { Object craft = getNMSCopy(stack); @@ -1111,7 +1133,9 @@ public class NMSUtil19 { } public static ItemStack makeReal(ItemStack stack) { - if (stack == null) return null; + if (stack == null) { + return null; + } Object nmsStack = getHandle(stack); if (nmsStack == null) { stack = getCopy(stack); @@ -1146,7 +1170,9 @@ public class NMSUtil19 { Object tag = null; try { Object mcItemStack = getHandle(itemStack); - if (mcItemStack == null) return null; + if (mcItemStack == null) { + return null; + } tag = class_ItemStack_tagField.get(mcItemStack); } catch (Throwable ex) { ex.printStackTrace(); @@ -1155,13 +1181,19 @@ public class NMSUtil19 { } public static Object getNode(ItemStack stack, String tag) { - if (NMSUtil19.isEmpty(stack)) return null; + if (NMSUtil19.isEmpty(stack)) { + return null; + } Object meta = null; try { Object craft = getHandle(stack); - if (craft == null) return null; + if (craft == null) { + return null; + } Object tagObject = getTag(craft); - if (tagObject == null) return null; + if (tagObject == null) { + return null; + } meta = class_NBTTagCompound_getMethod.invoke(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); @@ -1170,7 +1202,9 @@ public class NMSUtil19 { } public static boolean containsNode(Object nbtBase, String tag) { - if (nbtBase == null) return false; + if (nbtBase == null) { + return false; + } Boolean result = false; try { result = (Boolean)class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); @@ -1181,7 +1215,9 @@ public class NMSUtil19 { } public static Object getNode(Object nbtBase, String tag) { - if (nbtBase == null) return null; + if (nbtBase == null) { + return null; + } Object meta = null; try { meta = class_NBTTagCompound_getMethod.invoke(nbtBase, tag); @@ -1192,7 +1228,9 @@ public class NMSUtil19 { } public static Object createNode(Object nbtBase, String tag) { - if (nbtBase == null) return null; + if (nbtBase == null) { + return null; + } Object meta = null; try { meta = class_NBTTagCompound_getCompoundMethod.invoke(nbtBase, tag); @@ -1204,12 +1242,16 @@ public class NMSUtil19 { } public static Object createNode(ItemStack stack, String tag) { - if (NMSUtil19.isEmpty(stack)) return null; + if (NMSUtil19.isEmpty(stack)) { + return null; + } Object outputObject = getNode(stack, tag); if (outputObject == null) { try { Object craft = getHandle(stack); - if (craft == null) return null; + if (craft == null) { + return null; + } Object tagObject = getTag(craft); if (tagObject == null) { tagObject = class_NBTTagCompound.newInstance(); @@ -1230,7 +1272,9 @@ public class NMSUtil19 { } public static String getMetaString(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) return null; + if (node == null || !class_NBTTagCompound.isInstance(node)) { + return null; + } String meta = null; try { meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag); @@ -1241,7 +1285,9 @@ public class NMSUtil19 { } public static String getMeta(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) return null; + if (node == null || !class_NBTTagCompound.isInstance(node)) { + return null; + } String meta = null; try { meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag); @@ -1252,7 +1298,9 @@ public class NMSUtil19 { } public static Byte getMetaByte(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) return null; + if (node == null || !class_NBTTagCompound.isInstance(node)) { + return null; + } Byte meta = null; try { meta = (Byte)class_NBTTagCompound_getByteMethod.invoke(node, tag); @@ -1263,7 +1311,9 @@ public class NMSUtil19 { } public static Integer getMetaInt(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) return null; + if (node == null || !class_NBTTagCompound.isInstance(node)) { + return null; + } Integer meta = null; try { meta = (Integer)class_NBTTagCompound_getIntMethod.invoke(node, tag); @@ -1274,7 +1324,9 @@ public class NMSUtil19 { } public static Boolean getMetaBoolean(Object node, String tag) { - if (node == null || !class_NBTTagCompound.isInstance(node)) return null; + if (node == null || !class_NBTTagCompound.isInstance(node)) { + return null; + } Boolean meta = null; try { meta = (Boolean)class_NBTTagCompound_getBooleanMethod.invoke(node, tag); @@ -1285,7 +1337,9 @@ public class NMSUtil19 { } public static void setMeta(Object node, String tag, String value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) return; + if (node == null|| !class_NBTTagCompound.isInstance(node)) { + return; + } try { if (value == null || value.length() == 0) { class_NBTTagCompound_removeMethod.invoke(node, tag); @@ -1298,7 +1352,9 @@ public class NMSUtil19 { } public static void setMetaLong(Object node, String tag, long value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) return; + if (node == null|| !class_NBTTagCompound.isInstance(node)) { + return; + } try { class_NBTTagCompound_setLongMethod.invoke(node, tag, value); } catch (Throwable ex) { @@ -1307,7 +1363,9 @@ public class NMSUtil19 { } public static void setMetaBoolean(Object node, String tag, boolean value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) return; + if (node == null|| !class_NBTTagCompound.isInstance(node)) { + return; + } try { class_NBTTagCompound_setBooleanMethod.invoke(node, tag, value); } catch (Throwable ex) { @@ -1316,7 +1374,9 @@ public class NMSUtil19 { } public static void setMetaDouble(Object node, String tag, double value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) return; + if (node == null|| !class_NBTTagCompound.isInstance(node)) { + return; + } try { class_NBTTagCompound_setDoubleMethod.invoke(node, tag, value); } catch (Throwable ex) { @@ -1325,7 +1385,9 @@ public class NMSUtil19 { } public static void setMetaInt(Object node, String tag, int value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) return; + if (node == null|| !class_NBTTagCompound.isInstance(node)) { + return; + } try { class_NBTTagCompound_setIntMethod.invoke(node, tag, value); } catch (Throwable ex) { @@ -1334,7 +1396,9 @@ public class NMSUtil19 { } public static void removeMeta(Object node, String tag) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) return; + if (node == null|| !class_NBTTagCompound.isInstance(node)) { + return; + } try { class_NBTTagCompound_removeMethod.invoke(node, tag); } catch (Throwable ex) { @@ -1343,13 +1407,19 @@ public class NMSUtil19 { } public static void removeMeta(ItemStack stack, String tag) { - if (NMSUtil19.isEmpty(stack)) return; + if (NMSUtil19.isEmpty(stack)) { + return; + } try { Object craft = getHandle(stack); - if (craft == null) return; + if (craft == null) { + return; + } Object tagObject = getTag(craft); - if (tagObject == null) return; + if (tagObject == null) { + return; + } removeMeta(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); @@ -1357,7 +1427,9 @@ public class NMSUtil19 { } public static void setMetaNode(Object node, String tag, Object child) { - if (node == null || !class_NBTTagCompound.isInstance(node)) return; + if (node == null || !class_NBTTagCompound.isInstance(node)) { + return; + } try { if (child == null) { class_NBTTagCompound_removeMethod.invoke(node, tag); @@ -1370,12 +1442,18 @@ public class NMSUtil19 { } public static boolean setMetaNode(ItemStack stack, String tag, Object child) { - if (NMSUtil19.isEmpty(stack)) return false; + if (NMSUtil19.isEmpty(stack)) { + return false; + } try { Object craft = getHandle(stack); - if (craft == null) return false; + if (craft == null) { + return false; + } Object node = getTag(craft); - if (node == null) return false; + if (node == null) { + return false; + } if (child == null) { class_NBTTagCompound_removeMethod.invoke(node, tag); } else { @@ -1390,13 +1468,19 @@ public class NMSUtil19 { } public static String getMetaString(ItemStack stack, String tag) { - if (NMSUtil19.isEmpty(stack)) return null; + if (NMSUtil19.isEmpty(stack)) { + return null; + } String meta = null; try { Object craft = getHandle(stack); - if (craft == null) return null; + if (craft == null) { + return null; + } Object tagObject = getTag(craft); - if (tagObject == null) return null; + if (tagObject == null) { + return null; + } meta = (String)class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); @@ -1405,12 +1489,18 @@ public class NMSUtil19 { } public static void setMeta(ItemStack stack, String tag, String value) { - if (NMSUtil19.isEmpty(stack)) return; + if (NMSUtil19.isEmpty(stack)) { + return; + } try { Object craft = getHandle(stack); - if (craft == null) return; + if (craft == null) { + return; + } Object tagObject = getTag(craft); - if (tagObject == null) return; + if (tagObject == null) { + return; + } class_NBTTagCompound_setStringMethod.invoke(tagObject, tag, value); } catch (Throwable ex) { ex.printStackTrace(); @@ -1418,12 +1508,18 @@ public class NMSUtil19 { } public static void setMetaBoolean(ItemStack stack, String tag, boolean value) { - if (NMSUtil19.isEmpty(stack)) return; + if (NMSUtil19.isEmpty(stack)) { + return; + } try { Object craft = getHandle(stack); - if (craft == null) return; + if (craft == null) { + return; + } Object tagObject = getTag(craft); - if (tagObject == null) return; + if (tagObject == null) { + return; + } setMetaBoolean(tagObject, tag, value); } catch (Throwable ex) { ex.printStackTrace(); @@ -1431,13 +1527,19 @@ public class NMSUtil19 { } public static boolean getMetaBoolean(ItemStack stack, String tag, boolean defaultValue) { - if (NMSUtil19.isEmpty(stack)) return defaultValue; + if (NMSUtil19.isEmpty(stack)) { + return defaultValue; + } boolean result = defaultValue; try { Object craft = getHandle(stack); - if (craft == null) return defaultValue; + if (craft == null) { + return defaultValue; + } Object tagObject = getTag(craft); - if (tagObject == null) return defaultValue; + if (tagObject == null) { + return defaultValue; + } Boolean value = getMetaBoolean(tagObject, tag); result = value == null ? defaultValue : value; } catch (Throwable ex) { @@ -1447,7 +1549,9 @@ public class NMSUtil19 { } public static void addGlow(ItemStack stack) { - if (NMSUtil19.isEmpty(stack)) return; + if (NMSUtil19.isEmpty(stack)) { + return; + } ItemMeta meta = stack.getItemMeta(); meta.addEnchant(Enchantment.LUCK, 1, true); @@ -1455,7 +1559,9 @@ public class NMSUtil19 { } public static void removeGlow(ItemStack stack) { - if (NMSUtil19.isEmpty(stack)) return; + if (NMSUtil19.isEmpty(stack)) { + return; + } ItemMeta meta = stack.getItemMeta(); if (meta.hasEnchant(Enchantment.LUCK)) { @@ -1465,13 +1571,19 @@ public class NMSUtil19 { } public static boolean isUnbreakable(ItemStack stack) { - if (NMSUtil19.isEmpty(stack)) return false; + if (NMSUtil19.isEmpty(stack)) { + return false; + } Boolean unbreakableFlag = null; try { Object craft = getHandle(stack); - if (craft == null) return false; + if (craft == null) { + return false; + } Object tagObject = getTag(craft); - if (tagObject == null) return false; + if (tagObject == null) { + return false; + } unbreakableFlag = getMetaBoolean(tagObject, "Unbreakable"); } catch (Throwable ignored) { @@ -1481,13 +1593,19 @@ public class NMSUtil19 { } public static void makeUnbreakable(ItemStack stack) { - if (NMSUtil19.isEmpty(stack)) return; + if (NMSUtil19.isEmpty(stack)) { + return; + } try { Object craft = getHandle(stack); - if (craft == null) return; + if (craft == null) { + return; + } Object tagObject = getTag(craft); - if (tagObject == null) return; + if (tagObject == null) { + return; + } Object unbreakableFlag = null; unbreakableFlag = class_NBTTagByte_constructor.newInstance((byte) 1); @@ -1502,13 +1620,19 @@ public class NMSUtil19 { } public static void hideFlags(ItemStack stack, byte flags) { - if (NMSUtil19.isEmpty(stack)) return; + if (NMSUtil19.isEmpty(stack)) { + return; + } try { Object craft = getHandle(stack); - if (craft == null) return; + if (craft == null) { + return; + } Object tagObject = getTag(craft); - if (tagObject == null) return; + if (tagObject == null) { + return; + } Object hideFlag = null; hideFlag = class_NBTTagByte_constructor.newInstance(flags); @@ -1520,10 +1644,14 @@ public class NMSUtil19 { 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; + if (world == null) { + return false; + } try { Object worldHandle = getHandle(world); - if (worldHandle == null) return false; + 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); @@ -1593,7 +1721,9 @@ public class NMSUtil19 { } public static Object setStringList(Object nbtBase, String tag, Collection values) { - if (nbtBase == null) return null; + if (nbtBase == null) { + return null; + } Object listMeta = null; try { listMeta = class_NBTTagList.newInstance(); @@ -1612,7 +1742,9 @@ public class NMSUtil19 { } public static ItemStack getItem(Object itemTag) { - if (itemTag == null) return null; + if (itemTag == null) { + return null; + } ItemStack item = null; try { Object nmsStack = null; @@ -1651,7 +1783,9 @@ public class NMSUtil19 { } public static Object getTileEntityData(Location location) { - if (class_CraftWorld_getTileEntityAtMethod == null || class_TileEntity_saveMethod == null) return null; + if (class_CraftWorld_getTileEntityAtMethod == null || class_TileEntity_saveMethod == null) { + return null; + } Object data = null; try { World world = location.getWorld(); @@ -1667,7 +1801,9 @@ public class NMSUtil19 { } public static Object getTileEntity(Location location) { - if (class_CraftWorld_getTileEntityAtMethod == null) return null; + if (class_CraftWorld_getTileEntityAtMethod == null) { + return null; + } Object tileEntity = null; try { World world = location.getWorld(); @@ -1679,11 +1815,17 @@ public class NMSUtil19 { } 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; + 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; + if (world == null) { + return; + } Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); if (tileEntity != null) { @@ -1704,15 +1846,23 @@ public class NMSUtil19 { } public static void setTileEntityData(Location location, Object data) { - if (class_TileEntity_loadMethod == null || class_TileEntity_updateMethod == null || class_CraftWorld_getTileEntityAtMethod == null) return; + if (class_TileEntity_loadMethod == null || class_TileEntity_updateMethod == null || class_CraftWorld_getTileEntityAtMethod == null) { + return; + } - if (location == null || data == null) return; + if (location == null || data == null) { + return; + } try { World world = location.getWorld(); - if (world == null) return; + if (world == null) { + return; + } Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (tileEntity == null) return; + if (tileEntity == null) { + return; + } class_NBTTagCompound_setIntMethod.invoke(data, "x", location.getBlockX()); class_NBTTagCompound_setIntMethod.invoke(data, "y", location.getBlockY()); @@ -1726,7 +1876,9 @@ public class NMSUtil19 { } public static Vector getPosition(Object entityData, String tag) { - if (class_NBTTagList_getDoubleMethod == null) return null; + 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); @@ -1777,7 +1929,9 @@ public class NMSUtil19 { public static Map getMap(ConfigurationSection section) { - if (section == null) return null; + if (section == null) { + return null; + } if (section instanceof MemorySection) { try { @@ -1801,11 +1955,17 @@ public class NMSUtil19 { } public static boolean isEmpty(ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) return true; - if (class_ItemStack_isEmptyMethod == null) return false; + 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; + if (handle == null) { + return false; + } return (Boolean)class_ItemStack_isEmptyMethod.invoke(handle); } catch (Throwable ex) { ex.printStackTrace(); diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtils.java b/src/main/java/me/skymc/taboolib/nms/NMSUtils.java index b5656d0..7ec6521 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtils.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtils.java @@ -142,7 +142,7 @@ public class NMSUtils { } public static Field getFieldWithException(Class clazz, String name) throws Exception { - for (Field field : clazz.getDeclaredFields()) + for (Field field : clazz.getDeclaredFields()) { if (field.getName().equals(name)) { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); @@ -152,7 +152,8 @@ public class NMSUtils { modifiersField.setInt(field, modifiers); return field; } - for (Field field : clazz.getFields()) + } + for (Field field : clazz.getFields()) { if (field.getName().equals(name)) { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); @@ -162,6 +163,7 @@ public class NMSUtils { modifiersField.setInt(field, modifiers); return field; } + } throw new Exception("Field Not Found"); } @@ -194,7 +196,7 @@ public class NMSUtils { } public static Field getFieldOfTypeWithException(Class clazz, Class type, String name) throws Exception { - for (Field field : clazz.getDeclaredFields()) + for (Field field : clazz.getDeclaredFields()) { if (field.getName().equals(name) && field.getType().equals(type)) { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); @@ -204,7 +206,8 @@ public class NMSUtils { modifiersField.setInt(field, modifiers); return field; } - for (Field field : clazz.getFields()) + } + for (Field field : clazz.getFields()) { if (field.getName().equals(name) && field.getType().equals(type)) { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); @@ -214,6 +217,7 @@ public class NMSUtils { modifiersField.setInt(field, modifiers); return field; } + } throw new Exception("Field Not Found"); } @@ -252,10 +256,11 @@ public class NMSUtils { public static Field getLastFieldOfTypeWithException(Class clazz, Class type) throws Exception { Field field = null; - for (Field f : clazz.getDeclaredFields()) + for (Field f : clazz.getDeclaredFields()) { if (f.getType().equals(type)) { field = f; } + } if (field == null) { throw new Exception("Field Not Found"); } @@ -278,16 +283,18 @@ public class NMSUtils { } public static Method getMethodWithException(Class clazz, String name, Class... args) throws Exception { - for (Method m : clazz.getDeclaredMethods()) + 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()) + } + 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"); } @@ -300,18 +307,23 @@ public class NMSUtils { } public static boolean ClassListEqual(Class[] l1, Class[] l2) { - if (l1.length != l2.length) + if (l1.length != l2.length) { return false; - for (int i = 0; i < l1.length; i++) - if (l1[i] != l2[i]) + } + for (int i = 0; i < l1.length; i++) { + if (l1[i] != l2[i]) { return false; + } + } return true; } public static Class getInnerClassWithException(Class c, String className) throws Exception { - for (Class cl : c.getDeclaredClasses()) - if (cl.getSimpleName().equals(className)) + for (Class cl : c.getDeclaredClasses()) { + if (cl.getSimpleName().equals(className)) { return cl; + } + } throw new Exception("Inner Class Not Found"); } @@ -333,16 +345,18 @@ public class NMSUtils { } public static Constructor getConstructor(Class clazz, Class... args) throws Exception { - for (Constructor c : clazz.getDeclaredConstructors()) + 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()) + } + 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"); } 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 index b471f13..1353ae8 100644 --- a/src/main/java/me/skymc/taboolib/nms/item/impl/_164ItemUtils.java +++ b/src/main/java/me/skymc/taboolib/nms/item/impl/_164ItemUtils.java @@ -1,1247 +1,1308 @@ package me.skymc.taboolib.nms.item.impl; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; - -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - 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; -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); +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 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; - } + } + 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(); + } } - 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{ + } 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()){ + 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); + 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){ + } 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){ + } + + 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){ + } + + 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; - } + } + + 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 index c29fc3c..371129d 100644 --- a/src/main/java/me/skymc/taboolib/nms/item/impl/_1710ItemUtils.java +++ b/src/main/java/me/skymc/taboolib/nms/item/impl/_1710ItemUtils.java @@ -683,8 +683,9 @@ public class _1710ItemUtils implements IDabItemUtils{ ret = nbtiad.get(nbt); break; } - if(ret == null) - return null; + if(ret == null) { + return null; + } return new JSONArray(new Object[]{ i, ret }); } @@ -1009,8 +1010,9 @@ public class _1710ItemUtils implements IDabItemUtils{ 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; + if(i != i1) { + return false; + } switch(i){ case NBTConstants.TYPE_BYTE: Byte b = (byte)nbtbd.get(tag); @@ -1062,15 +1064,18 @@ public class _1710ItemUtils implements IDabItemUtils{ 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; + 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; + if(!compareBaseTag(o, o1)) { + return false; + } } return true; } @@ -1080,8 +1085,9 @@ public class _1710ItemUtils implements IDabItemUtils{ 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.size() != list1.size()) { + return false; + } Collections.sort(list); Collections.sort(list1); Iterator it = list.iterator(); @@ -1089,8 +1095,9 @@ public class _1710ItemUtils implements IDabItemUtils{ while(it.hasNext() && it1.hasNext()){ Object o = it.next(); Object o1 = it1.next(); - if(!compareBaseTag(o, o1)) - return false; + if(!compareBaseTag(o, o1)) { + return false; + } } return true; } @@ -1191,8 +1198,9 @@ public class _1710ItemUtils implements IDabItemUtils{ int durability = jo.getInt("durability"); ItemStack is = new ItemStack(material, amount, (short)durability); JSONObject jo1 = jo.getJSONObject("tag"); - if(jo1.length() == 0) - return is; + if(jo1.length() == 0) { + return is; + } Object tag = convertJSONToCompoundTag(jo1); Object nmis = getNMSCopy(is); setTag(nmis, tag); 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 index 197c87a..e36b234 100644 --- a/src/main/java/me/skymc/taboolib/nms/item/impl/_194ItemUtils.java +++ b/src/main/java/me/skymc/taboolib/nms/item/impl/_194ItemUtils.java @@ -683,8 +683,9 @@ public class _194ItemUtils implements IDabItemUtils{ ret = nbtiad.get(nbt); break; } - if(ret == null) - return null; + if(ret == null) { + return null; + } return new JSONArray(new Object[]{ i, ret }); } @@ -1012,8 +1013,9 @@ public class _194ItemUtils implements IDabItemUtils{ 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; + if(i != i1) { + return false; + } switch(i){ case NBTConstants.TYPE_BYTE: Byte b = (byte)nbtbd.get(tag); @@ -1065,15 +1067,18 @@ public class _194ItemUtils implements IDabItemUtils{ 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; + 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; + if(!compareBaseTag(o, o1)) { + return false; + } } return true; } @@ -1083,10 +1088,12 @@ public class _194ItemUtils implements IDabItemUtils{ 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; + 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(); @@ -1103,8 +1110,9 @@ public class _194ItemUtils implements IDabItemUtils{ break; } } - if(!cont) - return false; + if(!cont) { + return false; + } } return copy.isEmpty() && copy1.isEmpty(); } @@ -1203,8 +1211,9 @@ public class _194ItemUtils implements IDabItemUtils{ int durability = jo.getInt("durability"); ItemStack is = new ItemStack(material, amount, (short)durability); JSONObject jo1 = jo.getJSONObject("tag"); - if(jo1.length() == 0) - return is; + if(jo1.length() == 0) { + return is; + } Object tag = convertJSONToCompoundTag(jo1); Object nmis = getNMSCopy(is); setTag(nmis, tag); diff --git a/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java b/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java index b6ba3af..72dc5e8 100644 --- a/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java +++ b/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java @@ -120,28 +120,30 @@ public class PluginUtils { } else { Iterator attributeIterator = ((Map) commandNext.getValue()).entrySet().iterator(); - while (true) while (true) { - Entry attributeNext; - if (!attributeIterator.hasNext()) { - continue label55; - } - - attributeNext = (Entry) attributeIterator.next(); - while (!attributeNext.getKey().equals("aliases")) { + while (true) { + while (true) { + Entry attributeNext; if (!attributeIterator.hasNext()) { continue label55; } attributeNext = (Entry) attributeIterator.next(); - } + while (!"aliases".equals(attributeNext.getKey())) { + if (!attributeIterator.hasNext()) { + continue label55; + } - Object aliases = attributeNext.getValue(); - if (aliases instanceof String) { - if (((String) aliases).equalsIgnoreCase(command)) { - plugins.add(plugin.getName()); + attributeNext = (Entry) attributeIterator.next(); + } + + Object aliases = attributeNext.getValue(); + if (aliases instanceof String) { + if (((String) aliases).equalsIgnoreCase(command)) { + plugins.add(plugin.getName()); + } + } else { + ((List) aliases).stream().filter(str -> str.equalsIgnoreCase(command)).map(str -> plugin.getName()).forEach(plugins::add); } - } else { - ((List) aliases).stream().filter(str -> str.equalsIgnoreCase(command)).map(str -> plugin.getName()).forEach(plugins::add); } } } diff --git a/src/main/java/me/skymc/taboolib/sound/SoundPack.java b/src/main/java/me/skymc/taboolib/sound/SoundPack.java index af616d6..1b7490b 100644 --- a/src/main/java/me/skymc/taboolib/sound/SoundPack.java +++ b/src/main/java/me/skymc/taboolib/sound/SoundPack.java @@ -61,6 +61,7 @@ public class SoundPack { } } + @Override public String toString() { return sound.name() + "-" + a + "-" + b; } diff --git a/src/main/java/me/skymc/taboolib/string/StringUtils.java b/src/main/java/me/skymc/taboolib/string/StringUtils.java index 8ad28f5..be0359e 100644 --- a/src/main/java/me/skymc/taboolib/string/StringUtils.java +++ b/src/main/java/me/skymc/taboolib/string/StringUtils.java @@ -72,21 +72,22 @@ public class StringUtils { int[][] matrix = new int[m + 1][n + 1]; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { - if (chars_strA[i - 1] == chars_strB[j - 1]) + if (chars_strA[i - 1] == chars_strB[j - 1]) { matrix[i][j] = matrix[i - 1][j - 1] + 1; - else + } else { matrix[i][j] = Math.max(matrix[i][j - 1], matrix[i - 1][j]); + } } } char[] result = new char[matrix[m][n]]; int currentIndex = result.length - 1; while (matrix[m][n] != 0) { - if (matrix[n] == matrix[n - 1]) + if (matrix[n] == matrix[n - 1]) { n--; - else if (matrix[m][n] == matrix[m - 1][n]) + } else if (matrix[m][n] == matrix[m - 1][n]) { m--; - else { + } else { result[currentIndex] = chars_strA[m - 1]; currentIndex--; n--; diff --git a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java index 5a8c2ff..97ab5ff 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java +++ b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java @@ -82,7 +82,7 @@ public class Language2Book implements Language2Line { // 遍历内容 for (String line : list) { // 翻页 - if (line.equals("[page]")) { + if ("[page]".equals(line)) { book.addPages(page.build()); page = new PageBuilder(); } diff --git a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Json.java b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Json.java index 7ba9745..38a0a82 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Json.java +++ b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Json.java @@ -100,7 +100,7 @@ public class Language2Json implements Language2Line { clickEvent = new OpenUrlEvent(message.substring(KEY_URL.length())); } // 换行 - else if (message.equals("[break]")) { + else if ("[break]".equals(message)) { append(current, clickEvent, hoverEvent); // 删除动作 clickEvent = null; diff --git a/src/main/java/me/skymc/taboolib/thread/ThreadUtils.java b/src/main/java/me/skymc/taboolib/thread/ThreadUtils.java index 91af79d..2f660cf 100644 --- a/src/main/java/me/skymc/taboolib/thread/ThreadUtils.java +++ b/src/main/java/me/skymc/taboolib/thread/ThreadUtils.java @@ -2,6 +2,9 @@ package me.skymc.taboolib.thread; import java.util.LinkedList; +/** + * @author sky + */ public class ThreadUtils { private static PoolWorker[] threads; diff --git a/src/main/java/me/skymc/tlm/command/TLMCommands.java b/src/main/java/me/skymc/tlm/command/TLMCommands.java index ebab347..5ef1819 100644 --- a/src/main/java/me/skymc/tlm/command/TLMCommands.java +++ b/src/main/java/me/skymc/tlm/command/TLMCommands.java @@ -17,7 +17,7 @@ public class TLMCommands implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] args) { - if (args.length == 0 || args[0].equalsIgnoreCase("help")) { + if (args.length == 0 || "help".equalsIgnoreCase(args[0])) { if (sender.hasPermission("taboolib.admin")) { TLM.getInst().getLanguage().get("COMMAND-HELP").send(sender); } else { @@ -26,7 +26,7 @@ public class TLMCommands implements CommandExecutor { } // 重载 - else if (args[0].equalsIgnoreCase("reload")) { + else if ("reload".equalsIgnoreCase(args[0])) { if (sender.hasPermission("taboolib.admin")) { new TLMReloadCommand(sender, args); } else { @@ -35,7 +35,7 @@ public class TLMCommands implements CommandExecutor { } // 列出 - else if (args[0].equalsIgnoreCase("list")) { + else if ("list".equalsIgnoreCase(args[0])) { if (sender.hasPermission("taboolib.admin")) { new TLMListCommand(sender, args); } else { @@ -44,7 +44,7 @@ public class TLMCommands implements CommandExecutor { } // InventorySave 模块 - else if (args[0].equalsIgnoreCase("inv")) { + else if ("inv".equalsIgnoreCase(args[0])) { if (sender.hasPermission("taboolib.admin")) { new TLMInvCommand(sender, args); } else { @@ -53,7 +53,7 @@ public class TLMCommands implements CommandExecutor { } // Kit 模块 - else if (args[0].equalsIgnoreCase("kit")) { + else if ("kit".equalsIgnoreCase(args[0])) { new TLMKitCommand(sender, args); } else { TLM.getInst().getLanguage().get("COMMAND-ERROR").send(sender); diff --git a/src/main/java/me/skymc/tlm/command/sub/TLMInvCommand.java b/src/main/java/me/skymc/tlm/command/sub/TLMInvCommand.java index 63bd1cc..e611c38 100644 --- a/src/main/java/me/skymc/tlm/command/sub/TLMInvCommand.java +++ b/src/main/java/me/skymc/tlm/command/sub/TLMInvCommand.java @@ -43,12 +43,12 @@ public class TLMInvCommand extends SubCommand { } // 列出背包 - else if (args[1].equalsIgnoreCase("list")) { + else if ("list".equalsIgnoreCase(args[1])) { TLM.getInst().getLanguage().get("INV-LIST").addPlaceholder("$name", moduleInventorySave.getInventorys().toString()).send(sender); } // 查看背包 - else if (args[1].equalsIgnoreCase("info")) { + else if ("info".equalsIgnoreCase(args[1])) { // 如果是后台 if (!(sender instanceof Player)) { TLM.getInst().getLanguage().get("INV-CONSOLE").send(sender); @@ -108,7 +108,7 @@ public class TLMInvCommand extends SubCommand { } // 保存背包 - else if (args[1].equalsIgnoreCase("save")) { + else if ("save".equalsIgnoreCase(args[1])) { // 如果是后台 if (!(sender instanceof Player)) { TLM.getInst().getLanguage().get("INV-CONSOLE").send(sender); @@ -132,7 +132,7 @@ public class TLMInvCommand extends SubCommand { } // 覆盖背包 - else if (args[1].equalsIgnoreCase("paste")) { + else if ("paste".equalsIgnoreCase(args[1])) { // 判断长度 if (args.length < 3) { TLM.getInst().getLanguage().get("INV-NAME").send(sender); @@ -175,7 +175,7 @@ public class TLMInvCommand extends SubCommand { } // 删除背包 - else if (args[1].equalsIgnoreCase("delete")) { + else if ("delete".equalsIgnoreCase(args[1])) { // 判断长度 if (args.length < 3) { TLM.getInst().getLanguage().get("INV-NAME").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 index 42949ee..42ded4d 100644 --- a/src/main/java/me/skymc/tlm/command/sub/TLMKitCommand.java +++ b/src/main/java/me/skymc/tlm/command/sub/TLMKitCommand.java @@ -38,7 +38,7 @@ public class TLMKitCommand extends SubCommand { TLM.getInst().getLanguage().get("KIT-EMPTY").send(sender); } - else if (args[1].equalsIgnoreCase("list")) { + else if ("list".equalsIgnoreCase(args[1])) { // 判断权限 if (!sender.hasPermission("taboolib.kit.list")) { TLM.getInst().getLanguage().get("NOPERMISSION-KIT-LIST").send(sender); @@ -50,7 +50,7 @@ public class TLMKitCommand extends SubCommand { } } - else if (args[1].equalsIgnoreCase("reward")) { + else if ("reward".equalsIgnoreCase(args[1])) { // 判断权限 if (!sender.hasPermission("taboolib.kit.reward")) { TLM.getInst().getLanguage().get("NOPERMISSION-KIT-REWARD").send(sender); @@ -130,7 +130,7 @@ public class TLMKitCommand extends SubCommand { // 提示信息 TLM.getInst().getLanguage().get("KIT-SUCCESS").addPlaceholder("$kit", args[2]).send(sender); } - else if (args[1].equalsIgnoreCase("reset")) { + else if ("reset".equalsIgnoreCase(args[1])) { // 判断权限 if (!sender.hasPermission("taboolib.kit.reset")) { TLM.getInst().getLanguage().get("NOPERMISSION-KIT-RESET").send(sender); diff --git a/src/main/java/me/skymc/tlm/command/sub/TLMReloadCommand.java b/src/main/java/me/skymc/tlm/command/sub/TLMReloadCommand.java index 602f57d..fa82fd6 100644 --- a/src/main/java/me/skymc/tlm/command/sub/TLMReloadCommand.java +++ b/src/main/java/me/skymc/tlm/command/sub/TLMReloadCommand.java @@ -24,12 +24,12 @@ public class TLMReloadCommand extends SubCommand { MsgUtils.send(sender, "&4参数错误。"); } - else if (args[1].equalsIgnoreCase("tlm")) { + else if ("tlm".equalsIgnoreCase(args[1])) { TLM.getInst().reloadConfig(); MsgUtils.send(sender, "&fTLM &7配置文件已重载。"); } - else if (args[1].equalsIgnoreCase("all")) { + else if ("all".equalsIgnoreCase(args[1])) { TabooLibraryModule.getInst().reloadConfig(); MsgUtils.send(sender, "所有模块配置文件已重载。"); } diff --git a/src/main/java/me/skymc/tlm/module/sub/ModuleCommandChanger.java b/src/main/java/me/skymc/tlm/module/sub/ModuleCommandChanger.java index e476392..b23a059 100644 --- a/src/main/java/me/skymc/tlm/module/sub/ModuleCommandChanger.java +++ b/src/main/java/me/skymc/tlm/module/sub/ModuleCommandChanger.java @@ -27,7 +27,7 @@ public class ModuleCommandChanger implements ITabooLibraryModule, Listener { // 判断命令 if (e.getMessage().startsWith(key)) { // 判断执行方式 - if (!getConfig().contains("Commands." + id + ".ReplaceMode") || getConfig().getString("Commands." + id + ".ReplaceMode").equals("PLAYER")) { + 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; @@ -45,7 +45,7 @@ public class ModuleCommandChanger implements ITabooLibraryModule, Listener { // 判断命令 if (e.getCommand().startsWith(key)) { // 判断执行方式 - if (!getConfig().contains("Commands." + id + ".ReplaceMode") || getConfig().getString("Commands." + id + ".ReplaceMode").equals("CONSOLE")) { + 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 index 3fe5b07..b6f71a0 100644 --- a/src/main/java/me/skymc/tlm/module/sub/ModuleInventorySave.java +++ b/src/main/java/me/skymc/tlm/module/sub/ModuleInventorySave.java @@ -3,7 +3,6 @@ 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.message.MsgUtils; import me.skymc.taboolib.playerdata.DataUtils; import me.skymc.tlm.TLM; import me.skymc.tlm.annotation.DisableConfig; @@ -96,11 +95,11 @@ public class ModuleInventorySave implements ITabooLibraryModule, Listener { // 如果原本有物品 if (!ItemUtils.isNull(player.getInventory().getItem(i))) { // 跳过 - if (module.equalsIgnoreCase("-b")) { + if ("-b".equalsIgnoreCase(module)) { continue; } // 给予 - else if (module.equalsIgnoreCase("-a")) { + else if ("-a".equalsIgnoreCase(module)) { otherItem.add(item); continue; } diff --git a/src/main/java/org/javalite/activejdbc/MetaModel.java b/src/main/java/org/javalite/activejdbc/MetaModel.java index 3eaa97b..55657bf 100644 --- a/src/main/java/org/javalite/activejdbc/MetaModel.java +++ b/src/main/java/org/javalite/activejdbc/MetaModel.java @@ -64,8 +64,9 @@ public class MetaModel implements Serializable { } static Map getTableNamesMap() { - if (shardingTableNamesTL.get() == null) + if (shardingTableNamesTL.get() == null) { shardingTableNamesTL.set(new HashMap<>()); + } return shardingTableNamesTL.get(); } @@ -274,8 +275,9 @@ public class MetaModel implements Serializable { * @return all attribute names. */ protected Set getAttributeNames() { - if (columnMetadata == null || columnMetadata.isEmpty()) + if (columnMetadata == null || columnMetadata.isEmpty()) { throw new InitException("Failed to find table: " + getTableName()); + } return Collections.unmodifiableSet(columnMetadata.keySet()); } @@ -378,7 +380,9 @@ public class MetaModel implements Serializable { protected boolean hasAssociation(Class targetClass, Class associationClass) { for (Association association : associations) { if (association.getTargetClass().equals(targetClass) && - association.getClass().equals(associationClass)) return true; + association.getClass().equals(associationClass)) { + return true; + } } return false; } @@ -471,8 +475,9 @@ public class MetaModel implements Serializable { * @return Provides column metadata map, keyed by attribute names. */ public Map getColumnMetadata() { - if (columnMetadata == null || columnMetadata.isEmpty()) + if (columnMetadata == null || columnMetadata.isEmpty()) { throw new InitException("Failed to find table: " + getTableName()); + } return Collections.unmodifiableMap(columnMetadata); } diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 49ab9ab..c4649cd 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -90,6 +90,16 @@ UPDATETASK: - '&7 开源地址: &fhttps://github.com/Bkm016/TabooLib/' - '&8####################################################' +MYSQL-CONNECTION: + FALL-NOTFOUND-DRIVE: '&7驱动器获取失败, 无法连接到数据库' + FALL-NOTFOUND-CONNECTION: '&7警告! 数据库尚未连接, 请检查配置文件后重启服务器! ({0})' + FALL-COMMAND-NORMAL: '&4数据库命令执行出错, 错误原因: &c{0}' + FALL-COMMAND-DETAIL: '&4数据库命令执行出错, 错误代码: &c{0}&4, 错误原因: &c{1}' + SUCCESS-REGISTERED: '&7已向书库注册插件 &f{0}&7 的数据库连接' + SUCCESS-REGISTERED-LISTENER: '&7启动数据库连接监控' + NOTIFY-CONNECTING: '&7正在连接数据库, 地址: &f{0}' + NOTIFY-CONNECTED: '数据库连接成功 ({0}ms)' + TABOOLIB-MODULE: SUCCESS-LOADED: '&7载入 &f{0} &7个 &fTLM &7模块' FALL-LOADED: '&4模块载入异常: &c{0}&4, 模块: &c{1}&4, 位于: &c{2}' @@ -404,6 +414,7 @@ COMMANDS: 0: '名称' INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4不存在' INVALID-PLUGIN-IGNORED: '&8[&3&lTabooLib&8] &4插件 &c{0} &4无法操作' + TRY-RELOAD: '&8[&3&lTabooLib&8] &7尝试重载插件...' DATABASE: CONNECTION-ESTABLISHED: '成功连接到 {0} 数据库,连接池大小 {1}'