diff --git a/TabooLib.iml b/TabooLib.iml new file mode 100644 index 0000000..5c1eac3 --- /dev/null +++ b/TabooLib.iml @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index c56e5db..a319200 100644 --- a/pom.xml +++ b/pom.xml @@ -77,11 +77,6 @@ asm 6.1.1 - - org.projectlombok - lombok - 1.16.20 - bukkit bukkit1_12 diff --git a/src/main/java/com/ilummc/tlib/ExampleMain.java b/src/main/java/com/ilummc/tlib/ExampleMain.java index 3ac4877..3544dbc 100644 --- a/src/main/java/com/ilummc/tlib/ExampleMain.java +++ b/src/main/java/com/ilummc/tlib/ExampleMain.java @@ -1,12 +1,11 @@ package com.ilummc.tlib; +import com.ilummc.tlib.annotations.TConfig; +import com.ilummc.tlib.bean.Property; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; -import com.ilummc.tlib.annotations.Config; -import com.ilummc.tlib.bean.Property; - -@Config(name = "cfg.yml", charset = "GBK") +@TConfig(name = "cfg.yml", charset = "GBK") public class ExampleMain extends JavaPlugin { private Property update = Property.of(false); diff --git a/src/main/java/com/ilummc/tlib/TLib.java b/src/main/java/com/ilummc/tlib/TLib.java index 6686c94..91e5390 100644 --- a/src/main/java/com/ilummc/tlib/TLib.java +++ b/src/main/java/com/ilummc/tlib/TLib.java @@ -11,7 +11,6 @@ import com.ilummc.tlib.logger.TLogger; import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocaleLoader; import com.ilummc.tlib.util.IO; -import lombok.Getter; import me.skymc.taboolib.Main; import org.bukkit.Bukkit; import org.bukkit.configuration.InvalidConfigurationException; @@ -27,44 +26,40 @@ import java.nio.charset.Charset; @Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-api:1.7.25") public class TLib { - @Getter private static TLib tLib; - - @Getter + private static YamlConfiguration internalLanguage; private TLogger logger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE); - - @Getter private TLibConfig config; - - @Getter private TConfigWatcher configWatcher = new TConfigWatcher(); - - @Getter private File libsFolder; - @Getter - private YamlConfiguration internalLang; - private TLib() { libsFolder = new File(Main.getInst().getDataFolder(), "/libs"); if (!libsFolder.exists()) { libsFolder.mkdirs(); } try { - String yamlText = new String(IO.readFully(TLib.class.getResourceAsStream("/internalLang.yml")), Charset.forName("utf-8")); - internalLang = new YamlConfiguration(); - internalLang.loadFromString(yamlText); + String yamlText = new String(IO.readFully(TLib.class.getResourceAsStream("/lang/internal.yml")), Charset.forName("utf-8")); + internalLanguage = new YamlConfiguration(); + internalLanguage.loadFromString(yamlText); } catch (IOException | InvalidConfigurationException ignored) { } } + public static TLib getTLib() { + return tLib; + } + + public static YamlConfiguration getInternalLanguage() { + return internalLanguage; + } + public static void init() { tLib = new TLib(); TLoggerFilter.init(); TLocaleLoader.init(); PlaceholderHook.init(); - TLocaleLoader.load(Main.getInst(), false); TDependencyInjector.inject(Main.getInst(), tLib); } @@ -86,4 +81,20 @@ public class TLib { TLocale.Logger.fatal("TLIB.INJECTION-FAILED"); } } + + public TLogger getLogger() { + return logger; + } + + public TLibConfig getConfig() { + return config; + } + + public TConfigWatcher getConfigWatcher() { + return configWatcher; + } + + public File getLibsFolder() { + return libsFolder; + } } diff --git a/src/main/java/com/ilummc/tlib/annotations/Config.java b/src/main/java/com/ilummc/tlib/annotations/Config.java deleted file mode 100644 index 87b6aa3..0000000 --- a/src/main/java/com/ilummc/tlib/annotations/Config.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ilummc.tlib.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.Modifier; - -import com.ilummc.tlib.util.Ref; - -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -public @interface Config { - - String name() default "config.yml"; - - boolean fromJar() default false; - - boolean saveOnExit() default false; - - boolean readOnly() default true; - - String charset() default "UTF-8"; - - boolean listenChanges() default false; - - int excludeModifiers() default Modifier.STATIC | Modifier.TRANSIENT | Ref.ACC_SYNTHETIC | Ref.ACC_BRIDGE; - -} diff --git a/src/main/java/com/ilummc/tlib/annotations/Logger.java b/src/main/java/com/ilummc/tlib/annotations/Logger.java index 2fc75a9..1fd7408 100644 --- a/src/main/java/com/ilummc/tlib/annotations/Logger.java +++ b/src/main/java/com/ilummc/tlib/annotations/Logger.java @@ -5,14 +5,12 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import com.ilummc.tlib.logger.TLogger; - @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Logger { String value() default "[{0}|{1}] {1}"; - int level() default TLogger.INFO; + int level() default com.ilummc.tlib.logger.TLogger.INFO; } diff --git a/src/main/java/com/ilummc/tlib/config/TLibConfig.java b/src/main/java/com/ilummc/tlib/config/TLibConfig.java index f0c4cfc..cd30b1b 100644 --- a/src/main/java/com/ilummc/tlib/config/TLibConfig.java +++ b/src/main/java/com/ilummc/tlib/config/TLibConfig.java @@ -1,16 +1,20 @@ package com.ilummc.tlib.config; -import com.ilummc.tlib.annotations.Config; +import com.ilummc.tlib.annotations.TConfig; /** * @author sky * @since 2018-04-22 14:31:11 */ -@Config(name = "tlib.yml", listenChanges = true, readOnly = false) +@TConfig(name = "tlib.yml", listenChanges = true) public class TLibConfig { private boolean enablePlaceholderHookByDefault = false; + public void setEnablePlaceholderHookByDefault(boolean enablePlaceholderHookByDefault) { + this.enablePlaceholderHookByDefault = enablePlaceholderHookByDefault; + } + public boolean isEnablePlaceholderHookByDefault() { return enablePlaceholderHookByDefault; } diff --git a/src/main/java/com/ilummc/tlib/dependency/TDependencyLoader.java b/src/main/java/com/ilummc/tlib/dependency/TDependencyLoader.java index 3db37f7..701e03a 100644 --- a/src/main/java/com/ilummc/tlib/dependency/TDependencyLoader.java +++ b/src/main/java/com/ilummc/tlib/dependency/TDependencyLoader.java @@ -7,6 +7,7 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; +import me.skymc.taboolib.message.MsgUtils; import org.bukkit.plugin.Plugin; public class TDependencyLoader { diff --git a/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java b/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java index 532e916..09ce66f 100644 --- a/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java +++ b/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java @@ -1,7 +1,7 @@ package com.ilummc.tlib.inject; import com.google.common.io.Files; -import com.ilummc.tlib.annotations.Config; +import com.ilummc.tlib.annotations.TConfig; import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.fileutils.ConfigUtils; import org.apache.commons.lang3.Validate; @@ -50,7 +50,7 @@ public class TConfigInjector { public static Object loadConfig(Plugin plugin, Class clazz) { try { - Config config = clazz.getAnnotation(Config.class); + 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); @@ -68,7 +68,7 @@ public class TConfigInjector { public static void reloadConfig(Plugin plugin, Object object) { try { - Config config = object.getClass().getAnnotation(Config.class); + TConfig config = object.getClass().getAnnotation(TConfig.class); Validate.notNull(config); File file = new File(plugin.getDataFolder(), config.name()); Map map = ConfigUtils.confToMap(ConfigUtils.loadYaml(plugin, file)); @@ -83,7 +83,7 @@ public class TConfigInjector { public static Object unserialize(Plugin plugin, Class clazz) { try { - Config config = clazz.getAnnotation(Config.class); + TConfig config = clazz.getAnnotation(TConfig.class); Validate.notNull(config); return ConfigUtils.confToObj( ConfigUtils.mapToConf( @@ -104,7 +104,7 @@ public class TConfigInjector { public static Map serialize(Plugin plugin, Object object) { try { - Config config = object.getClass().getAnnotation(Config.class); + TConfig config = object.getClass().getAnnotation(TConfig.class); Validate.notNull(config); return ConfigUtils.objToConf(object).getValues(false); } catch (NullPointerException e) { @@ -116,7 +116,7 @@ public class TConfigInjector { } public static void saveConfig(Plugin plugin, Object object) throws IOException, NullPointerException { - Config config = object.getClass().getAnnotation(Config.class); + TConfig config = object.getClass().getAnnotation(TConfig.class); Validate.notNull(config); Object obj = serialize(plugin, object); Validate.notNull(obj); diff --git a/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java b/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java index 4cf3744..ea6fc35 100644 --- a/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java +++ b/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java @@ -3,10 +3,10 @@ package com.ilummc.tlib.inject; import com.ilummc.tlib.TLib; import com.ilummc.tlib.annotations.*; import com.ilummc.tlib.dependency.TDependency; -import com.ilummc.tlib.logger.TLogger; import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocaleLoader; import com.ilummc.tlib.util.Ref; +import me.skymc.taboolib.Main; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; @@ -17,15 +17,17 @@ import java.lang.reflect.Field; public class TDependencyInjector { public static void inject(Plugin plugin, Object o) { + TLocaleLoader.load(plugin, true); injectDependencies(plugin, o); injectLogger(plugin, o); injectConfig(plugin, o); injectPluginInstance(plugin, o); - TLocaleLoader.load(plugin, true); } static void injectOnEnable(Plugin plugin) { - inject(plugin, plugin); + if (!plugin.equals(Main.getInst())) { + inject(plugin, plugin); + } } static void onDisable(Plugin plugin) { @@ -41,8 +43,8 @@ public class TDependencyInjector { private static void ejectConfig(Plugin plugin, Object o) { for (Field field : Ref.getDeclaredFields(o.getClass())) { - Config config; - if ((config = field.getType().getAnnotation(Config.class)) != null && config.saveOnExit()) { + TConfig config; + if ((config = field.getType().getAnnotation(TConfig.class)) != null && config.saveOnExit()) { try { field.setAccessible(true); TConfigInjector.saveConfig(plugin, field.get(o)); @@ -58,8 +60,8 @@ public class TDependencyInjector { private static void injectConfig(Plugin plugin, Object o) { for (Field field : Ref.getDeclaredFields(o.getClass())) { try { - Config config; - if ((config = field.getType().getAnnotation(Config.class)) != null) { + TConfig config; + if ((config = field.getType().getAnnotation(TConfig.class)) != null) { field.setAccessible(true); Object obj = TConfigInjector.loadConfig(plugin, field.getType()); if (obj != null) { @@ -92,8 +94,8 @@ public class TDependencyInjector { try { Logger logger; if ((logger = field.getAnnotation(Logger.class)) != null) { - field.getType().asSubclass(TLogger.class); - TLogger tLogger = new TLogger(logger.value(), plugin, logger.level()); + 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()) field.setAccessible(true); field.set(o, tLogger); diff --git a/src/main/java/com/ilummc/tlib/logger/TLogger.java b/src/main/java/com/ilummc/tlib/logger/TLogger.java index b2ee777..dd07bd4 100644 --- a/src/main/java/com/ilummc/tlib/logger/TLogger.java +++ b/src/main/java/com/ilummc/tlib/logger/TLogger.java @@ -1,8 +1,6 @@ package com.ilummc.tlib.logger; import com.ilummc.tlib.util.Strings; -import lombok.Getter; -import lombok.Setter; import me.skymc.taboolib.Main; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -12,16 +10,31 @@ public class TLogger { public static final int VERBOSE = 0, FINEST = 1, FINE = 2, INFO = 3, WARN = 4, ERROR = 5, FATAL = 6; - @Getter private static TLogger globalLogger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE); - @Getter private final String pattern; - @Getter private Plugin plugin; - @Getter - @Setter private int level; + public static TLogger getGlobalLogger() { + return globalLogger; + } + + public String getPattern() { + return pattern; + } + + public Plugin getPlugin() { + return plugin; + } + + public int getLevel() { + return level; + } + + public void setLevel(int level) { + this.level = level; + } + public TLogger(String pattern, Plugin plugin, int level) { this.pattern = pattern; this.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 a948875..daee4af 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocale.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocale.java @@ -10,6 +10,8 @@ import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; import java.lang.reflect.Field; +import java.util.Collections; +import java.util.List; public class TLocale { @@ -17,25 +19,18 @@ public class TLocale { throw new AssertionError(); } - private static JavaPlugin getCallerPlugin(Class callerClass) { - try { - Field pluginField = callerClass.getClassLoader().getClass().getDeclaredField("plugin"); - pluginField.setAccessible(true); - return (JavaPlugin) pluginField.get(callerClass.getClassLoader()); - } catch (Exception ignored) { - TLib.getTLib().getLogger().error("无效的语言文件发送形式: &4" + callerClass.getName()); - } - return (JavaPlugin) Main.getInst(); + static String asString(String path, Class callerClass, String... args) { + return TLocaleLoader.asString(getCallerPlugin(callerClass), path, args); + } + + static List asStringList(String path, Class callerClass, String... args) { + return TLocaleLoader.asStringList(getCallerPlugin(callerClass), path, args); } private static void sendTo(String path, CommandSender sender, String[] args, Class callerClass) { TLocaleLoader.sendTo(getCallerPlugin(callerClass), path, sender, args); } - static String asString(String path, Class callerClass, String... args) { - return TLocaleLoader.asString(getCallerPlugin(callerClass), path, args); - } - public static void sendToConsole(String path, String... args) { Ref.getCallerClass(3).ifPresent(clazz -> sendTo(path, Bukkit.getConsoleSender(), args, clazz)); } @@ -50,18 +45,39 @@ public class TLocale { public static String asString(String path, String... args) { try { - return asString(path, Ref.getCallerClass(3).get(), args); + return asString(path, Ref.getCallerClassNotOptional(3), args); } catch (Exception e) { - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("FETCH-LOCALE-ERROR"), path)); - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("LOCALE-ERROR-REASON"), e.getMessage())); + 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())); return "§4<" + path + "§4>"; } } + public static List asStringList(String path, String... args) { + 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())); + return Collections.singletonList("§4<" + path + "§4>"); + } + } + public static void reload() { Ref.getCallerClass(3).ifPresent(clazz -> TLocaleLoader.load(getCallerPlugin(clazz), false)); } + private static JavaPlugin getCallerPlugin(Class callerClass) { + try { + Field pluginField = callerClass.getClassLoader().getClass().getDeclaredField("plugin"); + pluginField.setAccessible(true); + return (JavaPlugin) pluginField.get(callerClass.getClassLoader()); + } catch (Exception ignored) { + TLib.getTLib().getLogger().error("无效的语言文件发送形式: &4" + callerClass.getName()); + } + return (JavaPlugin) Main.getInst(); + } + public static final class Logger extends TLocale { public static void info(String path, String... args) { diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java b/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java index e70fae0..0258710 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java @@ -2,6 +2,7 @@ package com.ilummc.tlib.resources; import com.google.common.collect.ImmutableList; import com.ilummc.tlib.TLib; +import com.ilummc.tlib.logger.TLogger; import com.ilummc.tlib.resources.type.TLocaleText; import com.ilummc.tlib.util.Strings; import org.bukkit.Bukkit; @@ -22,13 +23,36 @@ import java.util.stream.Collectors; @SuppressWarnings("rawtypes") class TLocaleInstance { + private final Map> map = new HashMap<>(); private final Plugin plugin; + private int updateNodes; TLocaleInstance(Plugin plugin) { this.plugin = plugin; } - void sendTo(String path, CommandSender sender, String... args) { + @Override + public String toString() { + return map.toString(); + } + + public int size() { + return map.size(); + } + + public Map> getMap() { + return map; + } + + public Plugin getPlugin() { + return plugin; + } + + public int getUpdateNodes() { + return updateNodes; + } + + public void sendTo(String path, CommandSender sender, String... args) { try { map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).forEach(sendable -> { if (Bukkit.isPrimaryThread()) { @@ -38,39 +62,39 @@ class TLocaleInstance { } }); } catch (Exception | Error e) { - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SEND-LOCALE-ERROR"), path)); - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("LOCALE-ERROR-REASON"), e.toString())); + 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())); e.printStackTrace(); } } - String asString(String path, String... args) { + public String asString(String path, String... args) { return map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).get(0).asString(args); } - void load(YamlConfiguration configuration) { + public List asStringList(String path, String... args) { + return map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).get(0).asStringList(args); + } + + public void load(YamlConfiguration configuration) { + updateNodes = 0; configuration.getKeys(true).forEach(s -> { + boolean isCover = false; Object object = configuration.get(s); if (object instanceof TLocaleSendable) { - map.put(s, Collections.singletonList((TLocaleSendable) object)); + isCover = map.put(s, Collections.singletonList((TLocaleSendable) object)) != null; } else if (object instanceof List && !((List) object).isEmpty()) { - map.put(s, ((List) object).stream().map(TO_SENDABLE).collect(Collectors.toList())); + isCover = map.put(s, ((List) object).stream().map(TO_SENDABLE).collect(Collectors.toList())) != null; } else if (!(object instanceof ConfigurationSection)) { String str = String.valueOf(object); - map.put(s, Collections.singletonList(str.length() == 0 ? TLocaleSendable.getEmpty() : TLocaleText.of(str))); + isCover = map.put(s, Collections.singletonList(str.length() == 0 ? TLocaleSendable.getEmpty() : TLocaleText.of(str))) != null; + } + if (isCover) { + updateNodes++; } }); } - int size() { - return map.size(); - } - - @Override - public String toString() { - return map.toString(); - } - private static final Function TO_SENDABLE = o -> { if (o instanceof TLocaleSendable) { return ((TLocaleSendable) o); @@ -80,7 +104,4 @@ class TLocaleInstance { return TLocaleText.of(String.valueOf(o)); } }; - - private final Map> map = new HashMap<>(); - } diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java index 0e58c87..704b982 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java @@ -1,13 +1,14 @@ package com.ilummc.tlib.resources; import com.ilummc.tlib.TLib; -import com.ilummc.tlib.resources.type.TLocaleActionBar; -import com.ilummc.tlib.resources.type.TLocaleJson; -import com.ilummc.tlib.resources.type.TLocaleText; -import com.ilummc.tlib.resources.type.TLocaleTitle; +import com.ilummc.tlib.annotations.TLocalePlugin; +import com.ilummc.tlib.logger.TLogger; +import com.ilummc.tlib.resources.type.*; +import com.ilummc.tlib.util.IO; import com.ilummc.tlib.util.Strings; import me.skymc.taboolib.Main; import me.skymc.taboolib.fileutils.ConfigUtils; +import me.skymc.taboolib.other.NumberUtils; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; @@ -16,8 +17,9 @@ import org.bukkit.plugin.Plugin; import java.io.File; import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.StandardOpenOption; +import java.nio.charset.Charset; +import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @@ -26,7 +28,15 @@ public class TLocaleLoader { private static final Map map = new ConcurrentHashMap<>(); - static void sendTo(Plugin plugin, String path, CommandSender sender, String... args) { + public static void init() { + ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT"); + ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON"); + ConfigurationSerialization.registerClass(TLocaleSound.class, "SOUND"); + ConfigurationSerialization.registerClass(TLocaleTitle.class, "TITLE"); + ConfigurationSerialization.registerClass(TLocaleActionBar.class, "ACTION"); + } + + 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) { @@ -34,67 +44,121 @@ public class TLocaleLoader { } } - static String asString(Plugin plugin, String path, String... args) { - return map.get(plugin.getName()).asString(path, args); - } - - public static void init() { - ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT"); - ConfigurationSerialization.registerClass(TLocaleTitle.class, "TITLE"); - ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON"); - ConfigurationSerialization.registerClass(TLocaleActionBar.class, "ACTION"); - } - - public static void load(Plugin plugin, boolean ignoreLoaded) { - try { - if ((!ignoreLoaded || !map.containsKey(plugin.getName())) && (plugin == Main.getInst() || plugin.getDescription().getDepend().contains("TabooLib") || plugin.getDescription().getSoftDepend().contains("TabooLib"))) { - InputStream inputStream = null; - File file = null; - String lang = null; - for (String s : Main.getInst().getConfig().getStringList("LOCALE.PRIORITY")) { - lang = s; - file = new File(plugin.getDataFolder(), "/lang/" + s + ".yml"); - if (file.exists()) { - inputStream = Files.newInputStream(file.toPath(), StandardOpenOption.READ); - break; - } else if ((inputStream = plugin.getClass().getResourceAsStream("/lang/" + s + ".yml")) != null) { - break; - } - } - if (inputStream == null) { - TLib.getTLib().getLogger().error(TLib.getTLib().getInternalLang().getString("LANG-LOAD-FAIL")); - return; - } - if (!file.exists()) { - file.getParentFile().mkdirs(); - file.createNewFile(); - plugin.saveResource("lang/" + lang + ".yml", true); - } - TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("TRY-LOADING-LANG"), plugin.getName(), lang)); - { - YamlConfiguration configuration = ConfigUtils.loadYaml(plugin, file); - TLocaleInstance localeInstance = new TLocaleInstance(plugin); - localeInstance.load(configuration); - map.put(plugin.getName(), localeInstance); - TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SUCCESS-LOADING-LANG"), - plugin.getName(), lang, String.valueOf(localeInstance.size()))); - } - File finalFile = file; - String finalLang = lang; - TLib.getTLib().getConfigWatcher().addListener(file, null, obj -> { - TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("RELOADING-LANG"), plugin.getName())); - YamlConfiguration configuration = ConfigUtils.loadYaml(plugin, finalFile); - TLocaleInstance localeInstance = new TLocaleInstance(plugin); - localeInstance.load(configuration); - map.put(plugin.getName(), localeInstance); - TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SUCCESS-LOADING-LANG"), - plugin.getName(), finalLang, String.valueOf(localeInstance.size()))); - }); - } - } catch (Exception e) { - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("ERROR-LOADING-LANG"), - plugin.getName(), e.toString() + "\n" + e.getStackTrace()[0].toString())); + public static String asString(Plugin plugin, String path, String... args) { + TLocaleInstance tLocaleInstance = map.get(plugin.getName()); + if (tLocaleInstance != null) { + return tLocaleInstance.asString(path, args); + } else { + return ""; } } + public static List asStringList(Plugin plugin, String path, String... args) { + TLocaleInstance tLocaleInstance = map.get(plugin.getName()); + if (tLocaleInstance != null) { + return tLocaleInstance.asStringList(path, args); + } else { + return Collections.emptyList(); + } + } + + /** + * 载入语言文件 + * + * @param plugin 载入插件 + * @param isCover 是否覆盖 + */ + public static void load(Plugin plugin, boolean isCover) { + try { + if ((isCover || !isLocaleLoaded(plugin)) && (plugin.equals(Main.getInst()) || isDependWithTabooLib(plugin))) { + // 获取文件 + File localeFile = getLocaleFile(plugin); + if (localeFile == null) { + return; + } + + // 加载文件 + infoLogger("TRY-LOADING-LANG", plugin.getName(), localeFile.getName()); + YamlConfiguration localeConfiguration = ConfigUtils.loadYaml(plugin, localeFile); + YamlConfiguration localeConfigurationAtStream = getLocaleAtStream(plugin, localeFile); + + // 载入配置 + loadPluginLocale(plugin, localeFile, localeConfiguration, localeConfigurationAtStream); + + // 注册监听 + TLib.getTLib().getConfigWatcher().removeListener(localeFile); + TLib.getTLib().getConfigWatcher().addListener(localeFile, null, obj -> { + infoLogger("RELOADING-LANG", plugin.getName()); + loadPluginLocale(plugin, localeFile, ConfigUtils.loadYaml(plugin, localeFile), getLocaleAtStream(plugin, localeFile)); + }); + } + } catch (Exception e) { + errorLogger("ERROR-LOADING-LANG", plugin.getName(), e.toString() + "\n" + e.getStackTrace()[0].toString()); + } + } + + private static void infoLogger(String path, String... args) { + TLogger.getGlobalLogger().info(Strings.replaceWithOrder(TLib.getInternalLanguage().getString(path), args)); + } + + private static void errorLogger(String path, String... args) { + TLogger.getGlobalLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString(path), args)); + } + + private static boolean isVersionOutOfDate(YamlConfiguration configuration, YamlConfiguration configurationAtSteam) { + return (configurationAtSteam != null && configurationAtSteam.contains("VERSION") && configuration.contains("VERSION")) && NumberUtils.getDouble(configurationAtSteam.get("VERSION").toString()) > NumberUtils.getDouble(configuration.get("VERSION").toString()); + } + + private static File getLocaleFile(Plugin plugin) { + releaseLocales(plugin); + return getLocalePriority().stream().map(localeName -> new File(plugin.getDataFolder(), "lang/" + localeName + ".yml")).filter(File::exists).findFirst().orElse(null); + } + + private static void releaseLocales(Plugin plugin) { + getLocalePriority().stream().filter(localeName -> !new File(plugin.getDataFolder(), "lang/" + localeName + ".yml").exists() && plugin.getResource("lang/" + localeName + ".yml") != null).forEach(localeName -> plugin.saveResource("lang/" + localeName + ".yml", true)); + } + + public static boolean isLocaleLoaded(Plugin plugin) { + return map.containsKey(plugin.getName()); + } + + public static boolean isDependWithTabooLib(Plugin plugin) { + return plugin.getClass().getAnnotation(TLocalePlugin.class) != null || plugin.getDescription().getDepend().contains(Main.getInst().getName()) || plugin.getDescription().getSoftDepend().contains(Main.getInst().getName()); + } + + public static List getLocalePriority() { + return Main.getInst().getConfig().contains("LOCALE.PRIORITY") ? Main.getInst().getConfig().getStringList("LOCALE.PRIORITY") : Collections.singletonList("zh_CN"); + } + + private static TLocaleInstance getLocaleInstance(Plugin plugin) { + TLocaleInstance instance = new TLocaleInstance(plugin); + map.put(plugin.getName(), instance); + return instance; + } + + private static YamlConfiguration getLocaleAtStream(Plugin plugin, File localeFile) { + InputStream localeInputSteam = plugin.getClass().getResourceAsStream("/lang/" + localeFile.getName()); + try { + String yamlText = new String(IO.readFully(localeInputSteam), Charset.forName("utf-8")); + YamlConfiguration yaml = new YamlConfiguration(); + yaml.loadFromString(yamlText); + return yaml; + } catch (Exception ignored) { + return null; + } + } + + private static void loadPluginLocale(Plugin plugin, File localeFile, YamlConfiguration localeConfiguration, YamlConfiguration localeConfigurationAtStream) { + TLocaleInstance localeInstance = getLocaleInstance(plugin); + boolean versionOutOfDate = isVersionOutOfDate(localeConfiguration, localeConfigurationAtStream); + if (versionOutOfDate) { + localeInstance.load(localeConfigurationAtStream); + } + localeInstance.load(localeConfiguration); + if (!versionOutOfDate || localeInstance.size() - localeInstance.getUpdateNodes() == 0) { + infoLogger("SUCCESS-LOADING-LANG-NORMAL", plugin.getName(), localeFile.getName().split("\\.")[0], String.valueOf(localeInstance.size())); + } else { + infoLogger("SUCCESS-LOADING-LANG-UPDATE", plugin.getName(), localeFile.getName().split("\\.")[0], String.valueOf(localeInstance.size()), String.valueOf(localeInstance.size() - localeInstance.getUpdateNodes())); + } + } } diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleSendable.java b/src/main/java/com/ilummc/tlib/resources/TLocaleSendable.java index 61959e5..99d2c11 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleSendable.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleSendable.java @@ -2,10 +2,20 @@ package com.ilummc.tlib.resources; import org.bukkit.command.CommandSender; +import java.util.Collections; +import java.util.List; + public interface TLocaleSendable { + static TLocaleSendable getEmpty() { + return (sender, args) -> { + // Empty + }; + } + static TLocaleSendable getEmpty(String path) { return new TLocaleSendable() { + @Override public void sendTo(CommandSender sender, String... args) { sender.sendMessage("§4<" + path + "§4>"); @@ -15,23 +25,21 @@ public interface TLocaleSendable { public String asString(String... args) { return "§4<" + path + "§4>"; } - }; - } - - static TLocaleSendable getEmpty() { - return new TLocaleSendable() { - @Override - public void sendTo(CommandSender sender, String... args) { - } @Override - public String asString(String... args) { - return ""; + public List asStringList(String... args) { + return Collections.singletonList("§4<" + path + "§4>"); } }; } void sendTo(CommandSender sender, String... args); - String asString(String... args); + default String asString(String... args) { + return ""; + } + + default List asStringList(String... args) { + return Collections.emptyList(); + } } 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 8e32bed..1f7965b 100644 --- a/src/main/java/com/ilummc/tlib/resources/type/TLocaleActionBar.java +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleActionBar.java @@ -20,7 +20,6 @@ import java.util.Map; public class TLocaleActionBar implements TLocaleSendable, ConfigurationSerializable { private final String text; - private final boolean papi; private TLocaleActionBar(String text, boolean papi) { @@ -54,8 +53,9 @@ public class TLocaleActionBar implements TLocaleSendable, ConfigurationSerializa public Map serialize() { Map map = Maps.newHashMap(); map.put("text", text); - if (papi) + if (papi) { map.put("papi", true); + } return map; } 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 58defe3..fcde732 100644 --- a/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java @@ -8,7 +8,9 @@ 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; @@ -37,25 +39,17 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable { } public static TLocaleJson valueOf(Map map) { - Object textObj = map.getOrDefault("text", "Empty Node"); - List textList = textObj instanceof String ? Lists.newArrayList(ChatColor.translateAlternateColorCodes('&', (String) textObj)) : - (textObj instanceof List && !((List) textObj).isEmpty()) ? - ((List) textObj).stream().map(Object::toString) - .map(s -> ChatColor.translateAlternateColorCodes('&', s)) - .collect(Collectors.toList()) : Lists.newArrayList(String.valueOf(textObj)); boolean papi = (boolean) map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false)); + List textList = getTextList(map.getOrDefault("text", "Empty Node")); Object argsObj = map.get("args"); if (argsObj instanceof Map) { Map section = new HashMap<>(((Map) argsObj).size()); ((Map) argsObj).forEach((k, v) -> section.put(String.valueOf(k), v)); List collect = textList.stream().map(s -> { - String[] template = pattern.split(s); int index = 0; + String[] template = pattern.split(s); Matcher matcher = pattern.matcher(s); - List builder; - if (template.length > index) { - builder = new ArrayList<>(Arrays.asList(TextComponent.fromLegacyText(template[index++]))); - } else builder = new ArrayList<>(); + 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; @@ -64,35 +58,22 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable { String text = split.length > 1 ? split[0] : ""; String node = split.length > 1 ? split[1] : split[0]; if (section.containsKey(node)) { - @SuppressWarnings("unchecked") Map arg = (Map) section.get(node); text = ChatColor.translateAlternateColorCodes('&', String.valueOf(arg.getOrDefault("text", text))); BaseComponent[] component = TextComponent.fromLegacyText(text); arg.forEach((key, value) -> { - switch (key) { - case "suggest": - for (BaseComponent baseComponent : component) { - baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, String.valueOf(value))); - } - break; - case "command": - for (BaseComponent baseComponent : component) { - baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.valueOf(value))); - } - break; - case "hover": - for (BaseComponent baseComponent : component) { - baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, - new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', String.valueOf(value))).create())); - } - break; - default: + if ("suggest".equalsIgnoreCase(key)) { + Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, String.valueOf(value)))); + } else if ("command".equalsIgnoreCase(key) || "commands".equalsIgnoreCase(key)) { + Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.valueOf(value)))); + } else if ("hover".equalsIgnoreCase(key)) { + Arrays.stream(component).forEach(baseComponent -> baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', String.valueOf(value))).create()))); } }); builder.addAll(Arrays.asList(component)); } else { builder.addAll(Arrays.asList(TextComponent.fromLegacyText(text))); - TLib.getTLib().getLogger().warn(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("MISSING-ARGUMENT"), node)); + TLib.getTLib().getLogger().warn(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("MISSING-ARGUMENT"), node)); } if (index < template.length) { builder.addAll(Arrays.asList(TextComponent.fromLegacyText(template[index++]))); @@ -105,10 +86,19 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable { return new TLocaleJson(textList.stream().map(TextComponent::fromLegacyText).collect(Collectors.toList()), papi, map); } + private static List getTextList(Object textObj) { + if (textObj instanceof List) { + return ((List) textObj).stream().map(Object::toString).map(s -> ChatColor.translateAlternateColorCodes('&', s)).collect(Collectors.toList()); + } else if (textObj instanceof String) { + return Lists.newArrayList(ChatColor.translateAlternateColorCodes('&', (String) textObj)); + } else { + return Collections.emptyList(); + } + } + @Override public void sendTo(CommandSender sender, String... args) { - if (sender instanceof Player) - components.forEach(comp -> ((Player) sender).spigot().sendMessage(replace(comp, sender, args))); + components.forEach(comp -> sendRawMessage(sender, replace(comp, sender, args))); } @Override @@ -121,6 +111,14 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable { return Maps.newHashMap(map); } + private void sendRawMessage(CommandSender sender, BaseComponent[] components) { + if (sender instanceof Player) { + JSONFormatter.sendRawMessage((Player) sender, ComponentSerializer.toString(components)); + } else { + sender.sendMessage(TextComponent.toLegacyText(components)); + } + } + private BaseComponent[] replace(BaseComponent[] component, CommandSender sender, String... args) { BaseComponent[] components = new BaseComponent[component.length]; for (int i = 0; i < components.length; i++) { @@ -142,8 +140,9 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable { HoverEvent hoverEvent = new HoverEvent(component.getHoverEvent().getAction(), replace(component.getHoverEvent().getValue(), sender, args)); component.setHoverEvent(hoverEvent); } - if (component.getExtra() != null) + if (component.getExtra() != null) { component.setExtra(replace(component.getExtra(), sender, args)); + } if (component instanceof TextComponent) { ((TextComponent) component).setText(replace(sender, ((TextComponent) component).getText(), args)); } diff --git a/src/main/java/com/ilummc/tlib/resources/type/TLocaleText.java b/src/main/java/com/ilummc/tlib/resources/type/TLocaleText.java index 3c0252c..86db573 100644 --- a/src/main/java/com/ilummc/tlib/resources/type/TLocaleText.java +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleText.java @@ -22,7 +22,6 @@ import java.util.stream.Collectors; public class TLocaleText implements TLocaleSendable, ConfigurationSerializable { private final Object text; - private final boolean usePlaceholder; private TLocaleText(Object text, boolean usePlaceholder) { @@ -78,9 +77,19 @@ public class TLocaleText implements TLocaleSendable, ConfigurationSerializable { return Strings.replaceWithOrder(objectToString(text), args); } + @Override + public List asStringList(String... args) { + if (text instanceof String) { + return Collections.singletonList(((String) text)); + } else { + return ((List) text); + } + } + private String objectToString(Object text) { - if (text instanceof String) return ((String) text); - else { + if (text instanceof String) { + return ((String) text); + } else { StringJoiner joiner = new StringJoiner("\n"); ((List) text).forEach(joiner::add); return joiner.toString(); diff --git a/src/main/java/com/ilummc/tlib/resources/type/TLocaleTitle.java b/src/main/java/com/ilummc/tlib/resources/type/TLocaleTitle.java index bf5a4ef..460c2c5 100644 --- a/src/main/java/com/ilummc/tlib/resources/type/TLocaleTitle.java +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleTitle.java @@ -54,7 +54,7 @@ public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable (int) map.getOrDefault("stay", 20), (boolean) map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false))); } catch (Exception e) { - title = new TLocaleTitle("§4Load failed!", "§c" + e.getMessage(), 10, 20, 10, false); + title = new TLocaleTitle("Empty Title message.", e.getMessage(), 10, 20, 10, false); } return title; } diff --git a/src/main/java/com/ilummc/tlib/util/Ref.java b/src/main/java/com/ilummc/tlib/util/Ref.java index 53f20ea..2b68dc8 100644 --- a/src/main/java/com/ilummc/tlib/util/Ref.java +++ b/src/main/java/com/ilummc/tlib/util/Ref.java @@ -70,6 +70,10 @@ public class Ref { return Optional.ofNullable(CallerClass.impl.getCallerClass(depth + 1)); } + public static Class getCallerClassNotOptional(int depth) { + return CallerClass.impl.getCallerClass(depth); + } + public static String getSerializedName(Field field) { return field.isAnnotationPresent(SerializedName.class) ? field.getAnnotation(SerializedName.class).value() : field.getName(); } diff --git a/src/main/java/com/ilummc/tlib/util/Strings.java b/src/main/java/com/ilummc/tlib/util/Strings.java index 04acc68..95fe02a 100644 --- a/src/main/java/com/ilummc/tlib/util/Strings.java +++ b/src/main/java/com/ilummc/tlib/util/Strings.java @@ -24,5 +24,4 @@ public class Strings { } return stringBuilder.toString(); } - } diff --git a/src/main/java/me/skymc/taboolib/Main.java b/src/main/java/me/skymc/taboolib/Main.java index c435b2a..f45c432 100644 --- a/src/main/java/me/skymc/taboolib/Main.java +++ b/src/main/java/me/skymc/taboolib/Main.java @@ -1,11 +1,8 @@ package me.skymc.taboolib; import com.ilummc.tlib.TLib; -import lombok.Getter; -import lombok.Setter; import me.skymc.taboolib.anvil.AnvilContainerAPI; import me.skymc.taboolib.bstats.Metrics; -import me.skymc.taboolib.client.LogClient; import me.skymc.taboolib.commands.MainCommands; import me.skymc.taboolib.commands.language.Language2Command; import me.skymc.taboolib.commands.locale.TabooLibLocaleCommand; @@ -52,32 +49,70 @@ import java.util.Random; @SuppressWarnings("deprecation") public class Main extends JavaPlugin implements Listener { - @Getter private static Plugin inst; - @Getter - private static String prefix = "§8[§3§lTabooLib§8] §7"; - @Getter - @Setter + private static Economy Economy; - @Getter + private static File playerDataFolder; - @Getter + private static File serverDataFolder; - @Getter + private static StorageType storageType; - @Getter + private static boolean disable = false; - @Getter + private static MySQLConnection connection = null; - @Getter - private FileConfiguration config = null; - @Getter - private static LogClient client; - @Getter - private static Language2 exampleLangauge2; - @Getter + + private static Language2 exampleLanguage2; + private static boolean started; + private FileConfiguration config = null; + + public static Plugin getInst() { + return inst; + } + + public static String getPrefix() { + return "§8[§3§lTabooLib§8] §7"; + } + + public static net.milkbowl.vault.economy.Economy getEconomy() { + return Economy; + } + + public static void setEconomy(net.milkbowl.vault.economy.Economy economy) { + Economy = economy; + } + + public static File getPlayerDataFolder() { + return playerDataFolder; + } + + public static File getServerDataFolder() { + return serverDataFolder; + } + + public static StorageType getStorageType() { + return storageType; + } + + public static boolean isDisable() { + return disable; + } + + public static MySQLConnection getConnection() { + return connection; + } + + public static Language2 getExampleLanguage2() { + return exampleLanguage2; + } + + public static boolean isStarted() { + return started; + } + public static Random getRandom() { return NumberUtils.getRand(); } @@ -86,6 +121,11 @@ public class Main extends JavaPlugin implements Listener { return inst.getConfig().getString("MYSQL.PREFIX"); } + @Override + public FileConfiguration getConfig() { + return config; + } + @Override public void saveDefaultConfig() { reloadConfig(); @@ -179,7 +219,7 @@ public class Main extends JavaPlugin implements Listener { // 启动脚本 JavaShell.javaShellSetup(); // 载入语言文件 - exampleLangauge2 = new Language2("Language2", this); + exampleLanguage2 = new Language2("Language2", this); // 注册脚本 SkriptHandler.getInst(); @@ -304,13 +344,11 @@ public class Main extends JavaPlugin implements Listener { getServer().getPluginManager().registerEvents(new ItemLibraryPatch(), this); getServer().getPluginManager().registerEvents(new SoundsLibraryPatch(), this); - if (TabooLib.getVerint() > 10700) { getServer().getPluginManager().registerEvents(new EntityUtils(), this); getServer().getPluginManager().registerEvents(new SignUtils(), this); } - // 如果 YUM 插件存在 if (Bukkit.getPluginManager().getPlugin("YUM") != null) { getServer().getPluginManager().registerEvents(new ListenerNetWork(), this); } diff --git a/src/main/java/me/skymc/taboolib/TabooLib.java b/src/main/java/me/skymc/taboolib/TabooLib.java index 2f5cf19..d0fcfc6 100644 --- a/src/main/java/me/skymc/taboolib/TabooLib.java +++ b/src/main/java/me/skymc/taboolib/TabooLib.java @@ -1,62 +1,60 @@ package me.skymc.taboolib; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; - import me.skymc.taboolib.playerdata.DataUtils; import net.md_5.bungee.api.ChatColor; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +import java.util.Arrays; +import java.util.UUID; public class TabooLib { - - public static void debug(Plugin plugin, String... args) { - if (Main.getInst().getConfig().getBoolean("DEBUG")) { - for (String var : args) { - Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[TabooLib - DEBUG][" + plugin.getName() + "] " + ChatColor.RED + var); - } - } - } - - public static double getPluginVersion() { - try { - return Double.valueOf(Main.getInst().getDescription().getVersion()); - } catch (Exception e) { - return 0D; - } - } - - public static String getVersion() { - return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - } - - public static String getServerUID() { - if (!DataUtils.getPluginData("TabooLibrary", null).contains("serverUID")) { - DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString()); - } - return DataUtils.getPluginData("TabooLibrary", null).getString("serverUID"); - } - - public static void resetServerUID() { - DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString()); - } - - public static int getVerint() { - if (getVersion().startsWith("v1_7")) { - return 10700; - } else if (getVersion().startsWith("v1_8")) { - return 10800; - } else if (getVersion().startsWith("v1_9")) { - return 10900; - } else if (getVersion().startsWith("v1_10")) { - return 11000; - } else if (getVersion().startsWith("v1_11")) { - return 11100; - } else if (getVersion().startsWith("v1_12")) { - return 11200; - } else if (getVersion().startsWith("v1_13")) { - return 11300; - } - return 0; - } + + public static void debug(Plugin plugin, String... args) { + if (Main.getInst().getConfig().getBoolean("DEBUG")) { + Arrays.stream(args).forEach(var -> Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[TabooLib - DEBUG][" + plugin.getName() + "] " + ChatColor.RED + var)); + } + } + + public static double getPluginVersion() { + try { + return Double.valueOf(Main.getInst().getDescription().getVersion()); + } catch (Exception e) { + return 0D; + } + } + + public static String getVersion() { + return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + } + + public static String getServerUID() { + if (!DataUtils.getPluginData("TabooLibrary", null).contains("serverUID")) { + DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString()); + } + return DataUtils.getPluginData("TabooLibrary", null).getString("serverUID"); + } + + public static void resetServerUID() { + DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString()); + } + + public static int getVerint() { + if (getVersion().startsWith("v1_7")) { + return 10700; + } else if (getVersion().startsWith("v1_8")) { + return 10800; + } else if (getVersion().startsWith("v1_9")) { + return 10900; + } else if (getVersion().startsWith("v1_10")) { + return 11000; + } else if (getVersion().startsWith("v1_11")) { + return 11100; + } else if (getVersion().startsWith("v1_12")) { + return 11200; + } else if (getVersion().startsWith("v1_13")) { + return 11300; + } + return 0; + } } diff --git a/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java b/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java index b0fbdd0..584856d 100644 --- a/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java +++ b/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPI.java @@ -1,9 +1,6 @@ package me.skymc.taboolib.anvil; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - +import me.skymc.taboolib.anvil.versions.AnvilContainer_V1_9_4; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; @@ -18,107 +15,91 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import me.skymc.taboolib.anvil.versions.AnvilContainer_V1_9_4; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; -public class AnvilContainerAPI implements Listener{ - - public static List list = new ArrayList<>(); - public static ItemStack item = new ItemStack(Material.NAME_TAG); - - public static HashMap isOpen = new HashMap<>(); - public static AnvilContainerAPIEvent event; - - public static void send(Player p, String type, String str, List lorelist) - { - isOpen.put(p.getName(), type); - - AnvilContainer_V1_9_4.openAnvil(p); - ItemMeta meta = item.getItemMeta(); - - list.clear(); - if (lorelist == null) - { - list.add(""); - list.add("§7在上方文本框内输入信息"); - list.add("§7随后点击右侧输出物品"); - } - else - { - list = lorelist; - } - meta.setLore(list); - meta.setDisplayName(str); - item.setItemMeta(meta); - - p.getOpenInventory().setItem(0, item); - p.playSound(p.getLocation(), Sound.BLOCK_ANVIL_PLACE, 1, 1); - } - - @EventHandler - public void close(InventoryCloseEvent e) - { - if (isOpen.containsKey(e.getPlayer().getName())) - { - isOpen.remove(e.getPlayer().getName()); - if (e.getInventory().getType() == InventoryType.ANVIL) - { - e.getInventory().clear(); - } - } - } - - @EventHandler - public void click(InventoryClickEvent e) - { - if (!isOpen.containsKey(e.getWhoClicked().getName())) - { - return; - } - if (e.getInventory().getType() != InventoryType.ANVIL) - { - return; - } - e.setCancelled(true); - - int slot = e.getRawSlot(); - if (slot != 2) - { - return; - } - - Inventory inv = e.getInventory(); - if (inv.getItem(2) == null) - { - return; - } - - if (inv.getItem(2).getItemMeta().hasDisplayName()) - { - event = new AnvilContainerAPIEvent(e, isOpen.get(e.getWhoClicked().getName()), inv.getItem(2).getItemMeta().getDisplayName()); - e.getWhoClicked().closeInventory(); - Bukkit.getPluginManager().callEvent(event); - } - } - - @EventHandler - public void example(PlayerCommandPreprocessEvent e) - { - if (e.getMessage().equals("/anvilexample")) - { - if (e.getPlayer().hasPermission("taboolib.admin")) - { - e.setCancelled(true); - AnvilContainerAPI.send(e.getPlayer(), "EXAMPLE", "在这里输入文本", null); - } - } - } - - @EventHandler - public void example2(AnvilContainerAPIEvent e) - { - if (e.type.equals("EXAMPLE")) - { - e.event.getWhoClicked().sendMessage(e.string); - } - } +public class AnvilContainerAPI implements Listener { + + public static List list = new ArrayList<>(); + public static ItemStack item = new ItemStack(Material.NAME_TAG); + public static HashMap isOpen = new HashMap<>(); + public static AnvilContainerAPIEvent event; + + public static void send(Player p, String type, String str, List lorelist) { + isOpen.put(p.getName(), type); + + AnvilContainer_V1_9_4.openAnvil(p); + ItemMeta meta = item.getItemMeta(); + + list.clear(); + if (lorelist == null) { + list.add(""); + list.add("§7在上方文本框内输入信息"); + list.add("§7随后点击右侧输出物品"); + } else { + list = lorelist; + } + + meta.setLore(list); + meta.setDisplayName(str); + item.setItemMeta(meta); + + p.getOpenInventory().setItem(0, item); + p.playSound(p.getLocation(), Sound.BLOCK_ANVIL_PLACE, 1, 1); + } + + @EventHandler + public void close(InventoryCloseEvent e) { + if (isOpen.containsKey(e.getPlayer().getName())) { + isOpen.remove(e.getPlayer().getName()); + if (e.getInventory().getType() == InventoryType.ANVIL) { + e.getInventory().clear(); + } + } + } + + @EventHandler + public void click(InventoryClickEvent e) { + if (!isOpen.containsKey(e.getWhoClicked().getName())) { + return; + } + if (e.getInventory().getType() != InventoryType.ANVIL) { + return; + } + e.setCancelled(true); + + int slot = e.getRawSlot(); + if (slot != 2) { + return; + } + + Inventory inv = e.getInventory(); + if (inv.getItem(2) == null) { + return; + } + + if (inv.getItem(2).getItemMeta().hasDisplayName()) { + event = new AnvilContainerAPIEvent(e, isOpen.get(e.getWhoClicked().getName()), inv.getItem(2).getItemMeta().getDisplayName()); + e.getWhoClicked().closeInventory(); + Bukkit.getPluginManager().callEvent(event); + } + } + + @EventHandler + public void example(PlayerCommandPreprocessEvent e) { + if (e.getMessage().equals("/anvilexample")) { + if (e.getPlayer().hasPermission("taboolib.admin")) { + e.setCancelled(true); + AnvilContainerAPI.send(e.getPlayer(), "EXAMPLE", "在这里输入文本", null); + } + } + } + + @EventHandler + public void example2(AnvilContainerAPIEvent e) { + if (e.type.equals("EXAMPLE")) { + e.event.getWhoClicked().sendMessage(e.string); + } + } } diff --git a/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPIEvent.java b/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPIEvent.java index 1536683..5cbe6d4 100644 --- a/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPIEvent.java +++ b/src/main/java/me/skymc/taboolib/anvil/AnvilContainerAPIEvent.java @@ -4,28 +4,25 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.bukkit.event.inventory.InventoryClickEvent; -public class AnvilContainerAPIEvent extends Event{ - - public static final HandlerList handlers = new HandlerList(); - public InventoryClickEvent event; - public String string; - public String type; - - public AnvilContainerAPIEvent(InventoryClickEvent e, String t, String s) - { - event = e; - string = s; - type = t; - } +public class AnvilContainerAPIEvent extends Event { - @Override - public HandlerList getHandlers() - { - return handlers; - } - - public static HandlerList getHandlerList() - { - return handlers; - } + public static final HandlerList handlers = new HandlerList(); + public InventoryClickEvent event; + public String string; + public String type; + + public AnvilContainerAPIEvent(InventoryClickEvent e, String t, String s) { + event = e; + string = s; + type = t; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } } diff --git a/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_11_R1.java b/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_11_R1.java index 68cdcff..9383b3b 100644 --- a/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_11_R1.java +++ b/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_11_R1.java @@ -1,41 +1,32 @@ package me.skymc.taboolib.anvil.versions; +import net.minecraft.server.v1_11_R1.*; import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer; import org.bukkit.entity.Player; -import net.minecraft.server.v1_11_R1.BlockPosition; -import net.minecraft.server.v1_11_R1.ChatMessage; -import net.minecraft.server.v1_11_R1.ContainerAnvil; -import net.minecraft.server.v1_11_R1.EntityHuman; -import net.minecraft.server.v1_11_R1.EntityPlayer; -import net.minecraft.server.v1_11_R1.PacketPlayOutOpenWindow; - public class AnvilContainer_V1_11_R1 extends ContainerAnvil { - public AnvilContainer_V1_11_R1(EntityHuman player) - { - super(player.inventory, player.world, new BlockPosition(0, 0, 0), player); - } - - @Override - public boolean a(EntityHuman player) - { - return true; - } - - /** - * @deprecated 方法已过期,已有新的方法 - */ - @Deprecated - public static void openAnvil(Player p) - { - EntityPlayer player = ((CraftPlayer)p).getHandle(); - AnvilContainer_V1_11_R1 container = new AnvilContainer_V1_11_R1(player); - int c = player.nextContainerCounter(); + public AnvilContainer_V1_11_R1(EntityHuman player) { + super(player.inventory, player.world, new BlockPosition(0, 0, 0), player); + } + + @Override + public boolean a(EntityHuman player) { + return true; + } + + /** + * @deprecated 方法已过期,已有新的方法 + */ + @Deprecated + public static void openAnvil(Player p) { + EntityPlayer player = ((CraftPlayer) p).getHandle(); + AnvilContainer_V1_11_R1 container = new AnvilContainer_V1_11_R1(player); + int c = player.nextContainerCounter(); player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(c, "minecraft:anvil", new ChatMessage("Repairing"), 0)); - player.activeContainer = container; - player.activeContainer.windowId = c; - player.activeContainer.addSlotListener(player); - } + player.activeContainer = container; + player.activeContainer.windowId = c; + player.activeContainer.addSlotListener(player); + } } diff --git a/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_8_R3.java b/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_8_R3.java index 3b38d5e..afe3a29 100644 --- a/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_8_R3.java +++ b/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_8_R3.java @@ -1,41 +1,32 @@ package me.skymc.taboolib.anvil.versions; +import net.minecraft.server.v1_8_R3.*; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import org.bukkit.entity.Player; -import net.minecraft.server.v1_8_R3.BlockPosition; -import net.minecraft.server.v1_8_R3.ChatMessage; -import net.minecraft.server.v1_8_R3.ContainerAnvil; -import net.minecraft.server.v1_8_R3.EntityHuman; -import net.minecraft.server.v1_8_R3.EntityPlayer; -import net.minecraft.server.v1_8_R3.PacketPlayOutOpenWindow; - public class AnvilContainer_V1_8_R3 extends ContainerAnvil { - public AnvilContainer_V1_8_R3(EntityHuman player) - { - super(player.inventory, player.world, new BlockPosition(0, 0, 0), player); - } - - @Override - public boolean a(EntityHuman player) - { - return true; - } - - /** - * @deprecated 方法已过期,已有新的方法 - */ - @Deprecated - public static void openAnvil(Player p) - { - EntityPlayer player = ((CraftPlayer)p).getHandle(); - AnvilContainer_V1_8_R3 container = new AnvilContainer_V1_8_R3(player); - int c = player.nextContainerCounter(); + public AnvilContainer_V1_8_R3(EntityHuman player) { + super(player.inventory, player.world, new BlockPosition(0, 0, 0), player); + } + + @Override + public boolean a(EntityHuman player) { + return true; + } + + /** + * @deprecated 方法已过期,已有新的方法 + */ + @Deprecated + public static void openAnvil(Player p) { + EntityPlayer player = ((CraftPlayer) p).getHandle(); + AnvilContainer_V1_8_R3 container = new AnvilContainer_V1_8_R3(player); + int c = player.nextContainerCounter(); player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(c, "minecraft:anvil", new ChatMessage("Repairing"), 0)); - player.activeContainer = container; - player.activeContainer.windowId = c; - player.activeContainer.addSlotListener(player); - } + player.activeContainer = container; + player.activeContainer.windowId = c; + player.activeContainer.addSlotListener(player); + } } diff --git a/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_9_4.java b/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_9_4.java index ed3abf4..37ca366 100644 --- a/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_9_4.java +++ b/src/main/java/me/skymc/taboolib/anvil/versions/AnvilContainer_V1_9_4.java @@ -1,41 +1,32 @@ package me.skymc.taboolib.anvil.versions; +import net.minecraft.server.v1_9_R2.*; import org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer; import org.bukkit.entity.Player; -import net.minecraft.server.v1_9_R2.BlockPosition; -import net.minecraft.server.v1_9_R2.ChatMessage; -import net.minecraft.server.v1_9_R2.ContainerAnvil; -import net.minecraft.server.v1_9_R2.EntityHuman; -import net.minecraft.server.v1_9_R2.EntityPlayer; -import net.minecraft.server.v1_9_R2.PacketPlayOutOpenWindow; - public class AnvilContainer_V1_9_4 extends ContainerAnvil { - public AnvilContainer_V1_9_4(EntityHuman player) - { - super(player.inventory, player.world, new BlockPosition(0, 0, 0), player); - } - - @Override - public boolean a(EntityHuman player) - { - return true; - } - - /** - * @deprecated 方法已过期,已有新的方法 - */ - @Deprecated - public static void openAnvil(Player p) - { - EntityPlayer player = ((CraftPlayer)p).getHandle(); - AnvilContainer_V1_9_4 container = new AnvilContainer_V1_9_4(player); - int c = player.nextContainerCounter(); + public AnvilContainer_V1_9_4(EntityHuman player) { + super(player.inventory, player.world, new BlockPosition(0, 0, 0), player); + } + + @Override + public boolean a(EntityHuman player) { + return true; + } + + /** + * @deprecated 方法已过期,已有新的方法 + */ + @Deprecated + public static void openAnvil(Player p) { + EntityPlayer player = ((CraftPlayer) p).getHandle(); + AnvilContainer_V1_9_4 container = new AnvilContainer_V1_9_4(player); + int c = player.nextContainerCounter(); player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(c, "minecraft:anvil", new ChatMessage("Repairing"), 0)); - player.activeContainer = container; - player.activeContainer.windowId = c; - player.activeContainer.addSlotListener(player); - } + player.activeContainer = container; + player.activeContainer.windowId = c; + player.activeContainer.addSlotListener(player); + } } diff --git a/src/main/java/me/skymc/taboolib/bookformatter/BookAchievement.java b/src/main/java/me/skymc/taboolib/bookformatter/BookAchievement.java index ea1c284..6232998 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/BookAchievement.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/BookAchievement.java @@ -1,87 +1,55 @@ package me.skymc.taboolib.bookformatter; -import static org.bukkit.Achievement.ACQUIRE_IRON; -import static org.bukkit.Achievement.BAKE_CAKE; -import static org.bukkit.Achievement.BOOKCASE; -import static org.bukkit.Achievement.BREED_COW; -import static org.bukkit.Achievement.BREW_POTION; -import static org.bukkit.Achievement.BUILD_BETTER_PICKAXE; -import static org.bukkit.Achievement.BUILD_FURNACE; -import static org.bukkit.Achievement.BUILD_HOE; -import static org.bukkit.Achievement.BUILD_PICKAXE; -import static org.bukkit.Achievement.BUILD_SWORD; -import static org.bukkit.Achievement.BUILD_WORKBENCH; -import static org.bukkit.Achievement.COOK_FISH; -import static org.bukkit.Achievement.DIAMONDS_TO_YOU; -import static org.bukkit.Achievement.ENCHANTMENTS; -import static org.bukkit.Achievement.END_PORTAL; -import static org.bukkit.Achievement.EXPLORE_ALL_BIOMES; -import static org.bukkit.Achievement.FLY_PIG; -import static org.bukkit.Achievement.FULL_BEACON; -import static org.bukkit.Achievement.GET_BLAZE_ROD; -import static org.bukkit.Achievement.GET_DIAMONDS; -import static org.bukkit.Achievement.GHAST_RETURN; -import static org.bukkit.Achievement.KILL_COW; -import static org.bukkit.Achievement.KILL_ENEMY; -import static org.bukkit.Achievement.KILL_WITHER; -import static org.bukkit.Achievement.MAKE_BREAD; -import static org.bukkit.Achievement.MINE_WOOD; -import static org.bukkit.Achievement.NETHER_PORTAL; -import static org.bukkit.Achievement.ON_A_RAIL; -import static org.bukkit.Achievement.OPEN_INVENTORY; -import static org.bukkit.Achievement.OVERKILL; -import static org.bukkit.Achievement.OVERPOWERED; -import static org.bukkit.Achievement.SNIPE_SKELETON; -import static org.bukkit.Achievement.SPAWN_WITHER; -import static org.bukkit.Achievement.THE_END; - -import java.util.HashMap; - import org.bukkit.Achievement; +import java.util.HashMap; + +import static org.bukkit.Achievement.*; + public final class BookAchievement { - - private static final HashMap achievements = new HashMap<>(); - - static { - achievements.put(OPEN_INVENTORY, "openInventory"); - achievements.put(MINE_WOOD, "mineWood"); - achievements.put(BUILD_WORKBENCH, "buildWorkBench"); - achievements.put(BUILD_PICKAXE, "buildPickaxe"); - achievements.put(BUILD_FURNACE, "buildFurnace"); - achievements.put(ACQUIRE_IRON, "aquireIron"); - achievements.put(BUILD_HOE, "buildHoe"); - achievements.put(MAKE_BREAD, "makeBread"); - achievements.put(BAKE_CAKE,"bakeCake"); - achievements.put(BUILD_BETTER_PICKAXE,"buildBetterPickaxe"); - achievements.put(COOK_FISH,"cookFish"); - achievements.put(ON_A_RAIL,"onARail"); - achievements.put(BUILD_SWORD,"buildSword"); - achievements.put(KILL_ENEMY,"killEnemy"); - achievements.put(KILL_COW,"killCow"); - achievements.put(FLY_PIG,"flyPig"); - achievements.put(SNIPE_SKELETON,"snipeSkeleton"); - achievements.put(GET_DIAMONDS,"diamonds"); - achievements.put(NETHER_PORTAL,"portal"); - achievements.put(GHAST_RETURN,"ghast"); - achievements.put(GET_BLAZE_ROD,"blazerod"); - achievements.put(BREW_POTION,"potion"); - achievements.put(END_PORTAL,"thEnd"); - achievements.put(THE_END,"theEnd2"); - achievements.put(ENCHANTMENTS,"enchantments"); - achievements.put(OVERKILL,"overkill"); - achievements.put(BOOKCASE,"bookacase"); - achievements.put(EXPLORE_ALL_BIOMES,"exploreAllBiomes"); - achievements.put(SPAWN_WITHER,"spawnWither"); - achievements.put(KILL_WITHER,"killWither"); - achievements.put(FULL_BEACON,"fullBeacon"); - achievements.put(BREED_COW,"breedCow"); - achievements.put(DIAMONDS_TO_YOU,"diamondsToYou"); + + private static final HashMap achievements = new HashMap<>(); + + static { + achievements.put(OPEN_INVENTORY, "openInventory"); + achievements.put(MINE_WOOD, "mineWood"); + achievements.put(BUILD_WORKBENCH, "buildWorkBench"); + achievements.put(BUILD_PICKAXE, "buildPickaxe"); + achievements.put(BUILD_FURNACE, "buildFurnace"); + achievements.put(ACQUIRE_IRON, "aquireIron"); + achievements.put(BUILD_HOE, "buildHoe"); + achievements.put(MAKE_BREAD, "makeBread"); + achievements.put(BAKE_CAKE, "bakeCake"); + achievements.put(BUILD_BETTER_PICKAXE, "buildBetterPickaxe"); + achievements.put(COOK_FISH, "cookFish"); + achievements.put(ON_A_RAIL, "onARail"); + achievements.put(BUILD_SWORD, "buildSword"); + achievements.put(KILL_ENEMY, "killEnemy"); + achievements.put(KILL_COW, "killCow"); + achievements.put(FLY_PIG, "flyPig"); + achievements.put(SNIPE_SKELETON, "snipeSkeleton"); + achievements.put(GET_DIAMONDS, "diamonds"); + achievements.put(NETHER_PORTAL, "portal"); + achievements.put(GHAST_RETURN, "ghast"); + achievements.put(GET_BLAZE_ROD, "blazerod"); + achievements.put(BREW_POTION, "potion"); + achievements.put(END_PORTAL, "thEnd"); + achievements.put(THE_END, "theEnd2"); + achievements.put(ENCHANTMENTS, "enchantments"); + achievements.put(OVERKILL, "overkill"); + achievements.put(BOOKCASE, "bookacase"); + achievements.put(EXPLORE_ALL_BIOMES, "exploreAllBiomes"); + achievements.put(SPAWN_WITHER, "spawnWither"); + achievements.put(KILL_WITHER, "killWither"); + achievements.put(FULL_BEACON, "fullBeacon"); + achievements.put(BREED_COW, "breedCow"); + achievements.put(DIAMONDS_TO_YOU, "diamondsToYou"); achievements.put(OVERPOWERED, "overpowered"); - } + } /** * Gets the json id from the bukkit achievement passed as argument + * * @param achievement the achievement * @return the achievement's id or null if not found */ @@ -89,7 +57,7 @@ public final class BookAchievement { return achievements.get(achievement); } - private BookAchievement(){ - + private BookAchievement() { + } } diff --git a/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java b/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java index bb22245..acdcff2 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java @@ -1,5 +1,13 @@ package me.skymc.taboolib.bookformatter; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.chat.ComponentSerializer; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.BookMeta; + import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -8,21 +16,11 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.BookMeta; - -import lombok.Getter; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import net.md_5.bungee.chat.ComponentSerializer; - /** * The NMS helper for all the Book-API */ public final class BookReflection { - + private static final String version; private static final boolean doubleHands; @@ -31,11 +29,11 @@ public final class BookReflection { private static final Method chatSerializerA; private static final Method craftPlayerGetHandle; - + //This method takes an enum that represents the player's hand only in versions >= 1.9 //In the other versions it only takes the nms item private static final Method entityPlayerOpenBook; - + //only version >= 1.9 private static final Object[] hands; @@ -56,7 +54,7 @@ public final class BookReflection { final int major, minor; Pattern pattern = Pattern.compile("v([0-9]+)_([0-9]+)"); Matcher m = pattern.matcher(version); - if(m.find()) { + if (m.find()) { major = Integer.parseInt(m.group(1)); minor = Integer.parseInt(m.group(2)); } else { @@ -68,7 +66,7 @@ public final class BookReflection { craftMetaBookField = craftMetaBookClass.getDeclaredField("pages"); craftMetaBookField.setAccessible(true); Class chatSerializer = getNmsClass("IChatBaseComponent$ChatSerializer", false); - if(chatSerializer == null) + if (chatSerializer == null) chatSerializer = getNmsClass("ChatSerializer"); chatSerializerA = chatSerializer.getDeclaredMethod("a", String.class); @@ -78,7 +76,7 @@ public final class BookReflection { final Class entityPlayerClass = getNmsClass("EntityPlayer"); final Class itemStackClass = getNmsClass("ItemStack"); - if(doubleHands) { + if (doubleHands) { final Class enumHandClass = getNmsClass("EnumHand"); entityPlayerOpenBook = entityPlayerClass.getMethod("a", itemStackClass, enumHandClass); hands = enumHandClass.getEnumConstants(); @@ -110,7 +108,8 @@ public final class BookReflection { /** * Sets the pages of the book to the components json equivalent - * @param meta the book meta to change + * + * @param meta the book meta to change * @param components the pages of the book */ @SuppressWarnings("unchecked")//reflections = unchecked warnings @@ -118,7 +117,7 @@ public final class BookReflection { try { List pages = (List) craftMetaBookField.get(meta); pages.clear(); - for(BaseComponent[] c : components) { + for (BaseComponent[] c : components) { final String json = ComponentSerializer.toString(c); //System.out.println("page:" + json); //Debug pages.add(chatSerializerA.invoke(null, json)); @@ -127,17 +126,18 @@ public final class BookReflection { throw new UnsupportedVersionException(e); } } - + /** * Append the pages of the book to the components json equivalent - * @param meta the book meta to change + * + * @param meta the book meta to change * @param components the pages of the book */ @SuppressWarnings("unchecked")//reflections = unchecked warnings public static void addPages(BookMeta meta, BaseComponent[][] components) { - try { + try { List pages = (List) craftMetaBookField.get(meta); - for(BaseComponent[] c : components) { + for (BaseComponent[] c : components) { final String json = ComponentSerializer.toString(c); //System.out.println("page:" + json); //Debug pages.add(chatSerializerA.invoke(null, json)); @@ -149,8 +149,9 @@ public final class BookReflection { /** * Opens the book to a player (the player needs to have the book in one of his hands) - * @param player the player - * @param book the book to open + * + * @param player the player + * @param book the book to open * @param offHand false if the book is in the right hand, true otherwise */ public static void openBook(Player player, ItemStack book, boolean offHand) { @@ -161,7 +162,7 @@ public final class BookReflection { entityHumanPlayerConnection.get(toNms(player)), createBookOpenPacket() );*/ - if(doubleHands) { + if (doubleHands) { entityPlayerOpenBook.invoke( toNms(player), nmsCopy(book), @@ -193,24 +194,27 @@ public final class BookReflection { /** * Translates an ItemStack to his Chat-Component equivalent + * * @param item the item to be converted * @return a Chat-Component equivalent of the parameter */ public static BaseComponent[] itemToComponents(ItemStack item) { - return jsonToComponents(itemToJson(item)); + return jsonToComponents(itemToJson(item)); } /** * Translates a json string to his Chat-Component equivalent + * * @param json the json string to be converted * @return a Chat-Component equivalent of the parameter */ public static BaseComponent[] jsonToComponents(String json) { - return new BaseComponent[] { new TextComponent(json) }; + return new BaseComponent[]{new TextComponent(json)}; } /** * Translates an ItemStack to his json equivalent + * * @param item the item to be converted * @return a json equivalent of the parameter */ @@ -234,16 +238,19 @@ public final class BookReflection { */ public static class UnsupportedVersionException extends RuntimeException { /** - * serialVersionUID - */ - private static final long serialVersionUID = 6835583513394319946L; - - /** + * serialVersionUID + */ + private static final long serialVersionUID = 6835583513394319946L; + + /** * The current running version */ - @Getter private final String version = BookReflection.version; + public String getVersion() { + return version; + } + public UnsupportedVersionException(Exception e) { super("Error while executing reflections, submit to developers the following log (version: " + BookReflection.version + ")", e); } @@ -252,10 +259,11 @@ public final class BookReflection { /** * Gets the EntityPlayer handled by the argument + * * @param player the Player handler * @return the handled class * @throws InvocationTargetException when some problems are found with the reflection - * @throws IllegalAccessException when some problems are found with the reflection + * @throws IllegalAccessException when some problems are found with the reflection */ public static Object toNms(Player player) throws InvocationTargetException, IllegalAccessException { return craftPlayerGetHandle.invoke(player); @@ -263,10 +271,11 @@ public final class BookReflection { /** * Creates a NMS copy of the parameter + * * @param item the ItemStack to be nms-copied * @return a NMS-ItemStack that is the equivalent of the one passed as argument * @throws InvocationTargetException when some problems are found with the reflection - * @throws IllegalAccessException when some problems are found with the reflection + * @throws IllegalAccessException when some problems are found with the reflection */ public static Object nmsCopy(ItemStack item) throws InvocationTargetException, IllegalAccessException { return craftItemStackAsNMSCopy.invoke(null, item); @@ -275,8 +284,8 @@ public final class BookReflection { public static Class getNmsClass(String className, boolean log) { try { return Class.forName("net.minecraft.server." + version + "." + className); - } catch(ClassNotFoundException e) { - if(log) + } catch (ClassNotFoundException e) { + if (log) e.printStackTrace(); return null; } @@ -290,7 +299,7 @@ public final class BookReflection { private static Class getCraftClass(String path) { try { return Class.forName("org.bukkit.craftbukkit." + version + "." + path); - } catch(ClassNotFoundException e) { + } catch (ClassNotFoundException e) { 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 fe41dd5..5851a0b 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java @@ -1,8 +1,5 @@ package me.skymc.taboolib.bookformatter.action; -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import lombok.experimental.Accessors; import net.md_5.bungee.api.chat.ClickEvent; /** @@ -10,15 +7,17 @@ import net.md_5.bungee.api.chat.ClickEvent; * @since 2018-03-08 22:38:04 */ public interface ClickAction { - + /** * Get the Chat-Component action + * * @return the Chat-Component action */ ClickEvent.Action action(); /** * The value paired to the action + * * @return the value paired tot the action */ String value(); @@ -26,6 +25,7 @@ public interface ClickAction { /** * Creates a command action: when the player clicks, the command passed as parameter gets executed with the clicker as sender + * * @param command the command to be executed * @return a new ClickAction */ @@ -35,6 +35,7 @@ public interface ClickAction { /** * Creates a suggest_command action: when the player clicks, the book closes and the chat opens with the parameter written into it + * * @param command the command to be suggested * @return a new ClickAction */ @@ -44,11 +45,12 @@ public interface ClickAction { /** * Creates a open_utl action: when the player clicks the url passed as argument will open in the browser + * * @param url the url to be opened * @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 throw new IllegalArgumentException("Invalid url: \"" + url + "\", it should start with http:// or https://"); @@ -56,6 +58,7 @@ public interface ClickAction { /** * Creates a change_page action: when the player clicks the book page will be set at the value passed as argument + * * @param page the new page * @return a new ClickAction */ @@ -63,11 +66,32 @@ public interface ClickAction { return new SimpleClickAction(ClickEvent.Action.CHANGE_PAGE, Integer.toString(page)); } - @Getter - @Accessors(fluent = true) - @RequiredArgsConstructor class SimpleClickAction implements ClickAction { + private final ClickEvent.Action action; private final String value; + + public SimpleClickAction(ClickEvent.Action action, String value) { + this.action = action; + this.value = value; + } + + public ClickEvent.Action getAction() { + return action; + } + + public String getValue() { + return value; + } + + @Override + public ClickEvent.Action action() { + return null; + } + + @Override + public String value() { + return null; + } } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java b/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java index 5eb1bc9..9505c3c 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java @@ -1,18 +1,15 @@ package me.skymc.taboolib.bookformatter.action; -import java.util.UUID; - -import org.bukkit.Achievement; -import org.bukkit.entity.Entity; -import org.bukkit.inventory.ItemStack; - -import lombok.Getter; -import lombok.experimental.Accessors; import me.skymc.taboolib.bookformatter.BookAchievement; import me.skymc.taboolib.bookformatter.BookReflection; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Achievement; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; /** * @author sky @@ -20,14 +17,17 @@ import net.md_5.bungee.api.chat.TextComponent; */ @SuppressWarnings("deprecation") public interface HoverAction { - + /** * Get the Chat-Component action + * * @return the Chat-Component action */ HoverEvent.Action action(); + /** * The value paired to the action + * * @return the value paired tot the action */ BaseComponent[] value(); @@ -35,6 +35,7 @@ public interface HoverAction { /** * Creates a show_text action: when the component is hovered the text used as parameter will be displayed + * * @param text the text to display * @return a new HoverAction instance */ @@ -44,6 +45,7 @@ public interface HoverAction { /** * Creates a show_text action: when the component is hovered the text used as parameter will be displayed + * * @param text the text to display * @return a new HoverAction instance */ @@ -53,6 +55,7 @@ public interface HoverAction { /** * Creates a show_item action: when the component is hovered some item information will be displayed + * * @param item a component array representing item to display * @return a new HoverAction instance */ @@ -62,6 +65,7 @@ public interface HoverAction { /** * Creates a show_item action: when the component is hovered some item information will be displayed + * * @param item the item to display * @return a new HoverAction instance */ @@ -71,6 +75,7 @@ public interface HoverAction { /** * Creates a show_entity action: when the component is hovered some entity information will be displayed + * * @param entity a component array representing the item to display * @return a new HoverAction instance */ @@ -80,6 +85,7 @@ public interface HoverAction { /** * Creates a show_entity action: when the component is hovered some entity information will be displayed + * * @param uuid the entity's UniqueId * @param type the entity's type * @param name the entity's name @@ -95,15 +101,17 @@ public interface HoverAction { /** * Creates a show_entity action: when the component is hovered some entity information will be displayed + * * @param entity the item to display * @return a new HoverAction instance */ - static HoverAction showEntity(Entity entity) { + static HoverAction showEntity(Entity entity) { return showEntity(entity.getUniqueId(), entity.getType().getName(), entity.getName()); } /** * Creates a show_achievement action: when the component is hovered the achievement information will be displayed + * * @param achievementId the id of the achievement to display * @return a new HoverAction instance */ @@ -113,15 +121,17 @@ public interface HoverAction { /** * Creates a show_achievement action: when the component is hovered the achievement information will be displayed + * * @param achievement the achievement to display * @return a new HoverAction instance */ - static HoverAction showAchievement(Achievement achievement) { + static HoverAction showAchievement(Achievement achievement) { return showAchievement(BookAchievement.toId(achievement)); } /** * Creates a show_achievement action: when the component is hovered the statistic information will be displayed + * * @param statisticId the id of the statistic to display * @return a new HoverAction instance */ @@ -129,8 +139,6 @@ public interface HoverAction { return new SimpleHoverAction(HoverEvent.Action.SHOW_ACHIEVEMENT, new TextComponent("statistic." + statisticId)); } - @Getter - @Accessors(fluent = true) class SimpleHoverAction implements HoverAction { private final HoverEvent.Action action; private final BaseComponent[] value; @@ -139,5 +147,23 @@ public interface HoverAction { this.action = action; this.value = value; } + + public HoverEvent.Action getAction() { + return action; + } + + public BaseComponent[] getValue() { + return value; + } + + @Override + public HoverEvent.Action action() { + return null; + } + + @Override + public BaseComponent[] value() { + return new BaseComponent[0]; + } } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java b/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java index 5160859..c4d424c 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java @@ -1,8 +1,5 @@ package me.skymc.taboolib.bookformatter.builder; -import lombok.Getter; -import lombok.Setter; -import lombok.experimental.Accessors; import me.skymc.taboolib.bookformatter.action.ClickAction; import me.skymc.taboolib.bookformatter.action.HoverAction; import net.md_5.bungee.api.chat.BaseComponent; @@ -14,31 +11,54 @@ import net.md_5.bungee.api.chat.TextComponent; * @author sky * @since 2018-03-08 22:37:27 */ -@Setter -@Getter -@Accessors(fluent = true, chain = true) public class TextBuilder { - + private String text = ""; private ClickAction onClick = null; private HoverAction onHover = null; - public TextBuilder() {} - + public String getText() { + return text; + } + + public ClickAction getClick() { + return onClick; + } + + public HoverAction getHover() { + return onHover; + } + + public void text(String text) { + this.text = text; + } + + public void onClick(ClickAction onClick) { + this.onClick = onClick; + } + + public void onHover(HoverAction onHover) { + this.onHover = onHover; + } + + public TextBuilder() { + } + public TextBuilder(String text) { - this.text = text; + this.text = text; } /** * Creates the component representing the built text + * * @return the component representing the built text */ public BaseComponent build() { TextComponent res = new TextComponent(text); - if(onClick != null) { + if (onClick != null) { res.setClickEvent(new ClickEvent(onClick.action(), onClick.value())); } - if(onHover != null) { + if (onHover != null) { res.setHoverEvent(new HoverEvent(onHover.action(), onHover.value())); } return res; @@ -46,10 +66,11 @@ public class TextBuilder { /** * Creates a new TextBuilder with the parameter as his initial text + * * @param text initial text * @return a new TextBuilder with the parameter as his initial text */ public static TextBuilder of(String text) { - return new TextBuilder().text(text); + return new TextBuilder(text); } } diff --git a/src/main/java/me/skymc/taboolib/commands/MainCommands.java b/src/main/java/me/skymc/taboolib/commands/MainCommands.java index 3e6704b..9209fcc 100644 --- a/src/main/java/me/skymc/taboolib/commands/MainCommands.java +++ b/src/main/java/me/skymc/taboolib/commands/MainCommands.java @@ -1,100 +1,67 @@ package me.skymc.taboolib.commands; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; - -import me.skymc.taboolib.commands.sub.AttributesCommand; -import me.skymc.taboolib.commands.sub.EnchantCommand; -import me.skymc.taboolib.commands.sub.FlagCommand; -import me.skymc.taboolib.commands.sub.HelpCommand; -import me.skymc.taboolib.commands.sub.ImportCommand; -import me.skymc.taboolib.commands.sub.InfoCommand; -import me.skymc.taboolib.commands.sub.ItemCommand; -import me.skymc.taboolib.commands.sub.PotionCommand; -import me.skymc.taboolib.commands.sub.SaveCommand; -import me.skymc.taboolib.commands.sub.SlotCommand; -import me.skymc.taboolib.commands.sub.TagDeleteCommand; -import me.skymc.taboolib.commands.sub.TagPrefixCommand; -import me.skymc.taboolib.commands.sub.TagSuffixCommand; -import me.skymc.taboolib.commands.sub.VariableGetCommand; -import me.skymc.taboolib.commands.sub.VariableSetCommand; +import com.ilummc.tlib.resources.TLocale; +import me.skymc.taboolib.commands.sub.*; import me.skymc.taboolib.commands.sub.cycle.CycleCommand; import me.skymc.taboolib.commands.sub.itemlist.ItemListCommand; import me.skymc.taboolib.commands.sub.shell.ShellCommand; import me.skymc.taboolib.commands.sub.sounds.SoundsCommand; import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.message.MsgUtils; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; -public class MainCommands implements CommandExecutor{ +import java.lang.reflect.Parameter; - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (args.length == 0 || args[0].equalsIgnoreCase("help")) { - new HelpCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("itemreload") || args[0].equalsIgnoreCase("ireload")) { - ItemUtils.reloadItemCache(); - ItemUtils.reloadItemName(); - MsgUtils.send(sender, "重载成功"); - } - else if (args[0].equalsIgnoreCase("save")) { - new SaveCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("enchants")) { - new EnchantCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("potions")) { - new PotionCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("flags")) { - new FlagCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("attributes")) { - new AttributesCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("slots")) { - new SlotCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("importdata")) { - new ImportCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("iteminfo")) { - new InfoCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("itemlist")) { - new ItemListCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("item") || args[0].equalsIgnoreCase("i")) { - new ItemCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("setvariable")) { - new VariableSetCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("getvariable")) { - new VariableGetCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("shell") || args[0].equalsIgnoreCase("s")) { - new ShellCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("cycle") || args[0].equalsIgnoreCase("c")) { - new CycleCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("sounds")) { - new SoundsCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("tagprefix")) { - new TagPrefixCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("tagsuffix")) { - new TagSuffixCommand(sender, args); - } - else if (args[0].equalsIgnoreCase("tagdelete")) { - new TagDeleteCommand(sender, args); - } - else { - MsgUtils.send(sender, "&4指令错误"); - } - return true; - } +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")) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.HELP"); + } else if (args[0].equalsIgnoreCase("save")) { + new SaveCommand(sender, args); + } else if (args[0].equalsIgnoreCase("enchants")) { + new EnchantCommand(sender, args); + } else if (args[0].equalsIgnoreCase("potions")) { + new PotionCommand(sender, args); + } else if (args[0].equalsIgnoreCase("flags")) { + new FlagCommand(sender, args); + } else if (args[0].equalsIgnoreCase("attributes")) { + new AttributesCommand(sender, args); + } else if (args[0].equalsIgnoreCase("slots")) { + new SlotCommand(sender, args); + } else if (args[0].equalsIgnoreCase("importdata")) { + new ImportCommand(sender, args); + } else if (args[0].equalsIgnoreCase("iteminfo")) { + new InfoCommand(sender, args); + } else if (args[0].equalsIgnoreCase("itemlist")) { + new ItemListCommand(sender, args); + } else if (args[0].equalsIgnoreCase("item") || args[0].equalsIgnoreCase("i")) { + new ItemCommand(sender, args); + } else if (args[0].equalsIgnoreCase("setvariable")) { + new VariableSetCommand(sender, args); + } else if (args[0].equalsIgnoreCase("getvariable")) { + new VariableGetCommand(sender, args); + } else if (args[0].equalsIgnoreCase("shell") || args[0].equalsIgnoreCase("s")) { + new ShellCommand(sender, args); + } else if (args[0].equalsIgnoreCase("cycle") || args[0].equalsIgnoreCase("c")) { + new CycleCommand(sender, args); + } else if (args[0].equalsIgnoreCase("sounds")) { + new SoundsCommand(sender, args); + } else if (args[0].equalsIgnoreCase("tagprefix")) { + new TagPrefixCommand(sender, args); + } else if (args[0].equalsIgnoreCase("tagsuffix")) { + new TagSuffixCommand(sender, args); + } else if (args[0].equalsIgnoreCase("tagdelete")) { + new TagDeleteCommand(sender, args); + } else if (args[0].equalsIgnoreCase("itemreload") || args[0].equalsIgnoreCase("ireload")) { + ItemUtils.reloadItemCache(); + ItemUtils.reloadItemName(); + TLocale.sendTo(sender, "COMMANDS.RELOAD.SUCCESS-NORMAL"); + } else { + TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); + } + return true; + } } diff --git a/src/main/java/me/skymc/taboolib/commands/SubCommand.java b/src/main/java/me/skymc/taboolib/commands/SubCommand.java index 37dea74..9082192 100644 --- a/src/main/java/me/skymc/taboolib/commands/SubCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/SubCommand.java @@ -3,36 +3,34 @@ package me.skymc.taboolib.commands; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + public abstract class SubCommand { - - public CommandSender sender; - public String[] args; - - public boolean returnValue = false; - - public SubCommand(CommandSender sender, String[] args) { - this.sender = sender; - this.args = args; - } - - public boolean setReturn(boolean returnValue) { - return this.returnValue = returnValue; - } - - public boolean isPlayer() { - return sender instanceof Player; - } - - public boolean command() { - return returnValue; - } - - public String getArgs(int size) { - StringBuilder sb = new StringBuilder(); - for (int i = size ; i < args.length ; i++) { - sb.append(args[i]); - sb.append(" "); - } - return sb.toString().substring(0, sb.length() - 1); - } + + public CommandSender sender; + public String[] args; + + public boolean returnValue = false; + + public SubCommand(CommandSender sender, String[] args) { + this.sender = sender; + this.args = args; + } + + public boolean setReturn(boolean returnValue) { + return this.returnValue = returnValue; + } + + public boolean isPlayer() { + return sender instanceof Player; + } + + public boolean command() { + return returnValue; + } + + public String getArgs(int size) { + return IntStream.range(size, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim(); + } } 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 9d1b38e..7c421e4 100644 --- a/src/main/java/me/skymc/taboolib/commands/language/Language2Command.java +++ b/src/main/java/me/skymc/taboolib/commands/language/Language2Command.java @@ -30,7 +30,7 @@ public class Language2Command implements CommandExecutor { else if (args[0].equalsIgnoreCase("reload")) { MsgUtils.send(sender, "§7重载中.."); long time = System.currentTimeMillis(); - Main.getExampleLangauge2().reload(); + Main.getExampleLanguage2().reload(); MsgUtils.send(sender, "§7重载完成! 耗时: &f" + (System.currentTimeMillis() - time) + "ms"); } else if (args[0].equalsIgnoreCase("send")) { @@ -42,7 +42,7 @@ public class Language2Command implements CommandExecutor { long time = System.currentTimeMillis(); // 获取语言文件 - Language2Value value = Main.getExampleLangauge2().get(args[2]); + Language2Value value = Main.getExampleLanguage2().get(args[2]); // 如果有变量参数 if (args.length > 3) { int i = 0; 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 f1294b4..ba8664f 100644 --- a/src/main/java/me/skymc/taboolib/commands/locale/TabooLibLocaleCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/locale/TabooLibLocaleCommand.java @@ -1,15 +1,16 @@ package me.skymc.taboolib.commands.locale; -import java.util.ArrayList; -import java.util.List; - +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; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import com.ilummc.tlib.resources.TLocale; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; /** * @author sky @@ -17,59 +18,59 @@ import com.ilummc.tlib.resources.TLocale; */ public class TabooLibLocaleCommand implements CommandExecutor { - @Override - public boolean onCommand(CommandSender sender, Command arg1, String label, String[] args) { - if (args.length == 0) { - TLocale.sendTo(sender, "commands-taboolocale-helps", label); - } - else if (args[0].equalsIgnoreCase("send")) { - send(sender, args); - } - else if (args[0].equalsIgnoreCase("reload")) { - reload(sender); - } - else { - TLocale.sendTo(sender, "commands-taboolocale-invalid"); - } - return true; - } - - void send(CommandSender sender, String[] args) { - if (args.length < 3) { - TLocale.sendTo(sender, "commands-taboolocale-send-empty"); - return; - } - - List target = new ArrayList<>(); - if (args[1].equalsIgnoreCase("all")) { - target.addAll(Bukkit.getOnlinePlayers()); - } else { - Player player = Bukkit.getPlayerExact(args[1]); - if (player == null) { - TLocale.sendTo(sender, "commands-taboolocale-send-offline", args[1]); - return; - } - target.add(player); - } - - if (args.length > 3) { - String[] vars = new String[args.length - 3]; - for (int i = 3 ; i < args.length ; i++) { - vars[i - 3] = args[i]; - } - target.forEach(x -> TLocale.sendTo(x, args[2], vars)); - } else { - target.forEach(x -> TLocale.sendTo(x, args[2])); - } - - if (sender instanceof Player) { - TLocale.sendTo(sender, "commands-taboolocale-send-success"); - } - } - - void reload(CommandSender sender) { - TLocale.reload(); - TLocale.sendTo(sender, "commands-taboolocale-reload"); - } + @Override + public boolean onCommand(CommandSender sender, Command arg1, String label, String[] args) { + if (args.length == 0) { + sender.sendMessage("§f"); + sender.sendMessage("§b§l----- §3§lTabooLibLoacle Commands §b§l-----"); + sender.sendMessage("§f"); + sender.sendMessage("§f /tloacle send §8[§7玩家/ALL§8] §8[§7语言§8] §8<§7变量§8> §6- §e发送语言提示"); + sender.sendMessage("§f /tloacle reload §6- §e重载语言库"); + sender.sendMessage("§f"); + } else if (args[0].equalsIgnoreCase("send")) { + send(sender, args); + } else if (args[0].equalsIgnoreCase("reload")) { + reload(sender); + } else { + MsgUtils.send(sender, "§4参数错误"); + } + return true; + } + + void send(CommandSender sender, String[] args) { + if (args.length < 3) { + MsgUtils.send(sender, "§4参数错误"); + return; + } + + List target = new ArrayList<>(); + if (args[1].equalsIgnoreCase("all")) { + target.addAll(Bukkit.getOnlinePlayers()); + } else { + Player player = Bukkit.getPlayerExact(args[1]); + if (player == null) { + MsgUtils.send(sender, "§4玩家不在线"); + return; + } + target.add(player); + } + + if (args.length > 3) { + String[] vars = new String[args.length - 3]; + IntStream.range(3, args.length).forEach(i -> vars[i - 3] = args[i]); + target.forEach(x -> TLocale.sendTo(x, args[2], vars)); + } else { + target.forEach(x -> TLocale.sendTo(x, args[2])); + } + + if (sender instanceof Player) { + MsgUtils.send(sender, "§7信息已发送"); + } + } + + void reload(CommandSender sender) { + TLocale.reload(); + MsgUtils.send(sender, "§7重载完成"); + } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/AttributesCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/AttributesCommand.java index 48ab718..d90bbc8 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/AttributesCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/AttributesCommand.java @@ -1,6 +1,8 @@ package me.skymc.taboolib.commands.sub; +import com.ilummc.tlib.resources.TLocale; import org.bukkit.command.CommandSender; +import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import me.skymc.taboolib.commands.SubCommand; @@ -8,28 +10,17 @@ import me.skymc.taboolib.jsonformatter.JSONFormatter; import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent; import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent; +import java.util.Arrays; + public class AttributesCommand extends SubCommand { public AttributesCommand(CommandSender sender, String[] args) { super(sender, args); - - sender.sendMessage("§f"); - sender.sendMessage("§b§l----- §3§lItemStack Attributes §b§l-----"); - sender.sendMessage("§f"); - - String[] attributes = new String[] { "damage", "speed", "attackspeed", "health", "knockback", "armor", "luck" }; - - for (String name : attributes) { - if (isPlayer()) { - JSONFormatter json = new JSONFormatter(); - json.append(" §7- §f" + name); - json.appendHoverClick(" §8(点击复制)", new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(name)); - json.send((Player) sender); - } - else { - sender.sendMessage(" §7- §f" + name); - } - } - sender.sendMessage("§f"); + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ATTRIBUTES.HEAD"); + + Arrays.stream(new String[] { "damage", "speed", "attackspeed", "health", "knockback", "armor", "luck" }).forEach(attribute -> TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ATTRIBUTES.BODY", attribute)); + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ATTRIBUTES.FOOT"); } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/EnchantCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/EnchantCommand.java index ecb5a78..2ea2d18 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/EnchantCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/EnchantCommand.java @@ -1,35 +1,22 @@ package me.skymc.taboolib.commands.sub; +import com.ilummc.tlib.resources.TLocale; +import me.skymc.taboolib.commands.SubCommand; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import me.skymc.taboolib.commands.SubCommand; -import me.skymc.taboolib.jsonformatter.JSONFormatter; -import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent; -import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent; +import java.util.Arrays; public class EnchantCommand extends SubCommand { - @SuppressWarnings("deprecation") - public EnchantCommand(CommandSender sender, String[] args) { - super(sender, args); - - sender.sendMessage("§f"); - sender.sendMessage("§b§l----- §3§lItemStack Enchantments §b§l-----"); - sender.sendMessage("§f"); - - for (Enchantment enchant : Enchantment.values()) { - if (isPlayer()) { - JSONFormatter json = new JSONFormatter(); - json.append(" §7- §f" + enchant.getId() + ". " + enchant.getName()); - json.appendHoverClick(" §8(点击复制)", new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(enchant.getName())); - json.send((Player) sender); - } - else { - sender.sendMessage(" §7- §f" + enchant.getId() + ". " + enchant.getName()); - } - } - sender.sendMessage("§f"); - } + @SuppressWarnings("deprecation") + public EnchantCommand(CommandSender sender, String[] args) { + super(sender, args); + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ENCHANTS.HEAD"); + + Arrays.stream(Enchantment.values()).forEach(enchant -> TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ENCHANTS.BODY", String.valueOf(enchant.getId()), enchant.getName())); + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ENCHANTS.FOOT"); + } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/FlagCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/FlagCommand.java index 5ea1ad4..0ad3cf2 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/FlagCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/FlagCommand.java @@ -1,6 +1,8 @@ package me.skymc.taboolib.commands.sub; +import com.ilummc.tlib.resources.TLocale; import org.bukkit.command.CommandSender; +import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemFlag; @@ -9,26 +11,17 @@ import me.skymc.taboolib.jsonformatter.JSONFormatter; import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent; import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent; +import java.util.Arrays; + public class FlagCommand extends SubCommand { public FlagCommand(CommandSender sender, String[] args) { super(sender, args); - - sender.sendMessage("§f"); - sender.sendMessage("§b§l----- §3§lItemStack Flags §b§l-----"); - sender.sendMessage("§f"); - - for (ItemFlag flag : ItemFlag.values()) { - if (isPlayer()) { - JSONFormatter json = new JSONFormatter(); - json.append(" §7- §f" + flag.name()); - json.appendHoverClick(" §8(点击复制)", new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(flag.name())); - json.send((Player) sender); - } - else { - sender.sendMessage(" §7- §f" + flag.name()); - } - } - sender.sendMessage("§f"); + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.FLAGS.HEAD"); + + Arrays.stream(ItemFlag.values()).forEach(itemFlag -> TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ENCHANTS.BODY", itemFlag.name())); + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.FLAGS.FOOT"); } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/HelpCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/HelpCommand.java deleted file mode 100644 index 7a9e611..0000000 --- a/src/main/java/me/skymc/taboolib/commands/sub/HelpCommand.java +++ /dev/null @@ -1,84 +0,0 @@ -package me.skymc.taboolib.commands.sub; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map.Entry; - -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; - -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.commands.SubCommand; -import me.skymc.taboolib.jsonformatter.JSONFormatter; -import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent; -import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent; - -public class HelpCommand extends SubCommand { - - public HelpCommand(CommandSender sender, String[] args) { - super(sender, args); - - HashMap helps = new LinkedHashMap<>(); - helps.put("/taboolib save §8[§7名称§8]", "§e保存手中物品"); - helps.put("/taboolib item §8[§7名称§8] §8<§7玩家§8> §8<§7数量§8>", "§e给予玩家物品"); - helps.put("/taboolib iteminfo", "§e查看物品信息"); - helps.put("/taboolib itemlist", "§e查看所有物品"); - helps.put("/taboolib itemreload", "§e重载物品缓存"); - helps.put("§a", null); - helps.put("/taboolib attributes", "§e查看所有属性"); - helps.put("/taboolib enchants", "§e查看所有附魔"); - helps.put("/taboolib potions", "§e查看所有药水"); - helps.put("/taboolib flags", "§e查看所有标签"); - helps.put("/taboolib slots", "§e查看所有部位"); - helps.put("/taboolib sounds", "§e查看所有音效"); - helps.put("§b", null); - helps.put("/taboolib getvariable §8[§7-s|a§8] §8[§7键§8]", "§e查看变量"); - helps.put("/taboolib setvariable §8[§7-s|a§8] §8[§7键§8] §8[§7值§8]", "§e更改变量"); - helps.put("§c", null); - helps.put("/taboolib cycle list", "§e列出所有时间检查器"); - helps.put("/taboolib cycle info §8[§7名称§8]", "§e查询检查器信息"); - helps.put("/taboolib cycle reset §8[§7名称§8]", "§e初始化时间检查器"); - helps.put("/taboolib cycle update §8[§7名称§8]", "§e更新时间检查器"); - helps.put("§f", null); - helps.put("/taboolib shell load §8[§7名称§8]", "§e载入某个脚本"); - helps.put("/taboolib shell unload §8[§7名称§8]", "§e卸载某个脚本"); - helps.put("§g", null); - helps.put("/taboolib tagprefix §8[§7名称§8] §8[§7文本§8]", "§e设置玩家头顶前缀"); - helps.put("/taboolib tagsuffix §8[§7名称§8] §8[§7文本§8]", "§e设置玩家头顶后缀"); - helps.put("/taboolib tagdelete §8[§7名称§8]", "§e删除玩家称号数据"); - helps.put("§e", null); - helps.put("/taboolib importdata", "§4向数据库导入本地数据 §8(该操作将会清空数据库)"); - - if (sender instanceof ConsoleCommandSender || TabooLib.getVerint() < 10900) { - sender.sendMessage("§f"); - sender.sendMessage("§b§l----- §3§lTaooLib Commands §b§l-----"); - sender.sendMessage("§f"); - // 遍历命令 - for (Entry entry : helps.entrySet()) { - if (entry.getValue() == null) { - sender.sendMessage("§f"); - } else { - sender.sendMessage("§f " + entry.getKey() + " §6- " + entry.getValue()); - } - } - sender.sendMessage("§f"); - } - else if (sender instanceof Player) { - JSONFormatter json = new JSONFormatter(); - json.append("§f"); json.newLine(); - json.append("§b§l----- §3§lTaooLib Commands §b§l-----"); json.newLine(); - json.append("§f"); json.newLine(); - // 遍历命令 - for (Entry entry : helps.entrySet()) { - if (entry.getValue() == null) { - json.append("§f"); json.newLine(); - } else { - json.appendHoverClick("§f " + entry.getKey() + " §6- " + entry.getValue(), new ShowTextEvent("§f点击复制指令"), new SuggestCommandEvent(entry.getKey().split("§")[0])); json.newLine(); - } - } - json.append("§f"); - json.send((Player) sender); - } - } -} diff --git a/src/main/java/me/skymc/taboolib/commands/sub/ImportCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/ImportCommand.java index 5a97dda..c3516b7 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/ImportCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/ImportCommand.java @@ -1,7 +1,9 @@ package me.skymc.taboolib.commands.sub; import java.io.File; +import java.util.Objects; +import com.ilummc.tlib.resources.TLocale; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; @@ -18,28 +20,34 @@ public class ImportCommand extends SubCommand { super(sender, args); if (isPlayer()) { - MsgUtils.warn("改命令只能由控制台输入"); + TLocale.sendTo(sender, "COMMANDS.GLOBAL.ONLY-PLAYER"); + return; } - else if (Main.getStorageType() == StorageType.LOCAL) { - MsgUtils.warn("只有启用数据库储存时才能这么做"); + + if (Main.getStorageType() == StorageType.LOCAL) { + TLocale.Logger.warn("COMMANDS.GLOBAL.ONLY-STORAGE-SQL"); + return; } - else { - MsgUtils.send("正在清空数据库..."); - Main.getConnection().truncateTable(Main.getTablePrefix() + "_playerdata"); - - MsgUtils.send("开始导入玩家数据..."); - int size = Main.getPlayerDataFolder().listFiles().length; - int loop = 1; - - for (File file : Main.getPlayerDataFolder().listFiles()) { - FileConfiguration conf = YamlConfiguration.loadConfiguration(file); - Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", file.getName().replace(".yml", ""), ConfigUtils.encodeYAML(conf)); - - MsgUtils.send("导入玩家: &f" + file.getName().replace(".yml", "") + " &7进度: &f" + loop + "/" + size); - loop++; - } - MsgUtils.send("导入完成!"); + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.CLEARING"); + Main.getConnection().truncateTable(Main.getTablePrefix() + "_playerdata"); + + if (!Main.getPlayerDataFolder().exists()) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.EMPTYDATA"); + return; } + + int size = Objects.requireNonNull(Main.getPlayerDataFolder().listFiles()).length; + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.IMPORTING-START", String.valueOf(size)); + + int loop = 1; + for (File file : Objects.requireNonNull(Main.getPlayerDataFolder().listFiles())) { + Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", file.getName().replace(".yml", ""), ConfigUtils.encodeYAML(YamlConfiguration.loadConfiguration(file))); + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.IMPORTING-PROGRESS", file.getName().replace(".yml", ""), String.valueOf(loop), String.valueOf(size)); + loop++; + } + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.SUCCESS"); } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/InfoCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/InfoCommand.java index 01c13ac..2a26603 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/InfoCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/InfoCommand.java @@ -1,51 +1,30 @@ package me.skymc.taboolib.commands.sub; +import com.ilummc.tlib.resources.TLocale; +import me.skymc.taboolib.commands.SubCommand; +import me.skymc.taboolib.inventory.ItemUtils; +import me.skymc.taboolib.itemnbtapi.NBTItem; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import me.skymc.taboolib.commands.SubCommand; -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.itemnbtapi.NBTItem; -import me.skymc.taboolib.jsonformatter.JSONFormatter; -import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent; -import me.skymc.taboolib.jsonformatter.hover.ShowItemEvent; -import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent; -import me.skymc.taboolib.message.MsgUtils; - public class InfoCommand extends SubCommand { - @SuppressWarnings("deprecation") - public InfoCommand(CommandSender sender, String[] args) { - super(sender, args); - - if (isPlayer()) { - Player player = (Player) sender; - if (player.getItemInHand().getType().equals(Material.AIR)) { - MsgUtils.send(player, "&7请手持正确物品"); - } - else { - sender.sendMessage("§f"); - sender.sendMessage("§b§l----- §3§lItemStack Info §b§l-----"); - sender.sendMessage("§f"); - - JSONFormatter json = new JSONFormatter(); - json.append("§7 - 物品材质: §f"); json.appendHoverClick("§f" + player.getItemInHand().getType().name(), new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(player.getItemInHand().getType().name())); - json.newLine(); - json.append("§7 - 物品名称: §f"); json.appendHoverClick("§f" + ItemUtils.getCustomName(player.getItemInHand()), new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(ItemUtils.getCustomName(player.getItemInHand()).replace("§", "&"))); - json.newLine(); - json.append("§7 - 物品序号: §f" + player.getItemInHand().getTypeId() + ":" + player.getItemInHand().getDurability()); - json.newLine(); - json.append("§7 - 物品展示: §f"); json.appendHover(ItemUtils.getCustomName(player.getItemInHand()), new ShowItemEvent(player.getItemInHand())); - json.send(player); - - NBTItem nbt = new NBTItem(((Player) sender).getItemInHand()); - sender.sendMessage("§7 - 物品 NBT: §f"); - sender.sendMessage("§f"); - sender.sendMessage(nbt.toString()); - - sender.sendMessage("§f"); - } - } - } + @SuppressWarnings("deprecation") + public InfoCommand(CommandSender sender, String[] args) { + super(sender, args); + if (isPlayer()) { + Player player = (Player) sender; + if (player.getItemInHand().getType().equals(Material.AIR)) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.INFO.INVALID-ITEM"); + } else { + NBTItem nbt = new NBTItem(player.getItemInHand()); + TLocale.sendTo(sender, "COMAMNDS.TABOOLIB.INFO.ITEM-INFO", + player.getItemInHand().getType().name(), + ItemUtils.getCustomName(player.getItemInHand()), + player.getItemInHand().getTypeId() + ":" + player.getItemInHand().getDurability(), + nbt.toString()); + } + } + } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/ItemCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/ItemCommand.java index 38dc3fc..9e64fac 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/ItemCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/ItemCommand.java @@ -1,77 +1,64 @@ package me.skymc.taboolib.commands.sub; -import java.util.HashMap; - +import com.ilummc.tlib.resources.TLocale; +import me.skymc.taboolib.commands.SubCommand; +import me.skymc.taboolib.inventory.ItemUtils; +import me.skymc.taboolib.message.MsgUtils; +import me.skymc.taboolib.other.NumberUtils; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import me.skymc.taboolib.commands.SubCommand; -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.message.MsgUtils; -import me.skymc.taboolib.other.NumberUtils; +import java.util.HashMap; public class ItemCommand extends SubCommand { - - /** - * /TabooLib item 物品 玩家 数量 - * - * @param sender - * @param args - */ - public ItemCommand(CommandSender sender, String[] args) { - super(sender, args); - - if (args.length < 2) { - MsgUtils.send(sender, "请输入正确的物品名称"); - setReturn(false); - } - else { - if (ItemUtils.getCacheItem(args[1]) == null) { - MsgUtils.send(sender, "物品 &f" + args[1] + "&7 不存在"); - setReturn(false); - return; - } - - Player player; - Integer amount = 1; - ItemStack item = ItemUtils.getCacheItem(args[1]).clone(); - - if (args.length > 2) { - player = Bukkit.getPlayerExact(args[2]); - if (player == null) { - MsgUtils.send(sender, "玩家 &f" + args[2] + "&7 不在线"); - setReturn(false); - return; - } - } - else if (sender instanceof Player) { - player = (Player) sender; - } - else { - MsgUtils.send(sender, "后台不允许这么做"); - setReturn(false); - return; - } - - if (args.length > 3) { - amount = NumberUtils.getInteger(args[3]); - if (amount < 1) { - MsgUtils.send(sender, "数量必须大于0"); - setReturn(false); - return; - } - } - item.setAmount(amount); - - HashMap map = player.getInventory().addItem(item); - if (map.size() > 0) { - player.getWorld().dropItem(player.getLocation(), item); - } - - MsgUtils.send(sender, "物品已发送至玩家 &f" + player.getName() + " &7的背包中"); - setReturn(true); - } - } + + public ItemCommand(CommandSender sender, String[] args) { + super(sender, args); + + if (args.length < 2) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-NAME"); + return; + } + + if (ItemUtils.getCacheItem(args[1]) == null) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-ITEM", args[1]); + return; + } + + Player player; + Integer amount = 1; + ItemStack item = ItemUtils.getCacheItem(args[1]).clone(); + + if (args.length > 2) { + player = Bukkit.getPlayerExact(args[2]); + if (player == null) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-PLAYER", args[2]); + return; + } + } else if (sender instanceof Player) { + player = (Player) sender; + } else { + TLocale.sendTo(sender, "COMMANDS.GLOBAL.ONLY-PLAYER"); + return; + } + + if (args.length > 3) { + amount = NumberUtils.getInteger(args[3]); + if (amount < 1) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-NUMBER"); + return; + } + } + item.setAmount(amount); + + HashMap map = player.getInventory().addItem(item); + if (map.size() > 0) { + player.getWorld().dropItem(player.getLocation(), item); + } + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.SUCCESS", player.getName()); + setReturn(true); + } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/PotionCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/PotionCommand.java index f08f012..8a9c70c 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/PotionCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/PotionCommand.java @@ -1,6 +1,8 @@ package me.skymc.taboolib.commands.sub; +import com.ilummc.tlib.resources.TLocale; import org.bukkit.command.CommandSender; +import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffectType; @@ -9,29 +11,22 @@ import me.skymc.taboolib.jsonformatter.JSONFormatter; import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent; import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent; +import java.util.Arrays; + public class PotionCommand extends SubCommand { @SuppressWarnings("deprecation") public PotionCommand(CommandSender sender, String[] args) { super(sender, args); - - sender.sendMessage("§f"); - sender.sendMessage("§b§l----- §3§lPotionEffect Types §b§l-----"); - sender.sendMessage("§f"); - - for (PotionEffectType type : PotionEffectType.values()) { - if (type != null) { - if (isPlayer()) { - JSONFormatter json = new JSONFormatter(); - json.append(" §7- §f" + type.getId() + ". " + type.getName()); - json.appendHoverClick(" §8(点击复制)", new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(type.getName())); - json.send((Player) sender); - } - else { - sender.sendMessage(" §7- §f" + type.getId() + ". " + type.getName() + ""); - } - } - } - sender.sendMessage("§f"); + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.POTIONS.HEAD"); + + for (PotionEffectType potionEffectType : PotionEffectType.values()) { + if (potionEffectType != null) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.POTIONS.BODY", String.valueOf(potionEffectType.getId()), potionEffectType.getName()); + } + } + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.POTIONS.FOOT"); } } 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 ef62f08..d8914af 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/SaveCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/SaveCommand.java @@ -1,11 +1,6 @@ package me.skymc.taboolib.commands.sub; -import org.bukkit.Material; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - +import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.Main; import me.skymc.taboolib.commands.SubCommand; import me.skymc.taboolib.fileutils.ConfigUtils; @@ -14,76 +9,78 @@ import me.skymc.taboolib.message.ChatCatcher; import me.skymc.taboolib.message.ChatCatcher.Catcher; import me.skymc.taboolib.message.MsgUtils; import me.skymc.taboolib.playerdata.DataUtils; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; public class SaveCommand extends SubCommand { - public SaveCommand(CommandSender sender, String[] args) { - super(sender, args); - if (!(sender instanceof Player)) { - MsgUtils.send(sender, "&4后台无法这么做"); - return; - } - - if (args.length < 2) { - MsgUtils.send(sender, "&4请输入正确的名称"); - return; - } - - if (((Player) sender).getItemInHand().getType().equals(Material.AIR)) { - MsgUtils.send(sender, "&4你不能保存空气"); - return; - } - - if (ItemUtils.getItemCachesFinal().containsKey(args[1])) { - MsgUtils.send(sender, "&4该名称所对应的物品保存于固定物品库中, 无法覆盖"); - return; - } - - if (ItemUtils.getItemCaches().containsKey(args[1])) { - // 检查聊天引导 - if (ChatCatcher.contains((Player) sender)) { - MsgUtils.send(sender, "&4你有一个正在进行的聊天引导, 请完成后在这么做"); - return; - } - - ChatCatcher.call((Player) sender, new ChatCatcher.Catcher() { - - @Override - public void cancel() { - MsgUtils.send(sender, "&7退出引导"); - } - - @Override - public Catcher before() { - MsgUtils.send(sender, "物品 &f" + args[1] + "&7 已存在, 如果你想要覆盖它, 请在聊天框中输入 \"&f是&7\""); - return this; - } - - @SuppressWarnings("deprecation") - @Override - public boolean after(String message) { - if (message.equals("是")) { - saveItem(args[1], ((Player) sender).getItemInHand()); - MsgUtils.send(sender, "物品 &f" + args[1] + " &7已替换"); - } - else { - MsgUtils.send(sender, "&7退出引导"); - } - return false; - } - }); - } - else { - saveItem(args[1], ((Player) sender).getItemInHand()); - MsgUtils.send(sender, "物品 &f" + args[1] + " &7已保存"); - } - } + public SaveCommand(CommandSender sender, String[] args) { + super(sender, args); + if (!(sender instanceof Player)) { + TLocale.sendTo(sender, "COMMANDS.GLOBAL.ONLY-PLAYER"); + return; + } - - private void saveItem(String name, ItemStack item) { - FileConfiguration conf = ConfigUtils.load(Main.getInst(), ItemUtils.getItemCacheFile()); - conf.set(name + ".bukkit", item); - DataUtils.saveConfiguration(conf, ItemUtils.getItemCacheFile()); - ItemUtils.reloadItemCache(); - } + if (args.length < 2) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.INVALID-NAME"); + return; + } + + if (((Player) sender).getItemInHand().getType().equals(Material.AIR)) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.INVALID-ITEM"); + return; + } + + if (ItemUtils.getItemCachesFinal().containsKey(args[1])) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.INVALID-ITEM-FINAL-EXISTS"); + return; + } + + if (ItemUtils.getItemCaches().containsKey(args[1])) { + // 检查聊天引导 + if (ChatCatcher.contains((Player) sender)) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.GUIDE-EXISTS"); + return; + } + + ChatCatcher.call((Player) sender, new ChatCatcher.Catcher() { + + @Override + public void cancel() { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.GUIDE-QUIT"); + } + + @Override + public Catcher before() { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.GUIDE-BEFORE", args[1]); + return this; + } + + @SuppressWarnings("deprecation") + @Override + public boolean after(String message) { + if (message.equalsIgnoreCase("yes")) { + saveItem(args[1], ((Player) sender).getItemInHand()); + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.SUCCESS", args[1]); + } else { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.GUIDE-QUIT"); + } + return false; + } + }); + } else { + saveItem(args[1], ((Player) sender).getItemInHand()); + MsgUtils.send(sender, "物品 &f" + args[1] + " &7已保存"); + } + } + + private void saveItem(String name, ItemStack item) { + FileConfiguration conf = ConfigUtils.load(Main.getInst(), ItemUtils.getItemCacheFile()); + conf.set(name + ".bukkit", item); + DataUtils.saveConfiguration(conf, ItemUtils.getItemCacheFile()); + ItemUtils.reloadItemCache(); + } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/SlotCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/SlotCommand.java index 57d8627..0dfa1e5 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/SlotCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/SlotCommand.java @@ -1,5 +1,6 @@ package me.skymc.taboolib.commands.sub; +import com.ilummc.tlib.resources.TLocale; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -8,28 +9,17 @@ import me.skymc.taboolib.jsonformatter.JSONFormatter; import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent; import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent; +import java.util.Arrays; + public class SlotCommand extends SubCommand { public SlotCommand(CommandSender sender, String[] args) { super(sender, args); - - sender.sendMessage("§f"); - sender.sendMessage("§b§l----- §3§lAttribute Slots §b§l-----"); - sender.sendMessage("§f"); - - String[] attributes = new String[] { "mainhand", "offhand", "feet", "legs", "chest", "head", "all" }; - - for (String name : attributes) { - if (isPlayer()) { - JSONFormatter json = new JSONFormatter(); - json.append(" §7- §f" + name); - json.appendHoverClick(" §8(点击复制)", new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(name)); - json.send((Player) sender); - } - else { - sender.sendMessage(" §7- §f" + name); - } - } - sender.sendMessage("§f"); + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SLOTS.HEAD"); + + Arrays.stream(new String[] { "mainhand", "offhand", "feet", "legs", "chest", "head", "all" }).forEach(slots -> TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SLOTS.BODY", slots)); + + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SLOTS.FOOT"); } } 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 6976e50..30da0a5 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/VariableGetCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/VariableGetCommand.java @@ -1,5 +1,6 @@ package me.skymc.taboolib.commands.sub; +import com.ilummc.tlib.resources.TLocale; import org.bukkit.command.CommandSender; import me.skymc.taboolib.commands.SubCommand; @@ -12,10 +13,13 @@ public class VariableGetCommand extends SubCommand { super(sender, args); if (args.length < 3) { - MsgUtils.send(sender, "&4请输入正确的指令 "); + TLocale.sendTo(sender, "COAMMNDS.PARAMETER.INSUFFICIENT"); + return; } - else if (!(args[1].equals("-a") || args[1].equals("-s"))) { - MsgUtils.send(sender, "&4请输入正确的读取方式"); + + if (!(args[1].equals("-a") || args[1].equals("-s"))) { + TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-ERROR-TYPE"); + return; } Long time = System.currentTimeMillis(); @@ -27,14 +31,8 @@ public class VariableGetCommand extends SubCommand { else if (args[1].equals("-a")) { value = GlobalDataManager.getVariableAsynchronous(args[2], null); } - - if (value == null) { - MsgUtils.send(sender, "读取完成, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)"); - MsgUtils.send(sender, "变量 &f" + args[2] + " &7不存在"); - } - else { - MsgUtils.send(sender, "读取完成, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)"); - MsgUtils.send(sender, "变量 &f" + args[2] + " &7的值为 &f" + value); - } + + 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 28bcdf4..202e7e0 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/VariableSetCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/VariableSetCommand.java @@ -1,5 +1,6 @@ package me.skymc.taboolib.commands.sub; +import com.ilummc.tlib.resources.TLocale; import org.bukkit.command.CommandSender; import me.skymc.taboolib.commands.SubCommand; @@ -12,10 +13,13 @@ public class VariableSetCommand extends SubCommand { super(sender, args); if (args.length < 4) { - MsgUtils.send(sender, "&4请输入正确的指令 "); + TLocale.sendTo(sender, "COAMMNDS.PARAMETER.INSUFFICIENT"); + return; } - else if (!(args[1].equals("-a") || args[1].equals("-s"))) { - MsgUtils.send(sender, "&4请输入正确的写入方式"); + + if (!(args[1].equals("-a") || args[1].equals("-s"))) { + TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.WRITE-ERROR-TYPE"); + return; } Long time = System.currentTimeMillis(); @@ -27,8 +31,8 @@ public class VariableSetCommand extends SubCommand { else if (args[1].equals("-a")) { GlobalDataManager.setVariableAsynchronous(args[2], value); } - - MsgUtils.send(sender, "写入完成, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)"); + + TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.WRITE-SUCCESS", String.valueOf(System.currentTimeMillis() - time)); 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 7427bf9..2c06f76 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 @@ -1,36 +1,31 @@ package me.skymc.taboolib.commands.sub.cycle; -import org.bukkit.command.CommandSender; - +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 CycleCommand extends SubCommand { - public CycleCommand(CommandSender sender, String[] args) { - super(sender, args); - if (args.length > 1) { - if (args[1].equalsIgnoreCase("list")) { - new CycleListCommand(sender, args); - } - else if (args[1].equalsIgnoreCase("info")) { - new CycleInfoCommand(sender, args); - } - else if (args[1].equalsIgnoreCase("reset")) { - new CycleResetCommand(sender, args); - } - else if (args[1].equalsIgnoreCase("update")) { - new CycleUpdateCommand(sender, args); - } - } - else { - MsgUtils.send(sender, "&4指令错误"); - } - } + public CycleCommand(CommandSender sender, String[] args) { + super(sender, args); + if (args.length > 1) { + if (args[1].equalsIgnoreCase("list")) { + new CycleListCommand(sender, args); + } else if (args[1].equalsIgnoreCase("info")) { + new CycleInfoCommand(sender, args); + } else if (args[1].equalsIgnoreCase("reset")) { + new CycleResetCommand(sender, args); + } else if (args[1].equalsIgnoreCase("update")) { + new CycleUpdateCommand(sender, args); + } + } else { + TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); + } + } - @Override - public boolean command() { - return true; - } + @Override + public boolean command() { + return true; + } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/itemlist/ItemListCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/itemlist/ItemListCommand.java index a6bd160..3101bc3 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/itemlist/ItemListCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/itemlist/ItemListCommand.java @@ -1,11 +1,10 @@ package me.skymc.taboolib.commands.sub.itemlist; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import me.skymc.taboolib.commands.SubCommand; import me.skymc.taboolib.commands.sub.itemlist.listener.ItemLibraryPatch; import me.skymc.taboolib.other.NumberUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; /** * @author sky @@ -13,19 +12,14 @@ import me.skymc.taboolib.other.NumberUtils; */ public class ItemListCommand extends SubCommand { - /** - * @param sender - * @param args - */ - public ItemListCommand(CommandSender sender, String[] args) { - super(sender, args); - if (isPlayer()) { - if (args.length == 1) { - ItemLibraryPatch.openInventory((Player) sender, 1); - } - else { - ItemLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1])); - } - } - } + public ItemListCommand(CommandSender sender, String[] args) { + super(sender, args); + if (isPlayer()) { + if (args.length == 1) { + ItemLibraryPatch.openInventory((Player) sender, 1); + } else { + ItemLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1])); + } + } + } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/itemlist/listener/ItemLibraryPatch.java b/src/main/java/me/skymc/taboolib/commands/sub/itemlist/listener/ItemLibraryPatch.java index 6ba40ae..9663ac3 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/itemlist/listener/ItemLibraryPatch.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/itemlist/listener/ItemLibraryPatch.java @@ -1,10 +1,8 @@ package me.skymc.taboolib.commands.sub.itemlist.listener; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; - +import com.ilummc.tlib.resources.TLocale; +import me.skymc.taboolib.inventory.InventoryUtil; +import me.skymc.taboolib.inventory.ItemUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -16,97 +14,96 @@ import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import me.skymc.taboolib.inventory.InventoryUtil; -import me.skymc.taboolib.inventory.ItemUtils; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; /** * @author sky * @since 2018年2月4日 下午4:35:00 */ public class ItemLibraryPatch implements Listener { - - /** - * 打开物品库界面 - * - * @param player - * @param page - */ - public static void openInventory(Player player, int page) { - ItemLibraryHolder holder = new ItemLibraryHolder(page); - Inventory inventory = Bukkit.createInventory(holder, 54, "物品库"); - LinkedHashMap map = new LinkedHashMap<>(); - map.putAll(ItemUtils.getItemCachesFinal()); - map.putAll(ItemUtils.getItemCaches()); + /** + * 打开物品库界面 + * + * @param player + * @param page + */ + public static void openInventory(Player player, int page) { + ItemLibraryHolder holder = new ItemLibraryHolder(page); + Inventory inventory = Bukkit.createInventory(holder, 54, TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.MENU.TITLE", String.valueOf(page))); - int loop = 0; - for (String name : map.keySet()) { - if (loop >= (page - 1) * 28) { - if (loop < page * 28) { - int slot = InventoryUtil.SLOT_OF_CENTENTS.get(loop - ((page - 1) * 28)); - ItemStack item = map.get(name).clone(); - { - ItemMeta meta = item.getItemMeta(); - List lore = meta.hasLore() ? meta.getLore() : new ArrayList<>(); - lore.add("§f"); - lore.add("§f§m "); - lore.add("§f序列号: §8" + name); - meta.setLore(lore); - item.setItemMeta(meta); - inventory.setItem(slot, item); - } - holder.ITEMS_DATA.put(slot, name); - } else { - break; - } - } - loop++; - } + LinkedHashMap map = new LinkedHashMap<>(); + map.putAll(ItemUtils.getItemCachesFinal()); + map.putAll(ItemUtils.getItemCaches()); - if (page > 1) { - inventory.setItem(47, ItemUtils.setName(new ItemStack(Material.ARROW), "§f上一页")); - } - if (((int) Math.ceil(map.size() / 28D)) > page) { - inventory.setItem(51, ItemUtils.setName(new ItemStack(Material.ARROW), "§f下一页")); - } - player.openInventory(inventory); - } + int loop = 0; + for (String name : map.keySet()) { + if (loop >= (page - 1) * 28) { + if (loop < page * 28) { + int slot = InventoryUtil.SLOT_OF_CENTENTS.get(loop - ((page - 1) * 28)); + inventory.setItem(slot, getItem(map, name)); + holder.ITEMS_DATA.put(slot, name); + } else { + break; + } + } + loop++; + } - @EventHandler - public void inventoryClick(InventoryClickEvent e) { - if (e.getInventory().getHolder() instanceof ItemLibraryHolder) { - e.setCancelled(true); + if (page > 1) { + inventory.setItem(47, ItemUtils.setName(new ItemStack(Material.ARROW), TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.MENU.BACK"))); + } + if (((int) Math.ceil(map.size() / 28D)) > page) { + inventory.setItem(51, ItemUtils.setName(new ItemStack(Material.ARROW), TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.MENU.NEXT"))); + } + player.openInventory(inventory); + } - if (e.getCurrentItem() == null || e.getCurrentItem().getType().equals(Material.AIR) || e.getRawSlot() >= e.getInventory().getSize()) { - return; - } + @EventHandler + public void inventoryClick(InventoryClickEvent e) { + if (e.getInventory().getHolder() instanceof ItemLibraryHolder) { + e.setCancelled(true); - switch (e.getRawSlot()) { - case 47: - openInventory((Player) e.getWhoClicked(), ((ItemLibraryHolder) e.getInventory().getHolder()).PAGE - 1); - break; - case 51: - openInventory((Player) e.getWhoClicked(), ((ItemLibraryHolder) e.getInventory().getHolder()).PAGE + 1); - break; - default: - e.getWhoClicked().getInventory().addItem(ItemUtils.getCacheItem(((ItemLibraryHolder) e.getInventory().getHolder()).ITEMS_DATA.get(e.getRawSlot()))); - break; - } - } - } - - public static class ItemLibraryHolder implements InventoryHolder { + if (e.getCurrentItem() == null || e.getCurrentItem().getType().equals(Material.AIR) || e.getRawSlot() >= e.getInventory().getSize()) { + return; + } - public final int PAGE; - public final HashMap ITEMS_DATA = new HashMap<>(); - - public ItemLibraryHolder(int page) { - this.PAGE = page; - } - - @Override - public Inventory getInventory() { - return null; - } - } + int i = e.getRawSlot(); + if (i == 47) { + openInventory((Player) e.getWhoClicked(), ((ItemLibraryHolder) e.getInventory().getHolder()).PAGE - 1); + } else if (i == 51) { + openInventory((Player) e.getWhoClicked(), ((ItemLibraryHolder) e.getInventory().getHolder()).PAGE + 1); + } else { + e.getWhoClicked().getInventory().addItem(ItemUtils.getCacheItem(((ItemLibraryHolder) e.getInventory().getHolder()).ITEMS_DATA.get(e.getRawSlot()))); + } + } + } + + private static ItemStack getItem(HashMap map, String name) { + ItemStack item = map.get(name).clone(); + ItemMeta meta = item.getItemMeta(); + List lore = meta.hasLore() ? meta.getLore() : new ArrayList<>(); + lore.addAll(TLocale.asStringList("COMMANDS.TABOOLIB.ITEMLIST.MENU.LORE", name)); + meta.setLore(lore); + item.setItemMeta(meta); + return item; + } + + public static class ItemLibraryHolder implements InventoryHolder { + + public final int PAGE; + public final HashMap ITEMS_DATA = new HashMap<>(); + + public ItemLibraryHolder(int page) { + this.PAGE = page; + } + + @Override + public Inventory getInventory() { + return null; + } + } } 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 9150f31..3b6b3c1 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 @@ -1,30 +1,28 @@ package me.skymc.taboolib.commands.sub.shell; -import org.bukkit.command.CommandSender; - +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 { - public ShellCommand(CommandSender sender, String[] args) { - super(sender, args); - if (args.length > 1) { - if (args[1].equalsIgnoreCase("load")) { - new ShellLoadCommand(sender, args); - } - else if (args[1].equalsIgnoreCase("unload")) { - new ShellUnloadCommand(sender, args); - } - } - else { - MsgUtils.send(sender, "&4指令错误"); - } - } + public ShellCommand(CommandSender sender, String[] args) { + super(sender, args); + if (args.length > 1) { + if (args[1].equalsIgnoreCase("load")) { + new ShellLoadCommand(sender, args); + } else if (args[1].equalsIgnoreCase("unload")) { + new ShellUnloadCommand(sender, args); + } + } else { + TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); + } + } - @Override - public boolean command() { - return true; - } + @Override + public boolean command() { + return true; + } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellLoadCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellLoadCommand.java index c66668e..0df1d37 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellLoadCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellLoadCommand.java @@ -2,6 +2,7 @@ package me.skymc.taboolib.commands.sub.shell; import java.io.File; +import com.ilummc.tlib.resources.TLocale; import org.bukkit.command.CommandSender; import me.skymc.taboolib.commands.SubCommand; @@ -13,18 +14,18 @@ public class ShellLoadCommand extends SubCommand { public ShellLoadCommand(CommandSender sender, String[] args) { super(sender, args); if (args.length < 3) { - MsgUtils.send(sender, "&c请输入正确的脚本名称"); + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-NAME"); return; } File file = new File(JavaShell.getScriptFolder(), args[2].contains(".java") ? args[2] : args[2] + ".java"); if (!file.exists()) { - MsgUtils.send(sender, "&c脚本 &4" + args[2] + "&c 不存在"); + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-SHELL", args[2]); return; } if (JavaShell.reloadShell(args[2])) { - MsgUtils.send(sender, "脚本 " + args[2] + " 已载入"); + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.SUCCESS-LOAD", args[2]); } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellUnloadCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellUnloadCommand.java index 3ab5338..a893375 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellUnloadCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/shell/ShellUnloadCommand.java @@ -2,6 +2,7 @@ package me.skymc.taboolib.commands.sub.shell; import java.io.File; +import com.ilummc.tlib.resources.TLocale; import org.bukkit.command.CommandSender; import me.skymc.taboolib.commands.SubCommand; @@ -13,18 +14,18 @@ public class ShellUnloadCommand extends SubCommand { public ShellUnloadCommand(CommandSender sender, String[] args) { super(sender, args); if (args.length < 3) { - MsgUtils.send(sender, "&c请输入正确的脚本名称"); + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-NAME"); return; } File file = new File(JavaShell.getScriptFolder(), args[2].contains(".java") ? args[2] : args[2] + ".java"); if (!file.exists()) { - MsgUtils.send(sender, "&c脚本 &4" + args[2] + "&c 不存在"); + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-SHELL", args[2]); return; } JavaShell.unloadShell(args[2]); - MsgUtils.send(sender, "脚本 " + args[2] + " 已卸载"); + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.SUCCESS-UNLOAD", args[2]); } @Override diff --git a/src/main/java/me/skymc/taboolib/commands/sub/sounds/SoundsCommand.java b/src/main/java/me/skymc/taboolib/commands/sub/sounds/SoundsCommand.java index 4e2762e..9c2ea65 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/sounds/SoundsCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/sounds/SoundsCommand.java @@ -1,31 +1,27 @@ package me.skymc.taboolib.commands.sub.sounds; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import me.skymc.taboolib.commands.SubCommand; import me.skymc.taboolib.commands.sub.sounds.listener.SoundsLibraryPatch; import me.skymc.taboolib.other.NumberUtils; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; /** * @author sky * @since 2018-03-18 21:02:26 */ public class SoundsCommand extends SubCommand { - - /** - * @param sender - * @param args - */ - public SoundsCommand(CommandSender sender, String[] args) { - super(sender, args); - if (isPlayer()) { - if (args.length == 1) { - SoundsLibraryPatch.openInventory((Player) sender, 1); - } - else { - SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1])); - } - } - } + + public SoundsCommand(CommandSender sender, String[] args) { + super(sender, args); + if (isPlayer()) { + if (args.length == 1) { + SoundsLibraryPatch.openInventory((Player) sender, 1, null); + } else if (args.length == 2) { + SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1]), null); + } else { + SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1]), args[2]); + } + } + } } diff --git a/src/main/java/me/skymc/taboolib/commands/sub/sounds/listener/SoundsLibraryPatch.java b/src/main/java/me/skymc/taboolib/commands/sub/sounds/listener/SoundsLibraryPatch.java index e37ac1e..ec0cbe9 100644 --- a/src/main/java/me/skymc/taboolib/commands/sub/sounds/listener/SoundsLibraryPatch.java +++ b/src/main/java/me/skymc/taboolib/commands/sub/sounds/listener/SoundsLibraryPatch.java @@ -1,8 +1,11 @@ package me.skymc.taboolib.commands.sub.sounds.listener; -import java.util.Arrays; -import java.util.HashMap; - +import com.ilummc.tlib.resources.TLocale; +import com.ilummc.tlib.resources.type.TLocaleJson; +import me.skymc.taboolib.inventory.InventoryUtil; +import me.skymc.taboolib.inventory.ItemUtils; +import me.skymc.taboolib.jsonformatter.JSONFormatter; +import me.skymc.taboolib.message.MsgUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; @@ -15,95 +18,105 @@ import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import me.skymc.taboolib.inventory.InventoryUtil; -import me.skymc.taboolib.inventory.ItemUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; /** * @author sky * @since 2018年2月4日 下午4:35:00 */ public class SoundsLibraryPatch implements Listener { - - /** - * 打开物品库界面 - * - * @param player - * @param page - */ - public static void openInventory(Player player, int page) { - SoundLibraryHolder holder = new SoundLibraryHolder(page); - Inventory inventory = Bukkit.createInventory(holder, 54, "音效库 " + page); - int loop = 0; - for (Sound sound : Arrays.asList(Sound.values())) { - if (loop >= (page - 1) * 28) { - if (loop < page * 28) { - int slot = InventoryUtil.SLOT_OF_CENTENTS.get(loop - ((page - 1) * 28)); - ItemStack item = new ItemStack(Material.MAP); - { - ItemMeta meta = item.getItemMeta(); - meta.setDisplayName("§f" + sound.name()); - meta.setLore(Arrays.asList("", "§f左键: §71 音调", "§f左键: §72 音调")); - item.setItemMeta(meta); - inventory.setItem(slot, item); - } - holder.SOUNDS_DATA.put(slot, sound); - } else { - break; - } - } - loop++; - } + public static void openInventory(Player player, int page, String search) { + if (page < 1) { + page = 1; + } - if (page > 1) { - inventory.setItem(47, ItemUtils.setName(new ItemStack(Material.ARROW), "§f上一页")); - } - if (((int) Math.ceil(Sound.values().length / 28D)) > page) { - inventory.setItem(51, ItemUtils.setName(new ItemStack(Material.ARROW), "§f下一页")); - } - player.openInventory(inventory); - } + SoundLibraryHolder holder = new SoundLibraryHolder(page, search); + Inventory inventory = Bukkit.createInventory(holder, 54, TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.MENU.TITLE", String.valueOf(page))); + List soundFilter = Arrays.stream(Sound.values()).filter(sound -> search == null || sound.name().contains(search.toUpperCase())).collect(Collectors.toList()); - @EventHandler - public void inventoryClick(InventoryClickEvent e) { - if (e.getInventory().getHolder() instanceof SoundLibraryHolder) { - e.setCancelled(true); + int loop = 0; + for (Sound sound : soundFilter) { + if (loop >= (page - 1) * 28) { + if (loop < page * 28) { + int slot = InventoryUtil.SLOT_OF_CENTENTS.get(loop - ((page - 1) * 28)); + inventory.setItem(slot, getSoundItem(sound.name())); + holder.SOUNDS_DATA.put(slot, sound); + } else { + break; + } + } + loop++; + } - if (e.getCurrentItem() == null || e.getCurrentItem().getType().equals(Material.AIR) || e.getRawSlot() >= e.getInventory().getSize()) { - return; - } + if (page > 1) { + inventory.setItem(47, ItemUtils.setName(new ItemStack(Material.ARROW), TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.MENU.BACK"))); + } + if (((int) Math.ceil(Sound.values().length / 28D)) > page) { + inventory.setItem(51, ItemUtils.setName(new ItemStack(Material.ARROW), TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.MENU.NEXT"))); + } - switch (e.getRawSlot()) { - case 47: - openInventory((Player) e.getWhoClicked(), ((SoundLibraryHolder) e.getInventory().getHolder()).PAGE - 1); - break; - case 51: - openInventory((Player) e.getWhoClicked(), ((SoundLibraryHolder) e.getInventory().getHolder()).PAGE + 1); - break; - default: - Sound sound = ((SoundLibraryHolder) e.getInventory().getHolder()).SOUNDS_DATA.get(e.getRawSlot()); - if (e.getClick().isLeftClick()) { - ((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 1f); - } else { - ((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 2f); - } - break; - } - } - } - - public static class SoundLibraryHolder implements InventoryHolder { + if (!(player.getOpenInventory().getTopInventory().getHolder() instanceof SoundLibraryHolder)) { + TLocale.sendTo(player, "COMMANDS.TABOOLIB.SOUNDS.RESULT.SEARCH", (search == null ? "*" : search), String.valueOf(soundFilter.size())); + } + player.openInventory(inventory); + } - public final int PAGE; - public final HashMap SOUNDS_DATA = new HashMap<>(); - - public SoundLibraryHolder(int page) { - this.PAGE = page; - } - - @Override - public Inventory getInventory() { - return null; - } - } + @EventHandler + public void inventoryClick(InventoryClickEvent e) { + if (e.getInventory().getHolder() instanceof SoundLibraryHolder) { + e.setCancelled(true); + + if (e.getCurrentItem() == null || e.getCurrentItem().getType().equals(Material.AIR) || e.getRawSlot() >= e.getInventory().getSize()) { + return; + } + + SoundLibraryHolder soundLibraryHolder = ((SoundLibraryHolder) e.getInventory().getHolder()); + int i = e.getRawSlot(); + if (i == 47) { + openInventory((Player) e.getWhoClicked(), soundLibraryHolder.PAGE - 1, soundLibraryHolder.SEARCH); + } else if (i == 51) { + openInventory((Player) e.getWhoClicked(), soundLibraryHolder.PAGE + 1, soundLibraryHolder.SEARCH); + } else { + Sound sound = soundLibraryHolder.SOUNDS_DATA.get(e.getRawSlot()); + if (e.getClick().isLeftClick()) { + ((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 1f); + } else if (e.getClick().isRightClick()) { + ((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 2f); + } else if (e.getClick().isCreativeAction()) { + TLocale.sendTo(e.getWhoClicked(), "COMMANDS.TABOOLIB.SOUNDS.RESULT.COPY", sound.name()); + } + } + } + } + + private static ItemStack getSoundItem(String sound) { + ItemStack item = new ItemStack(Material.MAP); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName("§f§n" + sound); + meta.setLore(TLocale.asStringList("COMMANDS.TABOOLIB.SOUNDS.MENU.LORE")); + item.setItemMeta(meta); + return item; + } + + public static class SoundLibraryHolder implements InventoryHolder { + + public final int PAGE; + public final String SEARCH; + public final HashMap SOUNDS_DATA = new HashMap<>(); + + public SoundLibraryHolder(int page, String search) { + this.PAGE = page; + this.SEARCH = search; + } + + @Override + public Inventory getInventory() { + return null; + } + } } diff --git a/src/main/java/me/skymc/taboolib/csvutils/CsvReader.java b/src/main/java/me/skymc/taboolib/csvutils/CsvReader.java index 6d24bc7..594a856 100644 --- a/src/main/java/me/skymc/taboolib/csvutils/CsvReader.java +++ b/src/main/java/me/skymc/taboolib/csvutils/CsvReader.java @@ -1,20 +1,12 @@ package me.skymc.taboolib.csvutils; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; +import java.io.*; import java.nio.charset.Charset; import java.text.NumberFormat; import java.util.HashMap; -public class CsvReader -{ +public class CsvReader { + private Reader inputStream; private String fileName; private UserSettings userSettings; @@ -38,7 +30,7 @@ public class CsvReader private boolean closed; public static final int ESCAPE_MODE_DOUBLED = 1; public static final int ESCAPE_MODE_BACKSLASH = 2; - + public CsvReader(final String fileName, final char delimiter, final Charset charset) throws FileNotFoundException { this.inputStream = null; this.fileName = null; @@ -75,15 +67,15 @@ public class CsvReader this.charset = charset; this.isQualified = new boolean[this.values.length]; } - + public CsvReader(final String s, final char c) throws FileNotFoundException { this(s, c, Charset.forName("ISO-8859-1")); } - + public CsvReader(final String s) throws FileNotFoundException { this(s, ','); } - + public CsvReader(final Reader inputStream, final char delimiter) { this.inputStream = null; this.fileName = null; @@ -114,132 +106,132 @@ public class CsvReader this.initialized = true; this.isQualified = new boolean[this.values.length]; } - + public CsvReader(final Reader reader) { this(reader, ','); } - + public CsvReader(final InputStream inputStream, final char c, final Charset charset) { this(new InputStreamReader(inputStream, charset), c); } - + public CsvReader(final InputStream inputStream, final Charset charset) { this(new InputStreamReader(inputStream, charset)); } - + public boolean getCaptureRawRecord() { return this.userSettings.CaptureRawRecord; } - + public void setCaptureRawRecord(final boolean captureRawRecord) { this.userSettings.CaptureRawRecord = captureRawRecord; } - + public String getRawRecord() { return this.rawRecord; } - + public boolean getTrimWhitespace() { return this.userSettings.TrimWhitespace; } - + public void setTrimWhitespace(final boolean trimWhitespace) { this.userSettings.TrimWhitespace = trimWhitespace; } - + public char getDelimiter() { return this.userSettings.Delimiter; } - + public void setDelimiter(final char delimiter) { this.userSettings.Delimiter = delimiter; } - + public char getRecordDelimiter() { return this.userSettings.RecordDelimiter; } - + public void setRecordDelimiter(final char recordDelimiter) { this.useCustomRecordDelimiter = true; this.userSettings.RecordDelimiter = recordDelimiter; } - + public char getTextQualifier() { return this.userSettings.TextQualifier; } - + public void setTextQualifier(final char textQualifier) { this.userSettings.TextQualifier = textQualifier; } - + public boolean getUseTextQualifier() { return this.userSettings.UseTextQualifier; } - + public void setUseTextQualifier(final boolean useTextQualifier) { this.userSettings.UseTextQualifier = useTextQualifier; } - + public char getComment() { return this.userSettings.Comment; } - + public void setComment(final char comment) { this.userSettings.Comment = comment; } - + public boolean getUseComments() { return this.userSettings.UseComments; } - + public void setUseComments(final boolean useComments) { this.userSettings.UseComments = useComments; } - + public int getEscapeMode() { return this.userSettings.EscapeMode; } - + public void setEscapeMode(final int escapeMode) throws IllegalArgumentException { if (escapeMode != 1 && escapeMode != 2) { throw new IllegalArgumentException("Parameter escapeMode must be a valid value."); } this.userSettings.EscapeMode = escapeMode; } - + public boolean getSkipEmptyRecords() { return this.userSettings.SkipEmptyRecords; } - + public void setSkipEmptyRecords(final boolean skipEmptyRecords) { this.userSettings.SkipEmptyRecords = skipEmptyRecords; } - + public boolean getSafetySwitch() { return this.userSettings.SafetySwitch; } - + public void setSafetySwitch(final boolean safetySwitch) { this.userSettings.SafetySwitch = safetySwitch; } - + public int getColumnCount() { return this.columnsCount; } - + public long getCurrentRecord() { return this.currentRecord - 1L; } - + // TODO 2017-11-29 18:38:13 UPDATED public long setCurrentRecord(long currentRecord) { return this.currentRecord = currentRecord; } - + public int getHeaderCount() { return this.headersHolder.Length; } - + public String[] getHeaders() throws IOException { this.checkClosed(); if (this.headersHolder.Headers == null) { @@ -249,28 +241,27 @@ public class CsvReader System.arraycopy(this.headersHolder.Headers, 0, array, 0, this.headersHolder.Length); return array; } - + public void setHeaders(final String[] headers) { this.headersHolder.Headers = headers; this.headersHolder.IndexByName.clear(); if (headers != null) { this.headersHolder.Length = headers.length; - } - else { + } else { this.headersHolder.Length = 0; } for (int i = 0; i < this.headersHolder.Length; ++i) { this.headersHolder.IndexByName.put(headers[i], i); } } - + public String[] getValues() throws IOException { this.checkClosed(); final String[] array = new String[this.columnsCount]; System.arraycopy(this.values, 0, array, 0, this.columnsCount); return array; } - + public String get(final int n) throws IOException { this.checkClosed(); if (n > -1 && n < this.columnsCount) { @@ -278,19 +269,19 @@ public class CsvReader } return ""; } - + public String get(final String s) throws IOException { this.checkClosed(); return this.get(this.getIndex(s)); } - + public static CsvReader parse(final String s) { if (s == null) { throw new IllegalArgumentException("Parameter data can not be null."); } return new CsvReader(new StringReader(s)); } - + public boolean readRecord() throws IOException { this.checkClosed(); this.columnsCount = 0; @@ -301,8 +292,7 @@ public class CsvReader do { if (this.dataBuffer.Position == this.dataBuffer.Count) { this.checkDataLength(); - } - else { + } else { this.startedWithQualifier = false; char c = this.dataBuffer.Buffer[this.dataBuffer.Position]; if (this.userSettings.UseTextQualifier && c == this.userSettings.TextQualifier) { @@ -326,24 +316,21 @@ public class CsvReader do { if (this.dataBuffer.Position == this.dataBuffer.Count) { this.checkDataLength(); - } - else { + } else { final char lastLetter = this.dataBuffer.Buffer[this.dataBuffer.Position]; if (n2 != 0) { this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; if (lastLetter == this.userSettings.Delimiter) { this.endColumn(); - } - else if ((!this.useCustomRecordDelimiter && (lastLetter == '\r' || lastLetter == '\n')) || (this.useCustomRecordDelimiter && lastLetter == this.userSettings.RecordDelimiter)) { + } else if ((!this.useCustomRecordDelimiter && (lastLetter == '\r' || lastLetter == '\n')) || (this.useCustomRecordDelimiter && lastLetter == this.userSettings.RecordDelimiter)) { this.endColumn(); this.endRecord(); } - } - else if (n4 != 0) { + } else if (n4 != 0) { ++n6; switch (n5) { case 1: { - c2 = (char)((char)(c2 * '\u0010') + hexToDec(lastLetter)); + c2 = (char) ((char) (c2 * '\u0010') + hexToDec(lastLetter)); if (n6 == 4) { n4 = 0; break; @@ -351,7 +338,7 @@ public class CsvReader break; } case 2: { - c2 = (char)((char)(c2 * '\b') + (char)(lastLetter - '0')); + c2 = (char) ((char) (c2 * '\b') + (char) (lastLetter - '0')); if (n6 == 3) { n4 = 0; break; @@ -359,7 +346,7 @@ public class CsvReader break; } case 3: { - c2 = (char)((char)(c2 * '\n') + (char)(lastLetter - '0')); + c2 = (char) ((char) (c2 * '\n') + (char) (lastLetter - '0')); if (n6 == 3) { n4 = 0; break; @@ -367,7 +354,7 @@ public class CsvReader break; } case 4: { - c2 = (char)((char)(c2 * '\u0010') + hexToDec(lastLetter)); + c2 = (char) ((char) (c2 * '\u0010') + hexToDec(lastLetter)); if (n6 == 2) { n4 = 0; break; @@ -377,25 +364,21 @@ public class CsvReader } if (n4 == 0) { this.appendLetter(c2); - } - else { + } else { this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; } - } - else if (lastLetter == this.userSettings.TextQualifier) { + } else if (lastLetter == this.userSettings.TextQualifier) { if (n3 != 0) { n3 = 0; n = 0; - } - else { + } else { this.updateCurrentValue(); if (this.userSettings.EscapeMode == 1) { n3 = 1; } n = 1; } - } - else if (this.userSettings.EscapeMode == 2 && n3 != 0) { + } else if (this.userSettings.EscapeMode == 2 && n3 != 0) { switch (lastLetter) { case 'n': { this.appendLetter('\n'); @@ -440,7 +423,7 @@ public class CsvReader n5 = 2; n4 = 1; n6 = 1; - c2 = (char)(lastLetter - '0'); + c2 = (char) (lastLetter - '0'); this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; break; } @@ -482,20 +465,16 @@ public class CsvReader } } n3 = 0; - } - else if (lastLetter == textQualifier) { + } else if (lastLetter == textQualifier) { this.updateCurrentValue(); n3 = 1; - } - else if (n != 0) { + } else if (n != 0) { if (lastLetter == this.userSettings.Delimiter) { this.endColumn(); - } - else if ((!this.useCustomRecordDelimiter && (lastLetter == '\r' || lastLetter == '\n')) || (this.useCustomRecordDelimiter && lastLetter == this.userSettings.RecordDelimiter)) { + } else if ((!this.useCustomRecordDelimiter && (lastLetter == '\r' || lastLetter == '\n')) || (this.useCustomRecordDelimiter && lastLetter == this.userSettings.RecordDelimiter)) { this.endColumn(); this.endRecord(); - } - else { + } else { this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; n2 = 1; } @@ -513,40 +492,32 @@ public class CsvReader } } } while (this.hasMoreData && this.startedColumn); - } - else if (c == this.userSettings.Delimiter) { + } else if (c == this.userSettings.Delimiter) { this.lastLetter = c; this.endColumn(); - } - else if (this.useCustomRecordDelimiter && c == this.userSettings.RecordDelimiter) { + } else if (this.useCustomRecordDelimiter && c == this.userSettings.RecordDelimiter) { if (this.startedColumn || this.columnsCount > 0 || !this.userSettings.SkipEmptyRecords) { this.endColumn(); this.endRecord(); - } - else { + } else { this.dataBuffer.LineStart = this.dataBuffer.Position + 1; } this.lastLetter = c; - } - else if (!this.useCustomRecordDelimiter && (c == '\r' || c == '\n')) { + } else if (!this.useCustomRecordDelimiter && (c == '\r' || c == '\n')) { if (this.startedColumn || this.columnsCount > 0 || (!this.userSettings.SkipEmptyRecords && (c == '\r' || this.lastLetter != '\r'))) { this.endColumn(); this.endRecord(); - } - else { + } else { this.dataBuffer.LineStart = this.dataBuffer.Position + 1; } this.lastLetter = c; - } - else if (this.userSettings.UseComments && this.columnsCount == 0 && c == this.userSettings.Comment) { + } else if (this.userSettings.UseComments && this.columnsCount == 0 && c == this.userSettings.Comment) { this.lastLetter = c; this.skipLine(); - } - else if (this.userSettings.TrimWhitespace && (c == ' ' || c == '\t')) { + } else if (this.userSettings.TrimWhitespace && (c == ' ' || c == '\t')) { this.startedColumn = true; this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; - } - else { + } else { this.startedColumn = true; this.dataBuffer.ColumnStart = this.dataBuffer.Position; int n7 = 0; @@ -558,25 +529,22 @@ public class CsvReader do { if (n11 == 0 && this.dataBuffer.Position == this.dataBuffer.Count) { this.checkDataLength(); - } - else { + } else { if (n11 == 0) { c = this.dataBuffer.Buffer[this.dataBuffer.Position]; } if (!this.userSettings.UseTextQualifier && this.userSettings.EscapeMode == 2 && c == '\\') { if (n7 != 0) { n7 = 0; - } - else { + } else { this.updateCurrentValue(); n7 = 1; } - } - else if (n8 != 0) { + } else if (n8 != 0) { ++n10; switch (n9) { case 1: { - c3 = (char)((char)(c3 * '\u0010') + hexToDec(c)); + c3 = (char) ((char) (c3 * '\u0010') + hexToDec(c)); if (n10 == 4) { n8 = 0; break; @@ -584,7 +552,7 @@ public class CsvReader break; } case 2: { - c3 = (char)((char)(c3 * '\b') + (char)(c - '0')); + c3 = (char) ((char) (c3 * '\b') + (char) (c - '0')); if (n10 == 3) { n8 = 0; break; @@ -592,7 +560,7 @@ public class CsvReader break; } case 3: { - c3 = (char)((char)(c3 * '\n') + (char)(c - '0')); + c3 = (char) ((char) (c3 * '\n') + (char) (c - '0')); if (n10 == 3) { n8 = 0; break; @@ -600,7 +568,7 @@ public class CsvReader break; } case 4: { - c3 = (char)((char)(c3 * '\u0010') + hexToDec(c)); + c3 = (char) ((char) (c3 * '\u0010') + hexToDec(c)); if (n10 == 2) { n8 = 0; break; @@ -610,12 +578,10 @@ public class CsvReader } if (n8 == 0) { this.appendLetter(c3); - } - else { + } else { this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; } - } - else if (this.userSettings.EscapeMode == 2 && n7 != 0) { + } else if (this.userSettings.EscapeMode == 2 && n7 != 0) { switch (c) { case 'n': { this.appendLetter('\n'); @@ -660,7 +626,7 @@ public class CsvReader n9 = 2; n8 = 1; n10 = 1; - c3 = (char)(c - '0'); + c3 = (char) (c - '0'); this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; break; } @@ -702,11 +668,9 @@ public class CsvReader } } n7 = 0; - } - else if (c == this.userSettings.Delimiter) { + } else if (c == this.userSettings.Delimiter) { this.endColumn(); - } - else if ((!this.useCustomRecordDelimiter && (c == '\r' || c == '\n')) || (this.useCustomRecordDelimiter && c == this.userSettings.RecordDelimiter)) { + } else if ((!this.useCustomRecordDelimiter && (c == '\r' || c == '\n')) || (this.useCustomRecordDelimiter && c == this.userSettings.RecordDelimiter)) { this.endColumn(); this.endRecord(); } @@ -740,21 +704,18 @@ public class CsvReader if (this.hasMoreData) { if (this.rawBuffer.Position == 0) { this.rawRecord = new String(this.dataBuffer.Buffer, this.dataBuffer.LineStart, this.dataBuffer.Position - this.dataBuffer.LineStart - 1); - } - else { + } else { this.rawRecord = new String(this.rawBuffer.Buffer, 0, this.rawBuffer.Position) + new String(this.dataBuffer.Buffer, this.dataBuffer.LineStart, this.dataBuffer.Position - this.dataBuffer.LineStart - 1); } - } - else { + } else { this.rawRecord = new String(this.rawBuffer.Buffer, 0, this.rawBuffer.Position); } - } - else { + } else { this.rawRecord = ""; } return this.hasReadNextLine; } - + private void checkDataLength() throws IOException { if (!this.initialized) { if (this.fileName != null) { @@ -776,8 +737,7 @@ public class CsvReader } try { this.dataBuffer.Count = this.inputStream.read(this.dataBuffer.Buffer, 0, this.dataBuffer.Buffer.length); - } - catch (IOException ex) { + } catch (IOException ex) { this.close(); throw ex; } @@ -788,7 +748,7 @@ public class CsvReader this.dataBuffer.LineStart = 0; this.dataBuffer.ColumnStart = 0; } - + public boolean readHeaders() throws IOException { final boolean record = this.readRecord(); this.headersHolder.Length = this.columnsCount; @@ -804,7 +764,7 @@ public class CsvReader this.columnsCount = 0; return record; } - + public String getHeader(final int n) throws IOException { this.checkClosed(); if (n > -1 && n < this.headersHolder.Length) { @@ -812,12 +772,12 @@ public class CsvReader } return ""; } - + public boolean isQualified(final int n) throws IOException { this.checkClosed(); return n < this.columnsCount && n > -1 && this.isQualified[n]; } - + public void endColumn() throws IOException { String s = ""; if (this.startedColumn) { @@ -831,8 +791,7 @@ public class CsvReader } s = new String(this.dataBuffer.Buffer, this.dataBuffer.ColumnStart, n - this.dataBuffer.ColumnStart + 1); } - } - else { + } else { this.updateCurrentValue(); int n2 = this.columnBuffer.Position - 1; if (this.userSettings.TrimWhitespace && !this.startedWithQualifier) { @@ -862,7 +821,7 @@ public class CsvReader this.isQualified[this.columnsCount] = this.startedWithQualifier; ++this.columnsCount; } - + private void appendLetter(final char c) { if (this.columnBuffer.Position == this.columnBuffer.Buffer.length) { final char[] buffer = new char[this.columnBuffer.Buffer.length * 2]; @@ -872,7 +831,7 @@ public class CsvReader this.columnBuffer.Buffer[this.columnBuffer.Position++] = c; this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; } - + private void updateCurrentValue() { if (this.startedColumn && this.dataBuffer.ColumnStart < this.dataBuffer.Position) { if (this.columnBuffer.Buffer.length - this.columnBuffer.Position < this.dataBuffer.Position - this.dataBuffer.ColumnStart) { @@ -891,7 +850,7 @@ public class CsvReader this.hasReadNextLine = true; ++this.currentRecord; } - + public int getIndex(final String s) throws IOException { this.checkClosed(); final Integer value = this.headersHolder.IndexByName.get(s); @@ -900,7 +859,7 @@ public class CsvReader } return -1; } - + public boolean skipRecord() throws IOException { this.checkClosed(); boolean record = false; @@ -912,7 +871,7 @@ public class CsvReader } return record; } - + public boolean skipLine() throws IOException { this.checkClosed(); this.columnsCount = 0; @@ -922,8 +881,7 @@ public class CsvReader do { if (this.dataBuffer.Position == this.dataBuffer.Count) { this.checkDataLength(); - } - else { + } else { b = true; final char lastLetter = this.dataBuffer.Buffer[this.dataBuffer.Position]; if (lastLetter == '\r' || lastLetter == '\n') { @@ -944,14 +902,14 @@ public class CsvReader this.rawRecord = ""; return b; } - + public void close() { if (!this.closed) { this.close(true); this.closed = true; } } - + private void close(final boolean b) { if (!this.closed) { if (b) { @@ -972,55 +930,50 @@ public class CsvReader this.closed = true; } } - + private void checkClosed() throws IOException { if (this.closed) { throw new IOException("This instance of the CsvReader class has already been closed."); } } - + @Override - protected void finalize() { + protected void finalize() { this.close(false); } - + private static char hexToDec(final char c) { char c2; if (c >= 'a') { - c2 = (char)(c - 'a' + '\n'); - } - else if (c >= 'A') { - c2 = (char)(c - 'A' + '\n'); - } - else { - c2 = (char)(c - '0'); + c2 = (char) (c - 'a' + '\n'); + } else if (c >= 'A') { + c2 = (char) (c - 'A' + '\n'); + } else { + c2 = (char) (c - '0'); } return c2; } - - private class StaticSettings - { + + private class StaticSettings { public static final int MAX_BUFFER_SIZE = 1024; public static final int MAX_FILE_BUFFER_SIZE = 4096; public static final int INITIAL_COLUMN_COUNT = 10; public static final int INITIAL_COLUMN_BUFFER_SIZE = 50; } - - private class HeadersHolder - { + + private class HeadersHolder { public String[] Headers; public int Length; public HashMap IndexByName; - + public HeadersHolder() { this.Headers = null; this.Length = 0; this.IndexByName = new HashMap<>(); } } - - private class UserSettings - { + + private class UserSettings { public boolean CaseSensitive; public char TextQualifier; public boolean TrimWhitespace; @@ -1033,7 +986,7 @@ public class CsvReader public boolean SafetySwitch; public boolean SkipEmptyRecords; public boolean CaptureRawRecord; - + public UserSettings() { this.CaseSensitive = true; this.TextQualifier = '\"'; @@ -1049,9 +1002,8 @@ public class CsvReader this.CaptureRawRecord = true; } } - - private class Letters - { + + private class Letters { public static final char LF = '\n'; public static final char CR = '\r'; public static final char QUOTE = '\"'; @@ -1067,37 +1019,34 @@ public class CsvReader public static final char VERTICAL_TAB = '\u000b'; public static final char ALERT = '\u0007'; } - - private class RawRecordBuffer - { + + private class RawRecordBuffer { public char[] Buffer; public int Position; - + public RawRecordBuffer() { this.Buffer = new char[500]; this.Position = 0; } } - - private class ColumnBuffer - { + + private class ColumnBuffer { public char[] Buffer; public int Position; - + public ColumnBuffer() { this.Buffer = new char[50]; this.Position = 0; } } - - private class DataBuffer - { + + private class DataBuffer { public char[] Buffer; public int Position; public int Count; public int ColumnStart; public int LineStart; - + public DataBuffer() { this.Buffer = new char[1024]; this.Position = 0; @@ -1106,9 +1055,8 @@ public class CsvReader this.LineStart = 0; } } - - private class ComplexEscape - { + + private class ComplexEscape { private static final int UNICODE = 1; private static final int OCTAL = 2; private static final int DECIMAL = 3; diff --git a/src/main/java/me/skymc/taboolib/csvutils/CsvWriter.java b/src/main/java/me/skymc/taboolib/csvutils/CsvWriter.java index 1253798..9aefa35 100644 --- a/src/main/java/me/skymc/taboolib/csvutils/CsvWriter.java +++ b/src/main/java/me/skymc/taboolib/csvutils/CsvWriter.java @@ -1,15 +1,10 @@ package me.skymc.taboolib.csvutils; -import java.io.BufferedWriter; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; +import java.io.*; import java.nio.charset.Charset; -public class CsvWriter -{ +public class CsvWriter { + private Writer outputStream; private String fileName; private boolean firstColumn; @@ -21,7 +16,7 @@ public class CsvWriter private String systemRecordDelimiter; public static final int ESCAPE_MODE_DOUBLED = 1; public static final int ESCAPE_MODE_BACKSLASH = 2; - + public CsvWriter(final String fileName, final char delimiter, final Charset charset) { this.outputStream = null; this.fileName = null; @@ -42,11 +37,11 @@ public class CsvWriter this.userSettings.Delimiter = delimiter; this.charset = charset; } - + public CsvWriter(final String s) { this(s, ',', Charset.forName("ISO-8859-1")); } - + public CsvWriter(final Writer outputStream, final char delimiter) { this.outputStream = null; this.fileName = null; @@ -64,68 +59,68 @@ public class CsvWriter this.userSettings.Delimiter = delimiter; this.initialized = true; } - + public CsvWriter(final OutputStream outputStream, final char c, final Charset charset) { this(new OutputStreamWriter(outputStream, charset), c); } - + public char getDelimiter() { return this.userSettings.Delimiter; } - + public void setDelimiter(final char delimiter) { this.userSettings.Delimiter = delimiter; } - + public char getRecordDelimiter() { return this.userSettings.RecordDelimiter; } - + public void setRecordDelimiter(final char recordDelimiter) { this.useCustomRecordDelimiter = true; this.userSettings.RecordDelimiter = recordDelimiter; } - + public char getTextQualifier() { return this.userSettings.TextQualifier; } - + public void setTextQualifier(final char textQualifier) { this.userSettings.TextQualifier = textQualifier; } - + public boolean getUseTextQualifier() { return this.userSettings.UseTextQualifier; } - + public void setUseTextQualifier(final boolean useTextQualifier) { this.userSettings.UseTextQualifier = useTextQualifier; } - + public int getEscapeMode() { return this.userSettings.EscapeMode; } - + public void setEscapeMode(final int escapeMode) { this.userSettings.EscapeMode = escapeMode; } - + public void setComment(final char comment) { this.userSettings.Comment = comment; } - + public char getComment() { return this.userSettings.Comment; } - + public boolean getForceQualifier() { return this.userSettings.ForceQualifier; } - + public void setForceQualifier(final boolean forceQualifier) { this.userSettings.ForceQualifier = forceQualifier; } - + public void write(String s, final boolean b) throws IOException { this.checkClosed(); this.checkInit(); @@ -159,26 +154,22 @@ public class CsvWriter if (this.userSettings.EscapeMode == 2) { s = replace(s, "\\", "\\\\"); s = replace(s, "" + this.userSettings.TextQualifier, "\\" + this.userSettings.TextQualifier); - } - else { + } else { s = replace(s, "" + this.userSettings.TextQualifier, "" + this.userSettings.TextQualifier + this.userSettings.TextQualifier); } - } - else if (this.userSettings.EscapeMode == 2) { + } else if (this.userSettings.EscapeMode == 2) { s = replace(s, "\\", "\\\\"); s = replace(s, "" + this.userSettings.Delimiter, "\\" + this.userSettings.Delimiter); if (this.useCustomRecordDelimiter) { s = replace(s, "" + this.userSettings.RecordDelimiter, "\\" + this.userSettings.RecordDelimiter); - } - else { + } else { s = replace(s, "\r", "\\\r"); s = replace(s, "\n", "\\\n"); } if (this.firstColumn && s.length() > 0 && s.charAt(0) == this.userSettings.Comment) { if (s.length() > 1) { s = "\\" + this.userSettings.Comment + s.substring(1); - } - else { + } else { s = "\\" + this.userSettings.Comment; } } @@ -189,11 +180,11 @@ public class CsvWriter } this.firstColumn = false; } - + public void write(final String s) throws IOException { this.write(s, false); } - + public void writeComment(final String s) throws IOException { this.checkClosed(); this.checkInit(); @@ -201,8 +192,7 @@ public class CsvWriter this.outputStream.write(s); if (this.useCustomRecordDelimiter) { this.outputStream.write(this.userSettings.RecordDelimiter); - } - else { + } else { this.outputStream.write(this.systemRecordDelimiter); } this.firstColumn = true; @@ -224,23 +214,22 @@ public class CsvWriter } return s; } - + public void writeRecord(final String[] array) throws IOException { this.writeRecord(array, false); } - + public void endRecord() throws IOException { this.checkClosed(); this.checkInit(); if (this.useCustomRecordDelimiter) { this.outputStream.write(this.userSettings.RecordDelimiter); - } - else { + } else { this.outputStream.write(this.systemRecordDelimiter); } this.firstColumn = true; } - + private void checkInit() throws IOException { if (!this.initialized) { if (this.fileName != null) { @@ -249,11 +238,11 @@ public class CsvWriter this.initialized = true; } } - + public void flush() throws IOException { this.outputStream.flush(); } - + public void close() { if (!this.closed) { this.close(true); @@ -277,10 +266,10 @@ public class CsvWriter } @Override - protected void finalize() { + protected void finalize() { this.close(false); } - + private void close(final boolean b) { if (!this.closed) { if (b) { @@ -296,9 +285,8 @@ public class CsvWriter this.closed = true; } } - - private class UserSettings - { + + private class UserSettings { public char TextQualifier; public boolean UseTextQualifier; public char Delimiter; @@ -306,7 +294,7 @@ public class CsvWriter public char Comment; public int EscapeMode; public boolean ForceQualifier; - + public UserSettings() { this.TextQualifier = '\"'; this.UseTextQualifier = true; @@ -317,9 +305,8 @@ public class CsvWriter this.ForceQualifier = false; } } - - private class Letters - { + + private class Letters { public static final char LF = '\n'; public static final char CR = '\r'; public static final char QUOTE = '\"'; diff --git a/src/main/java/me/skymc/taboolib/damage/DamageUtils.java b/src/main/java/me/skymc/taboolib/damage/DamageUtils.java index 45c6837..a614445 100644 --- a/src/main/java/me/skymc/taboolib/damage/DamageUtils.java +++ b/src/main/java/me/skymc/taboolib/damage/DamageUtils.java @@ -1,71 +1,58 @@ package me.skymc.taboolib.damage; -import java.lang.reflect.InvocationTargetException; - +import me.skymc.taboolib.TabooLib; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; -import me.skymc.taboolib.TabooLib; +import java.lang.reflect.InvocationTargetException; public class DamageUtils { - - public static void damage(Player damager, LivingEntity victim, double damage) - { - dmg(damager, victim, damage); - } - - public static void damage(Player damager, Entity victim, double damage) - { - if (victim instanceof LivingEntity) { - dmg(damager, (LivingEntity) victim, damage); - } - } - - public static void dmg(LivingEntity paramLivingEntity1, LivingEntity paramLivingEntity2, double paramDouble) - { - if ((paramLivingEntity2.hasMetadata("NPC")) || (paramLivingEntity1.hasMetadata("NPC"))) { - return; - } - - Object localObject1 = null; - try - { - localObject1 = paramLivingEntity1.getClass().getDeclaredMethod("getHandle", new Class[0]).invoke(paramLivingEntity1); - } - catch (IllegalAccessException|IllegalArgumentException|InvocationTargetException|NoSuchMethodException|SecurityException localIllegalAccessException1) - { - return; - } - - Object localObject2 = null; - try - { - localObject2 = paramLivingEntity2.getClass().getDeclaredMethod("getHandle", new Class[0]).invoke(paramLivingEntity2); - } - catch (IllegalAccessException|IllegalArgumentException|InvocationTargetException|NoSuchMethodException|SecurityException localIllegalAccessException2) - { - return; - } - - try - { - Class DamageSource = nmsClass("DamageSource"); - Object localObject3 = DamageSource.getDeclaredMethod("playerAttack", new Class[]{nmsClass("EntityHuman")}).invoke(DamageSource, localObject1); - localObject2.getClass().getDeclaredMethod("damageEntity", new Class[]{DamageSource, Float.TYPE}).invoke(localObject2, localObject3, (float) paramDouble); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ignored) - { - } - } - - private static Class nmsClass(String paramString) - { - String str = "net.minecraft.server." + TabooLib.getVersion() + "." + paramString; - try { - return Class.forName(str); - } catch (ClassNotFoundException e) { - return null; - } - } + public static void damage(Player player, LivingEntity victim, double damage) { + dmg(player, victim, damage); + } + + public static void damage(Player player, Entity victim, double damage) { + if (victim instanceof LivingEntity) { + dmg(player, (LivingEntity) victim, damage); + } + } + + public static void dmg(LivingEntity paramLivingEntity1, LivingEntity paramLivingEntity2, double paramDouble) { + if ((paramLivingEntity2.hasMetadata("NPC")) || (paramLivingEntity1.hasMetadata("NPC"))) { + return; + } + + Object localObject1; + try { + localObject1 = paramLivingEntity1.getClass().getDeclaredMethod("getHandle").invoke(paramLivingEntity1); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException localIllegalAccessException1) { + return; + } + + Object localObject2; + try { + localObject2 = paramLivingEntity2.getClass().getDeclaredMethod("getHandle").invoke(paramLivingEntity2); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException localIllegalAccessException2) { + return; + } + + try { + Class DamageSource = nmsClass("DamageSource"); + Object localObject3 = DamageSource.getDeclaredMethod("playerAttack", nmsClass("EntityHuman")).invoke(DamageSource, localObject1); + + localObject2.getClass().getDeclaredMethod("damageEntity", new Class[]{DamageSource, Float.TYPE}).invoke(localObject2, localObject3, (float) paramDouble); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ignored) { + } + } + + private static Class nmsClass(String paramString) { + String str = "net.minecraft.server." + TabooLib.getVersion() + "." + paramString; + try { + return Class.forName(str); + } catch (ClassNotFoundException e) { + return null; + } + } } diff --git a/src/main/java/me/skymc/taboolib/damage/GetDamager.java b/src/main/java/me/skymc/taboolib/damage/GetDamager.java index 71b1b10..aee2773 100644 --- a/src/main/java/me/skymc/taboolib/damage/GetDamager.java +++ b/src/main/java/me/skymc/taboolib/damage/GetDamager.java @@ -5,19 +5,18 @@ import org.bukkit.entity.Projectile; import org.bukkit.event.entity.EntityDamageByEntityEvent; public class GetDamager { - - public static Player get(EntityDamageByEntityEvent e) { - Player p = null; - if (e.getDamager() instanceof Projectile) { - Projectile arrow = (Projectile) e.getDamager(); - if (arrow.getShooter() instanceof Player) { - p = (Player) arrow.getShooter(); - } - } - else if (e.getDamager() instanceof Player) { - p = (Player) e.getDamager(); - } - return p; - } + + public static Player get(EntityDamageByEntityEvent e) { + Player p = null; + if (e.getDamager() instanceof Projectile) { + Projectile arrow = (Projectile) e.getDamager(); + if (arrow.getShooter() instanceof Player) { + p = (Player) arrow.getShooter(); + } + } else if (e.getDamager() instanceof Player) { + p = (Player) e.getDamager(); + } + return p; + } } diff --git a/src/main/java/me/skymc/taboolib/damage/GetKiller.java b/src/main/java/me/skymc/taboolib/damage/GetKiller.java index ca9b143..1206c85 100644 --- a/src/main/java/me/skymc/taboolib/damage/GetKiller.java +++ b/src/main/java/me/skymc/taboolib/damage/GetKiller.java @@ -5,19 +5,18 @@ import org.bukkit.entity.Projectile; import org.bukkit.event.entity.EntityDeathEvent; public class GetKiller { - - public static Player get(EntityDeathEvent e) { - Player p = null; - if (e.getEntity().getKiller() instanceof Projectile) { - Projectile arrow = (Projectile) e.getEntity().getKiller(); - if (arrow.getShooter() instanceof Player) { - p = (Player) arrow.getShooter(); - } - } - else if (e.getEntity().getKiller() instanceof Player) { - p = e.getEntity().getKiller(); - } - return p; - } + + public static Player get(EntityDeathEvent e) { + Player p = null; + if (e.getEntity().getKiller() instanceof Projectile) { + Projectile arrow = (Projectile) e.getEntity().getKiller(); + if (arrow.getShooter() instanceof Player) { + p = (Player) arrow.getShooter(); + } + } else if (e.getEntity().getKiller() != null) { + p = e.getEntity().getKiller(); + } + return p; + } } diff --git a/src/main/java/me/skymc/taboolib/database/PlayerDataManager.java b/src/main/java/me/skymc/taboolib/database/PlayerDataManager.java index 0a87f65..5efcf54 100644 --- a/src/main/java/me/skymc/taboolib/database/PlayerDataManager.java +++ b/src/main/java/me/skymc/taboolib/database/PlayerDataManager.java @@ -1,9 +1,12 @@ package me.skymc.taboolib.database; -import java.io.File; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - +import me.skymc.taboolib.Main; +import me.skymc.taboolib.Main.StorageType; +import me.skymc.taboolib.events.PlayerLoadedEvent; +import me.skymc.taboolib.exception.PlayerOfflineException; +import me.skymc.taboolib.fileutils.ConfigUtils; +import me.skymc.taboolib.fileutils.FileUtils; +import me.skymc.taboolib.message.MsgUtils; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.configuration.file.FileConfiguration; @@ -15,256 +18,243 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.scheduler.BukkitRunnable; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.Main.StorageType; -import me.skymc.taboolib.events.PlayerLoadedEvent; -import me.skymc.taboolib.exception.PlayerOfflineException; -import me.skymc.taboolib.fileutils.ConfigUtils; -import me.skymc.taboolib.fileutils.FileUtils; -import me.skymc.taboolib.message.MsgUtils; +import java.io.File; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; public class PlayerDataManager implements Listener { - - private static final ConcurrentHashMap PLAYER_DATA = new ConcurrentHashMap<>(); + + private static final ConcurrentHashMap PLAYER_DATA = new ConcurrentHashMap<>(); public enum UsernameType { UUID, USERNAME - } - - /** - * 获取用户储存方式 - * - * @return - */ - public static UsernameType getUsernameType() { - return Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? UsernameType.UUID : UsernameType.USERNAME; - } - - /** - * 获取玩家数据 - * - * @param player 玩家 - * @return - * @throws PlayerOfflineException - */ - public static FileConfiguration getPlayerData(Player player) { - if (getUsernameType() == UsernameType.UUID) { - return getPlayerData(player.getUniqueId().toString(), false); - } - else { - return getPlayerData(player.getName(), false); - } - } - - /** - * 获取玩家数据 - * - * @param player - * @return - */ - public static FileConfiguration getPlayerData(OfflinePlayer player) { - if (!player.isOnline()) { - return null; - } - if (getUsernameType() == UsernameType.UUID) { - return getPlayerData(player.getUniqueId().toString(), false); - } - else { - return getPlayerData(player.getName(), false); - } - } - - /** - * 读取玩家数据 - * - * @param username 玩家 - * @return - * @throws PlayerOfflineException - */ - public static FileConfiguration getPlayerData(String username, boolean offline) { - if (PLAYER_DATA.containsKey(username)) { - return PLAYER_DATA.get(username); - } - else if (offline) { - if (Main.getStorageType() == StorageType.SQL) { - throw new PlayerOfflineException("不允许在储存模式为数据库的情况下获取离线玩家数据"); - } - return loadPlayerData(username); - } - return null; - } - - /** - * 载入玩家数据 - * - * @param username 玩家 - * @return - */ - public static FileConfiguration loadPlayerData(String username) { - // 本地储存 - if (Main.getStorageType() == StorageType.LOCAL) { - // 读取文件 - File file = FileUtils.file(Main.getPlayerDataFolder(), username + ".yml"); - // 载入配置 - PLAYER_DATA.put(username, YamlConfiguration.loadConfiguration(file)); - } - else { - // 数据是否存在 - if (Main.getConnection().isExists(Main.getTablePrefix() + "_playerdata", "username", username)) { - // 获取数据 - String code = Main.getConnection().getValue(Main.getTablePrefix() + "_playerdata", "username", username, "configuration").toString(); - try { - // 载入配置 - PLAYER_DATA.put(username, ConfigUtils.decodeYAML(code)); - } - catch (Exception e) { - // 创建空数据 - PLAYER_DATA.put(username, new YamlConfiguration()); - // 反馈信息 - MsgUtils.warn("玩家 &4" + username + " &c的数据载入出现异常: &4" + e.getMessage()); - } - } - else { - // 创建空数据 - PLAYER_DATA.put(username, new YamlConfiguration()); - } - } - return PLAYER_DATA.get(username); - } - - /** - * 保存玩家数据 - * - * @param username 玩家 - * @param remove 是否移除缓存 - */ - public static void savePlayerData(String username, boolean remove) { - // 没有数据 - if (!PLAYER_DATA.containsKey(username)) { - return; - } - // 本地储存 - if (Main.getStorageType() == StorageType.LOCAL) { - // 读取文件 - File file = FileUtils.file(Main.getPlayerDataFolder(), username + ".yml"); - // 保存配置 - try { - PLAYER_DATA.get(username).save(file); - } - catch (Exception e) { - // TODO: handle exception - } - } - // 如果是数据库储存且有数据 - else if (PLAYER_DATA.get(username).getConfigurationSection("").getKeys(false).size() > 0) { - // 数据是否存在 - if (Main.getConnection().isExists(Main.getTablePrefix() + "_playerdata", "username", username)) { - // 写入数据 - Main.getConnection().setValue(Main.getTablePrefix() + "_playerdata", "username", username, "configuration", ConfigUtils.encodeYAML(PLAYER_DATA.get(username))); - } - else { - // 插入数据 - Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", username, ConfigUtils.encodeYAML(PLAYER_DATA.get(username))); - } - } - // 获取这个属性对应的玩家 - Player player; - if (getUsernameType() == UsernameType.UUID) { - player = Bukkit.getPlayer(UUID.fromString(username)); - } - else { - player = Bukkit.getPlayerExact(username); - } - // 如果移除数据 或 玩家不在线 - if (remove || player == null) { - PLAYER_DATA.remove(username); - } - } - - /** - * 保存所有玩家的缓存 - * - * @param sync 是否异步进行 - * @param remove 是否移除数据 - */ - public static void saveAllCaches(boolean sync, boolean remove) { - BukkitRunnable runnable = new BukkitRunnable() { - - @Override - public void run() { - long time = System.currentTimeMillis(); - // 保存 - for (String name : PLAYER_DATA.keySet()) { - savePlayerData(name, false); - } - // 提示 - if (!Main.getInst().getConfig().getBoolean("HIDE-NOTIFY")) { - MsgUtils.send("保存 &f" + PLAYER_DATA.size() + " &7条玩家数据, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)"); - } - } - }; - // 如果异步 - if (sync) { - runnable.runTaskAsynchronously(Main.getInst()); - } - // 如果同步 - else { - runnable.run(); - } - } - - /** - * 保存所有玩家的数据 - * - * @param sync 是否异步进行 - * @param remove 是否移除数据 - */ - public static void saveAllPlayers(boolean sync, boolean remove) { - // 创建任务 - BukkitRunnable runnable = new BukkitRunnable() { - - @Override - public void run() { - for (Player player : Bukkit.getOnlinePlayers()) { - savePlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? player.getUniqueId().toString() : player.getName(), remove); - } - } - }; - // 如果异步 - if (sync) { - runnable.runTaskAsynchronously(Main.getInst()); - } - // 如果同步 - else { - runnable.run(); - } - } - - @EventHandler - public void join(PlayerJoinEvent e) { - new BukkitRunnable() { - - @Override - public void run() { - // 载入数据 - loadPlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName()); - // 载入完成 - Bukkit.getPluginManager().callEvent(new PlayerLoadedEvent(e.getPlayer())); - } - }.runTaskAsynchronously(Main.getInst()); - } - - @EventHandler - public void quit(PlayerQuitEvent e) { - if (!Main.isDisable()) { - new BukkitRunnable() { - - @Override - public void run() { - // 保存数据 - savePlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName(), true); - } - }.runTaskAsynchronously(Main.getInst()); - } - } + } + + /** + * 获取用户储存方式 + * + * @return + */ + public static UsernameType getUsernameType() { + return Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? UsernameType.UUID : UsernameType.USERNAME; + } + + /** + * 获取玩家数据 + * + * @param player 玩家 + * @return + * @throws PlayerOfflineException + */ + public static FileConfiguration getPlayerData(Player player) { + if (getUsernameType() == UsernameType.UUID) { + return getPlayerData(player.getUniqueId().toString(), false); + } else { + return getPlayerData(player.getName(), false); + } + } + + /** + * 获取玩家数据 + * + * @param player + * @return + */ + public static FileConfiguration getPlayerData(OfflinePlayer player) { + if (!player.isOnline()) { + return null; + } + if (getUsernameType() == UsernameType.UUID) { + return getPlayerData(player.getUniqueId().toString(), false); + } else { + return getPlayerData(player.getName(), false); + } + } + + /** + * 读取玩家数据 + * + * @param username 玩家 + * @return + * @throws PlayerOfflineException + */ + public static FileConfiguration getPlayerData(String username, boolean offline) { + if (PLAYER_DATA.containsKey(username)) { + return PLAYER_DATA.get(username); + } else if (offline) { + if (Main.getStorageType() == StorageType.SQL) { + throw new PlayerOfflineException("不允许在储存模式为数据库的情况下获取离线玩家数据"); + } + return loadPlayerData(username); + } + return null; + } + + /** + * 载入玩家数据 + * + * @param username 玩家 + * @return + */ + public static FileConfiguration loadPlayerData(String username) { + // 本地储存 + if (Main.getStorageType() == StorageType.LOCAL) { + // 读取文件 + File file = FileUtils.file(Main.getPlayerDataFolder(), username + ".yml"); + // 载入配置 + PLAYER_DATA.put(username, YamlConfiguration.loadConfiguration(file)); + } else { + // 数据是否存在 + if (Main.getConnection().isExists(Main.getTablePrefix() + "_playerdata", "username", username)) { + // 获取数据 + String code = Main.getConnection().getValue(Main.getTablePrefix() + "_playerdata", "username", username, "configuration").toString(); + try { + // 载入配置 + PLAYER_DATA.put(username, ConfigUtils.decodeYAML(code)); + } catch (Exception e) { + // 创建空数据 + PLAYER_DATA.put(username, new YamlConfiguration()); + // 反馈信息 + MsgUtils.warn("玩家 &4" + username + " &c的数据载入出现异常: &4" + e.getMessage()); + } + } else { + // 创建空数据 + PLAYER_DATA.put(username, new YamlConfiguration()); + } + } + return PLAYER_DATA.get(username); + } + + /** + * 保存玩家数据 + * + * @param username 玩家 + * @param remove 是否移除缓存 + */ + public static void savePlayerData(String username, boolean remove) { + // 没有数据 + if (!PLAYER_DATA.containsKey(username)) { + return; + } + // 本地储存 + if (Main.getStorageType() == StorageType.LOCAL) { + // 读取文件 + File file = FileUtils.file(Main.getPlayerDataFolder(), username + ".yml"); + // 保存配置 + try { + PLAYER_DATA.get(username).save(file); + } catch (Exception e) { + // TODO: handle exception + } + } + // 如果是数据库储存且有数据 + else if (PLAYER_DATA.get(username).getConfigurationSection("").getKeys(false).size() > 0) { + // 数据是否存在 + if (Main.getConnection().isExists(Main.getTablePrefix() + "_playerdata", "username", username)) { + // 写入数据 + Main.getConnection().setValue(Main.getTablePrefix() + "_playerdata", "username", username, "configuration", ConfigUtils.encodeYAML(PLAYER_DATA.get(username))); + } else { + // 插入数据 + Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", username, ConfigUtils.encodeYAML(PLAYER_DATA.get(username))); + } + } + // 获取这个属性对应的玩家 + Player player; + if (getUsernameType() == UsernameType.UUID) { + player = Bukkit.getPlayer(UUID.fromString(username)); + } else { + player = Bukkit.getPlayerExact(username); + } + // 如果移除数据 或 玩家不在线 + if (remove || player == null) { + PLAYER_DATA.remove(username); + } + } + + /** + * 保存所有玩家的缓存 + * + * @param sync 是否异步进行 + * @param remove 是否移除数据 + */ + public static void saveAllCaches(boolean sync, boolean remove) { + BukkitRunnable runnable = new BukkitRunnable() { + + @Override + public void run() { + long time = System.currentTimeMillis(); + // 保存 + for (String name : PLAYER_DATA.keySet()) { + savePlayerData(name, false); + } + // 提示 + if (!Main.getInst().getConfig().getBoolean("HIDE-NOTIFY")) { + MsgUtils.send("保存 &f" + PLAYER_DATA.size() + " &7条玩家数据, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)"); + } + } + }; + // 如果异步 + if (sync) { + runnable.runTaskAsynchronously(Main.getInst()); + } + // 如果同步 + else { + runnable.run(); + } + } + + /** + * 保存所有玩家的数据 + * + * @param sync 是否异步进行 + * @param remove 是否移除数据 + */ + public static void saveAllPlayers(boolean sync, boolean remove) { + // 创建任务 + BukkitRunnable runnable = new BukkitRunnable() { + + @Override + public void run() { + for (Player player : Bukkit.getOnlinePlayers()) { + savePlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? player.getUniqueId().toString() : player.getName(), remove); + } + } + }; + // 如果异步 + if (sync) { + runnable.runTaskAsynchronously(Main.getInst()); + } + // 如果同步 + else { + runnable.run(); + } + } + + @EventHandler + public void join(PlayerJoinEvent e) { + new BukkitRunnable() { + + @Override + public void run() { + // 载入数据 + loadPlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName()); + // 载入完成 + Bukkit.getPluginManager().callEvent(new PlayerLoadedEvent(e.getPlayer())); + } + }.runTaskAsynchronously(Main.getInst()); + } + + @EventHandler + public void quit(PlayerQuitEvent e) { + if (!Main.isDisable()) { + new BukkitRunnable() { + + @Override + public void run() { + // 保存数据 + savePlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName(), true); + } + }.runTaskAsynchronously(Main.getInst()); + } + } } diff --git a/src/main/java/me/skymc/taboolib/economy/EcoUtils.java b/src/main/java/me/skymc/taboolib/economy/EcoUtils.java index 21f370d..9d4fb41 100644 --- a/src/main/java/me/skymc/taboolib/economy/EcoUtils.java +++ b/src/main/java/me/skymc/taboolib/economy/EcoUtils.java @@ -1,34 +1,33 @@ package me.skymc.taboolib.economy; +import me.skymc.taboolib.Main; +import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.plugin.RegisteredServiceProvider; -import me.skymc.taboolib.Main; -import net.milkbowl.vault.economy.Economy; - public class EcoUtils { - - public static void setupEconomy() { - RegisteredServiceProvider l = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); - if (l != null) { - Main.setEconomy(l.getProvider()); - } - } - - public static void remove(OfflinePlayer p, double d) { - Main.getEconomy().withdrawPlayer(p, d); - } - - public static void add(OfflinePlayer p, double d) { - Main.getEconomy().depositPlayer(p, d); - } - - public static double get(OfflinePlayer p) { - return Main.getEconomy().getBalance(p); - } - - public static void create(OfflinePlayer p) { - Main.getEconomy().createPlayerAccount(p); - } + + public static void setupEconomy() { + RegisteredServiceProvider l = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); + if (l != null) { + Main.setEconomy(l.getProvider()); + } + } + + public static void remove(OfflinePlayer p, double d) { + Main.getEconomy().withdrawPlayer(p, d); + } + + public static void add(OfflinePlayer p, double d) { + Main.getEconomy().depositPlayer(p, d); + } + + public static double get(OfflinePlayer p) { + return Main.getEconomy().getBalance(p); + } + + public static void create(OfflinePlayer p) { + Main.getEconomy().createPlayerAccount(p); + } } diff --git a/src/main/java/me/skymc/taboolib/entity/EntityTag.java b/src/main/java/me/skymc/taboolib/entity/EntityTag.java index ce32a0d..49ff915 100644 --- a/src/main/java/me/skymc/taboolib/entity/EntityTag.java +++ b/src/main/java/me/skymc/taboolib/entity/EntityTag.java @@ -1,272 +1,271 @@ package me.skymc.taboolib.entity; +import me.skymc.taboolib.Main; +import org.bukkit.entity.Entity; +import org.bukkit.scheduler.BukkitRunnable; + import java.util.List; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import org.bukkit.entity.Entity; -import org.bukkit.scheduler.BukkitRunnable; - -import me.skymc.taboolib.Main; - /** * 伪 - MetaData - * + * * @author sky * @since 2018-03-11 11:43:41 */ public class EntityTag { - - private static EntityTag inst; - private static ConcurrentHashMap> entityData = new ConcurrentHashMap<>(); - - private EntityTag() { - new BukkitRunnable() { - - @Override - public void run() { - for (UUID uuid : entityData.keySet()) { - if (EntityUtils.getEntityWithUUID(uuid) == null) { - entityData.remove(uuid); - } - } - } - }.runTaskTimerAsynchronously(Main.getInst(), 20 * 180, 20 * 180); - } - - public static EntityTag getInst() { - if (inst == null) { - synchronized (EntityTag.class) { - if (inst == null) { - inst = new EntityTag(); - } - } - } - return inst; - } - - /** - * 设置标签 - * - * @param entity 实体 - * @param key 键 - * @param value 值 - */ - public void set(String key, Object value, Entity entity) { - if (contains(entity)) { - entityData.get(entity.getUniqueId()).put(key, value); - } else { - ConcurrentHashMap map = new ConcurrentHashMap<>(); - map.put(key, value); - entityData.put(entity.getUniqueId(), map); - } - } - - /** - * 设置标签 - * - * @param key 键 - * @param value 值 + + private static EntityTag inst; + private static ConcurrentHashMap> entityData = new ConcurrentHashMap<>(); + + private EntityTag() { + new BukkitRunnable() { + + @Override + public void run() { + for (UUID uuid : entityData.keySet()) { + if (EntityUtils.getEntityWithUUID(uuid) == null) { + entityData.remove(uuid); + } + } + } + }.runTaskTimerAsynchronously(Main.getInst(), 20 * 180, 20 * 180); + } + + public static EntityTag getInst() { + if (inst == null) { + synchronized (EntityTag.class) { + if (inst == null) { + inst = new EntityTag(); + } + } + } + return inst; + } + + /** + * 设置标签 + * + * @param entity 实体 + * @param key 键 + * @param value 值 */ - public void set(String key, Object value, Entity... entities) { - for (Entity entity : entities) set(key, value, entity); - } - - /** - * 设置标签 - * - * @param key 键 - * @param value 值 + public void set(String key, Object value, Entity entity) { + if (contains(entity)) { + entityData.get(entity.getUniqueId()).put(key, value); + } else { + ConcurrentHashMap map = new ConcurrentHashMap<>(); + map.put(key, value); + entityData.put(entity.getUniqueId(), map); + } + } + + /** + * 设置标签 + * + * @param key 键 + * @param value 值 */ - public void set(String key, Object value, List entities) { - for (Entity entity : entities) set(key, value, entity); - } - - /** - * 移除标签 - * - * @param key 键 - * @param entity 实体 - */ - public Object remove(String key, Entity entity) { - if (contains(entity)) { - entityData.get(entity.getUniqueId()).remove(key); - if (entityData.get(entity.getUniqueId()).size() == 0) { - return entityData.remove(entity.getUniqueId()); - } - } - return null; - } - - /** - * 移除标签 - * - * @param key 键 - * @param entities 实体 - */ - public void remove(String key, Entity... entities) { - for (Entity entity : entities) remove(key, entity); - } - - /** - * 移除标签 - * - * @param key 键 - * @param entities 实体 - */ - public void remove(String key, List entities) { - for (Entity entity : entities) remove(key, entity); - } - - /** - * 检查数据 - * - * @param entity 实体 - * @return boolean - */ - public boolean contains(Entity entity) { - return entityData.containsKey(entity.getUniqueId()); - } - - /** - * 检查标签 - * - * @param key 键 - * @param entity 实体 - * @return boolean - */ - public boolean hasKey(String key, Entity entity) { + public void set(String key, Object value, Entity... entities) { + for (Entity entity : entities) set(key, value, entity); + } + + /** + * 设置标签 + * + * @param key 键 + * @param value 值 + */ + public void set(String key, Object value, List entities) { + for (Entity entity : entities) set(key, value, entity); + } + + /** + * 移除标签 + * + * @param key 键 + * @param entity 实体 + */ + public Object remove(String key, Entity entity) { + if (contains(entity)) { + entityData.get(entity.getUniqueId()).remove(key); + if (entityData.get(entity.getUniqueId()).size() == 0) { + return entityData.remove(entity.getUniqueId()); + } + } + return null; + } + + /** + * 移除标签 + * + * @param key 键 + * @param entities 实体 + */ + public void remove(String key, Entity... entities) { + for (Entity entity : entities) remove(key, entity); + } + + /** + * 移除标签 + * + * @param key 键 + * @param entities 实体 + */ + public void remove(String key, List entities) { + for (Entity entity : entities) remove(key, entity); + } + + /** + * 检查数据 + * + * @param entity 实体 + * @return boolean + */ + public boolean contains(Entity entity) { + return entityData.containsKey(entity.getUniqueId()); + } + + /** + * 检查标签 + * + * @param key 键 + * @param entity 实体 + * @return boolean + */ + public boolean hasKey(String key, Entity entity) { return contains(entity) && entityData.get(entity.getUniqueId()).containsKey(key); } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return Object - */ - public Object get(String key, Entity entity) { - if (contains(entity)) { - return entityData.get(entity.getUniqueId()).get(key); - } - return null; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 值 - * @return String - */ - public String getString(String key, Entity entity) { - Object object = get(key, entity); - if (object instanceof String) { - return (String) object; - } - return null; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 值 - * @return int - */ - public int getInteger(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (int) object; - } - return 0; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 值 - * @return long - */ - public long getLong(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (long) object; - } - return 0L; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return boolean - */ - public boolean getBoolean(String key, Entity entity) { + + /** + * 获取数据 + * + * @param key 键 + * @param entity 实体 + * @return Object + */ + public Object get(String key, Entity entity) { + if (contains(entity)) { + return entityData.get(entity.getUniqueId()).get(key); + } + return null; + } + + /** + * 获取数据 + * + * @param key 键 + * @param entity 值 + * @return String + */ + public String getString(String key, Entity entity) { + Object object = get(key, entity); + if (object instanceof String) { + return (String) object; + } + return null; + } + + /** + * 获取数据 + * + * @param key 键 + * @param entity 值 + * @return int + */ + public int getInteger(String key, Entity entity) { + Object object = get(key, entity); + if (object != null) { + return (int) object; + } + return 0; + } + + /** + * 获取数据 + * + * @param key 键 + * @param entity 值 + * @return long + */ + public long getLong(String key, Entity entity) { + Object object = get(key, entity); + if (object != null) { + return (long) object; + } + return 0L; + } + + /** + * 获取数据 + * + * @param key 键 + * @param entity 实体 + * @return boolean + */ + public boolean getBoolean(String key, Entity entity) { Object object = get(key, entity); return object != null && (boolean) object; } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return double - */ - public double getDouble(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (double) object; - } - return 0D; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return float - */ - public double getFloat(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (float) object; - } - return 0F; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return short - */ - public short getShort(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (short) object; - } - return (short) 0; - } - - /** - * 获取数据 - * - * @param key 键 - * @param entity 实体 - * @return byte - */ - public byte getByte(String key, Entity entity) { - Object object = get(key, entity); - if (object != null) { - return (byte) object; - } - return (byte) 0; - } + + /** + * 获取数据 + * + * @param key 键 + * @param entity 实体 + * @return double + */ + public double getDouble(String key, Entity entity) { + Object object = get(key, entity); + if (object != null) { + return (double) object; + } + return 0D; + } + + /** + * 获取数据 + * + * @param key 键 + * @param entity 实体 + * @return float + */ + public double getFloat(String key, Entity entity) { + Object object = get(key, entity); + if (object != null) { + return (float) object; + } + return 0F; + } + + /** + * 获取数据 + * + * @param key 键 + * @param entity 实体 + * @return short + */ + public short getShort(String key, Entity entity) { + Object object = get(key, entity); + if (object != null) { + return (short) object; + } + return (short) 0; + } + + /** + * 获取数据 + * + * @param key 键 + * @param entity 实体 + * @return byte + */ + public byte getByte(String key, Entity entity) { + Object object = get(key, entity); + if (object != null) { + return (byte) object; + } + return (byte) 0; + } } diff --git a/src/main/java/me/skymc/taboolib/entity/EntityUtils.java b/src/main/java/me/skymc/taboolib/entity/EntityUtils.java index 84b13bf..37d76dd 100644 --- a/src/main/java/me/skymc/taboolib/entity/EntityUtils.java +++ b/src/main/java/me/skymc/taboolib/entity/EntityUtils.java @@ -1,8 +1,10 @@ package me.skymc.taboolib.entity; -import java.lang.reflect.InvocationTargetException; -import java.util.UUID; - +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import me.skymc.taboolib.exception.PluginNotFoundException; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Entity; @@ -11,72 +13,69 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntitySpawnEvent; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; - -import lombok.Getter; -import me.skymc.taboolib.exception.PluginNotFoundException; +import java.lang.reflect.InvocationTargetException; +import java.util.UUID; public class EntityUtils implements Listener { - - @Getter - private static Entity lastSpawnedEntity = null; - - @EventHandler - public void spawn(EntitySpawnEvent e) { - lastSpawnedEntity = e.getEntity(); - } - - /** - * 根据 UUID 获取生物 - * - * @param u - * @return - */ - public static Entity getEntityWithUUID(UUID u) { - for (World w : Bukkit.getWorlds()) { - for (Entity e : w.getLivingEntities()) { - if (e.getUniqueId().equals(u)) { - return e; - } - } - } - return null; - } - - /** - * 根据 UUID 获取生物(单世界) - * - * @param u - * @param world - * @return - */ - public static Entity getEntityWithUUID_World(UUID u, World world) { - for (Entity e : world.getLivingEntities()) { - if (e.getUniqueId().equals(u)) { - return e; - } - } - return null; - } - - /** - * 设置生物发光(ProcotolLib) - * - * @param player - * @param entity - */ - public static void addGlow(Player player,Entity entity) { - if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) { - try { - throw new PluginNotFoundException("缺少前置插件 ProtocolLib"); - } - catch (Exception e) { - // - } - } + + private static Entity lastSpawnedEntity = null; + + public static Entity getLastSpawnedEntity() { + return lastSpawnedEntity; + } + + @EventHandler + public void spawn(EntitySpawnEvent e) { + lastSpawnedEntity = e.getEntity(); + } + + /** + * 根据 UUID 获取生物 + * + * @param u + * @return + */ + public static Entity getEntityWithUUID(UUID u) { + for (World w : Bukkit.getWorlds()) { + for (Entity e : w.getLivingEntities()) { + if (e.getUniqueId().equals(u)) { + return e; + } + } + } + return null; + } + + /** + * 根据 UUID 获取生物(单世界) + * + * @param u + * @param world + * @return + */ + public static Entity getEntityWithUUID_World(UUID u, World world) { + for (Entity e : world.getLivingEntities()) { + if (e.getUniqueId().equals(u)) { + return e; + } + } + return null; + } + + /** + * 设置生物发光(ProcotolLib) + * + * @param player + * @param entity + */ + public static void addGlow(Player player, Entity entity) { + if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) { + try { + throw new PluginNotFoundException("缺少前置插件 ProtocolLib"); + } catch (Exception e) { + // + } + } PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); packet.getIntegers().write(0, entity.getEntityId()); WrappedDataWatcher watcher = new WrappedDataWatcher(); @@ -85,26 +84,26 @@ public class EntityUtils implements Listener { watcher.setObject(0, serializer, (byte) (0x40)); packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); try { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); } catch (InvocationTargetException e) { e.printStackTrace(); } } - - /** - * 取消生物发光(ProcotolLib) - * - * @param player - * @param entity - */ - public static void delGlow(Player player,Entity entity) { - if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) { - try { - throw new PluginNotFoundException("缺少前置插件 ProtocolLib"); - } catch (Exception e) { - // - } - } + + /** + * 取消生物发光(ProcotolLib) + * + * @param player + * @param entity + */ + public static void delGlow(Player player, Entity entity) { + if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) { + try { + throw new PluginNotFoundException("缺少前置插件 ProtocolLib"); + } catch (Exception e) { + // + } + } PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); packet.getIntegers().write(0, entity.getEntityId()); WrappedDataWatcher watcher = new WrappedDataWatcher(); @@ -113,7 +112,7 @@ public class EntityUtils implements Listener { watcher.setObject(0, serializer, (byte) (0x0)); packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); try { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); } catch (InvocationTargetException e) { e.printStackTrace(); } diff --git a/src/main/java/me/skymc/taboolib/events/CustomBookOpenEvent.java b/src/main/java/me/skymc/taboolib/events/CustomBookOpenEvent.java index 1195671..08a04b3 100644 --- a/src/main/java/me/skymc/taboolib/events/CustomBookOpenEvent.java +++ b/src/main/java/me/skymc/taboolib/events/CustomBookOpenEvent.java @@ -6,51 +6,71 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; -import lombok.Getter; -import lombok.Setter; - /** * The event called when a book is opened trough this Util */ public class CustomBookOpenEvent extends Event implements Cancellable { - + private static final HandlerList handlers = new HandlerList(); - @Getter - @Setter private boolean cancelled; /** * The player */ - @Getter private final Player player; /** * The hand used to open the book (the previous item will be restored after the opening) */ - @Getter - @Setter private Hand hand; /** * The actual book to be opened */ - @Getter - @Setter private ItemStack book; + public Player getPlayer() { + return player; + } + + public Hand getHand() { + return hand; + } + + public ItemStack getBook() { + return book; + } + + public void setHand(Hand hand) { + this.hand = hand; + } + + public void setBook(ItemStack book) { + this.book = book; + } + public CustomBookOpenEvent(Player player, ItemStack book, boolean offHand) { this.player = player; this.book = book; this.hand = offHand ? Hand.OFF_HAND : Hand.MAIN_HAND; } + @Override + public boolean isCancelled() { + return cancelled; + } + @Override public HandlerList getHandlers() { return handlers; } + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + public static HandlerList getHandlerList() { return handlers; } diff --git a/src/main/java/me/skymc/taboolib/events/DefaultEvent2.java b/src/main/java/me/skymc/taboolib/events/DefaultEvent2.java index 1df26f6..def7099 100644 --- a/src/main/java/me/skymc/taboolib/events/DefaultEvent2.java +++ b/src/main/java/me/skymc/taboolib/events/DefaultEvent2.java @@ -5,49 +5,47 @@ import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; -public class DefaultEvent2 extends PlayerEvent -{ +public class DefaultEvent2 extends PlayerEvent { + private static final HandlerList handlers; - + static { handlers = new HandlerList(); } - + private DefaultEvent2(final Player who) { super(who); } - + public static HandlerList getHandlerList() { return DefaultEvent2.handlers; } - + @Override - public HandlerList getHandlers() { + public HandlerList getHandlers() { return DefaultEvent2.handlers; } - - public static class Pre extends DefaultEvent2 implements Cancellable - { + + public static class Pre extends DefaultEvent2 implements Cancellable { private boolean cancelled; - + public Pre(Player who) { super(who); this.cancelled = false; } - + @Override - public boolean isCancelled() { + public boolean isCancelled() { return this.cancelled; } - + @Override - public void setCancelled(final boolean cancelled) { + public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } } - - public static class Post extends DefaultEvent2 - { + + public static class Post extends DefaultEvent2 { public Post(Player who) { super(who); } diff --git a/src/main/java/me/skymc/taboolib/events/PlayerJumpEvent.java b/src/main/java/me/skymc/taboolib/events/PlayerJumpEvent.java index 39d4c38..12eccf8 100644 --- a/src/main/java/me/skymc/taboolib/events/PlayerJumpEvent.java +++ b/src/main/java/me/skymc/taboolib/events/PlayerJumpEvent.java @@ -5,45 +5,37 @@ import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -public class PlayerJumpEvent - extends Event - implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); - private boolean isCancelled; - private Player player; - - public PlayerJumpEvent(boolean b, Player player) - { - this.isCancelled = false; - this.player = player; - } - - public Player getPlayer() - { - return this.player; - } - - @Override -public boolean isCancelled() - { - return this.isCancelled; - } - - @Override -public void setCancelled(boolean e) - { - this.isCancelled = e; - } - - @Override -public HandlerList getHandlers() - { - return handlers; - } - - public static HandlerList getHandlerList() - { - return handlers; - } +public class PlayerJumpEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private boolean isCancelled; + private Player player; + + public PlayerJumpEvent(boolean b, Player player) { + this.isCancelled = false; + this.player = player; + } + + public Player getPlayer() { + return this.player; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean e) { + this.isCancelled = e; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } } diff --git a/src/main/java/me/skymc/taboolib/events/PlayerLoadedEvent.java b/src/main/java/me/skymc/taboolib/events/PlayerLoadedEvent.java index 5b66380..75b022f 100644 --- a/src/main/java/me/skymc/taboolib/events/PlayerLoadedEvent.java +++ b/src/main/java/me/skymc/taboolib/events/PlayerLoadedEvent.java @@ -5,25 +5,25 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public class PlayerLoadedEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - private Player player; - - public PlayerLoadedEvent(Player player) { - super(true); - this.player = player; - } - - public Player getPlayer() { - return this.player; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } + + private static final HandlerList handlers = new HandlerList(); + private Player player; + + public PlayerLoadedEvent(Player player) { + super(true); + this.player = player; + } + + public Player getPlayer() { + return this.player; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } } diff --git a/src/main/java/me/skymc/taboolib/fileutils/EncodeUtils.java b/src/main/java/me/skymc/taboolib/fileutils/EncodeUtils.java index 13e1672..ce1bbd9 100644 --- a/src/main/java/me/skymc/taboolib/fileutils/EncodeUtils.java +++ b/src/main/java/me/skymc/taboolib/fileutils/EncodeUtils.java @@ -1,123 +1,116 @@ package me.skymc.taboolib.fileutils; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; +import java.io.*; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; public class EncodeUtils { - /** - * 把指定文件或目录转换成指定的编码 - * - * @param fileName 要转换的文件 - * @param fromCharsetName 源文件的编码 - * @param toCharsetName 要转换的编码 - * @throws Exception - */ - public static void convert(String fileName, String fromCharsetName, String toCharsetName) throws Exception { - convert(new File(fileName), fromCharsetName, toCharsetName, null); - } + /** + * 把指定文件或目录转换成指定的编码 + * + * @param fileName 要转换的文件 + * @param fromCharsetName 源文件的编码 + * @param toCharsetName 要转换的编码 + * @throws Exception + */ + public static void convert(String fileName, String fromCharsetName, String toCharsetName) throws Exception { + convert(new File(fileName), fromCharsetName, toCharsetName, null); + } - /** - * 把指定文件或目录转换成指定的编码 - * - * @param file 要转换的文件或目录 - * @param fromCharsetName 源文件的编码 - * @param toCharsetName 要转换的编码 - * @throws Exception - */ - public static void convert(File file, String fromCharsetName, String toCharsetName) throws Exception { - convert(file, fromCharsetName, toCharsetName, null); - } + /** + * 把指定文件或目录转换成指定的编码 + * + * @param file 要转换的文件或目录 + * @param fromCharsetName 源文件的编码 + * @param toCharsetName 要转换的编码 + * @throws Exception + */ + public static void convert(File file, String fromCharsetName, String toCharsetName) throws Exception { + convert(file, fromCharsetName, toCharsetName, null); + } - /** - * 把指定文件或目录转换成指定的编码 - * - * @param fromCharsetName 源文件的编码 - * @param toCharsetName 转换的编码 - * @param filter 文件名过滤器 - * @throws Exception - */ - public static void convert(String fileName, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception { - convert(new File(fileName), fromCharsetName, toCharsetName, filter); - } + /** + * 把指定文件或目录转换成指定的编码 + * + * @param fromCharsetName 源文件的编码 + * @param toCharsetName 转换的编码 + * @param filter 文件名过滤器 + * @throws Exception + */ + public static void convert(String fileName, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception { + convert(new File(fileName), fromCharsetName, toCharsetName, filter); + } - /** - * 把指定文件或目录转换成指定的编码 - * - * @param file 要转换的文件或目录 - * @param fromCharsetName 源文件的编码 - * @param toCharsetName 要转换的编码 - * @param filter 文件名过滤器 - * @throws Exception - */ - public static void convert(File file, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception { - if (file.isDirectory()) { - File[] fileList = null; - if (filter == null) { - fileList = file.listFiles(); - } else { - fileList = file.listFiles(filter); - } - for (File f : fileList) { - convert(f, fromCharsetName, toCharsetName, filter); - } - } else { - if (filter == null - || filter.accept(file.getParentFile(), file.getName())) { - String fileContent = getFileContentFromCharset(file, - fromCharsetName); - saveFile2Charset(file, toCharsetName, fileContent); - } - } - } + /** + * 把指定文件或目录转换成指定的编码 + * + * @param file 要转换的文件或目录 + * @param fromCharsetName 源文件的编码 + * @param toCharsetName 要转换的编码 + * @param filter 文件名过滤器 + * @throws Exception + */ + public static void convert(File file, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception { + if (file.isDirectory()) { + File[] fileList = null; + if (filter == null) { + fileList = file.listFiles(); + } else { + fileList = file.listFiles(filter); + } + for (File f : fileList) { + convert(f, fromCharsetName, toCharsetName, filter); + } + } else { + if (filter == null + || filter.accept(file.getParentFile(), file.getName())) { + String fileContent = getFileContentFromCharset(file, + fromCharsetName); + saveFile2Charset(file, toCharsetName, fileContent); + } + } + } - /** - * 以指定编码方式读取文件,返回文件内容 - * - * @param file 要转换的文件 - * @param fromCharsetName 源文件的编码 - * @return - * @throws Exception - */ - public static String getFileContentFromCharset(File file, String fromCharsetName) throws Exception { - if (!Charset.isSupported(fromCharsetName)) { - throw new UnsupportedCharsetException(fromCharsetName); - } - InputStream inputStream = new FileInputStream(file); - InputStreamReader reader = new InputStreamReader(inputStream, - fromCharsetName); - char[] chs = new char[(int) file.length()]; - reader.read(chs); - String str = new String(chs).trim(); - reader.close(); - return str; - } + /** + * 以指定编码方式读取文件,返回文件内容 + * + * @param file 要转换的文件 + * @param fromCharsetName 源文件的编码 + * @return + * @throws Exception + */ + public static String getFileContentFromCharset(File file, String fromCharsetName) throws Exception { + if (!Charset.isSupported(fromCharsetName)) { + throw new UnsupportedCharsetException(fromCharsetName); + } + InputStream inputStream = new FileInputStream(file); + InputStreamReader reader = new InputStreamReader(inputStream, + fromCharsetName); + char[] chs = new char[(int) file.length()]; + reader.read(chs); + String str = new String(chs).trim(); + reader.close(); + return str; + } - /** - * 以指定编码方式写文本文件,存在会覆盖 - * - * @param file 要写入的文件 - * @param toCharsetName 要转换的编码 - * @param content 文件内容 - * @throws Exception - */ - public static void saveFile2Charset(File file, String toCharsetName, String content) throws Exception { - if (!Charset.isSupported(toCharsetName)) { - throw new UnsupportedCharsetException(toCharsetName); - } - OutputStream outputStream = new FileOutputStream(file); - OutputStreamWriter outWrite = new OutputStreamWriter(outputStream, toCharsetName); - outWrite.write(content); - outWrite.close(); - - System.out.println("[Encodeing...] 更改文件: " + file.getPath()); - } + /** + * 以指定编码方式写文本文件,存在会覆盖 + * + * @param file 要写入的文件 + * @param toCharsetName 要转换的编码 + * @param content 文件内容 + * @throws Exception + */ + public static void saveFile2Charset(File file, String toCharsetName, String content) throws Exception { + if (!Charset.isSupported(toCharsetName)) { + throw new UnsupportedCharsetException(toCharsetName); + } + OutputStream outputStream = new FileOutputStream(file); + OutputStreamWriter outWrite = new OutputStreamWriter(outputStream, toCharsetName); + outWrite.write(content); + outWrite.close(); + + System.out.println("[Encodeing...] 更改文件: " + file.getPath()); + } } diff --git a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java index 8c45a4f..86013ef 100644 --- a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java +++ b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java @@ -10,304 +10,301 @@ import java.net.URLConnection; import java.nio.channels.FileChannel; public class FileUtils { - - public static String ip() { - try { - InputStream ins = null; - URL url = new URL("http://1212.ip138.com/ic.asp"); - URLConnection con = url.openConnection(); - ins = con.getInputStream(); + + public static String ip() { + try { + InputStream ins = null; + URL url = new URL("http://1212.ip138.com/ic.asp"); + URLConnection con = url.openConnection(); + ins = con.getInputStream(); InputStreamReader isReader = new InputStreamReader(ins, "GB2312"); BufferedReader bReader = new BufferedReader(isReader); StringBuilder webContent = new StringBuilder(); - String str = null; - while ((str = bReader.readLine()) != null) { - webContent.append(str); - } - int start = webContent.indexOf("[") + 1; - int end = webContent.indexOf("]"); + String str = null; + while ((str = bReader.readLine()) != null) { + webContent.append(str); + } + int start = webContent.indexOf("[") + 1; + int end = webContent.indexOf("]"); ins.close(); - return webContent.substring(start, end); - } - catch (Exception e) { - // TODO: handle exception - } + return webContent.substring(start, end); + } catch (Exception e) { + // TODO: handle exception + } return "[IP ERROR]"; - } - - /** - * 创建并获取文件 - * - * @param filePath - * @return - */ - public static File file(String filePath) { - File file = new File(filePath); - if (!file.exists()) { - try { - file.createNewFile(); - } catch (IOException e) { - // TODO Auto-generated catch block - } - } - return file; - } - - /** - * 创建并获取文件 - * - * @param Path - * @param filePath - * @return - */ - public static File file(File Path, String filePath) { - File file = new File(Path, filePath); - if (!file.exists()) { - try { - file.createNewFile(); - } catch (IOException e) { - // TODO Auto-generated catch block - } - } - return file; - } - - /** - * 删除文件夹 - * - * @param file - */ - public void deleteAllFile(File file) { - if (!file.exists()) { - return; - } - if (file.isFile()) { - file.delete(); - return; + } + + /** + * 创建并获取文件 + * + * @param filePath + * @return + */ + public static File file(String filePath) { + File file = new File(filePath); + if (!file.exists()) { + try { + file.createNewFile(); + } catch (IOException e) { + // TODO Auto-generated catch block + } + } + return file; + } + + /** + * 创建并获取文件 + * + * @param Path + * @param filePath + * @return + */ + public static File file(File Path, String filePath) { + File file = new File(Path, filePath); + if (!file.exists()) { + try { + file.createNewFile(); + } catch (IOException e) { + // TODO Auto-generated catch block + } + } + return file; + } + + /** + * 删除文件夹 + * + * @param file + */ + public void deleteAllFile(File file) { + if (!file.exists()) { + return; + } + if (file.isFile()) { + file.delete(); + return; } File[] files = file.listFiles(); for (File file1 : files) { deleteAllFile(file1); } - file.delete(); - } - - /** - * 复制文件夹 - * + file.delete(); + } + + /** + * 复制文件夹 + * * @param file1 文件1 * @param file2 文件2 - * @throws Exception - */ + * @throws Exception + */ public void copyAllFile(String file1, String file2) throws Exception { File _file1 = new File(file1); File _file2 = new File(file2); if (!_file2.exists()) { - if (!_file1.isDirectory()) { - _file2.createNewFile(); - } else { - _file2.mkdirs(); - } + if (!_file1.isDirectory()) { + _file2.createNewFile(); + } else { + _file2.mkdirs(); + } } if (_file1.isDirectory()) { - for (File file : _file1.listFiles()) { - if (file.isDirectory()) { - copyAllFile(file.getAbsolutePath(), file2 + "/" + file.getName()); - } else { - fileChannelCopy(file, new File(file2 + "/" + file.getName())); - } - } + for (File file : _file1.listFiles()) { + if (file.isDirectory()) { + copyAllFile(file.getAbsolutePath(), file2 + "/" + file.getName()); + } else { + fileChannelCopy(file, new File(file2 + "/" + file.getName())); + } + } } else { - fileChannelCopy(_file1, _file2); + fileChannelCopy(_file1, _file2); } } - + /** * 复制文件(通道) - * + * * @param file1 文件1 * @param file2 文件2 */ - public void fileChannelCopy(File file1, File file2) { - FileInputStream fileIn = null; - FileOutputStream fileOut = null; - FileChannel channelIn = null; - FileChannel channelOut = null; - try { - fileIn = new FileInputStream(file1); - fileOut = new FileOutputStream(file2); + public void fileChannelCopy(File file1, File file2) { + FileInputStream fileIn = null; + FileOutputStream fileOut = null; + FileChannel channelIn = null; + FileChannel channelOut = null; + try { + fileIn = new FileInputStream(file1); + fileOut = new FileOutputStream(file2); channelIn = fileIn.getChannel(); channelOut = fileOut.getChannel(); channelIn.transferTo(0, channelIn.size(), channelOut); - } catch (Exception e) { + } catch (Exception e) { // - } finally { - try { - fileIn.close(); - channelIn.close(); - fileOut.close(); - channelOut.close(); - } catch (Exception e) { + } finally { + try { + fileIn.close(); + channelIn.close(); + fileOut.close(); + channelOut.close(); + } catch (Exception e) { // - } - } - } - - /** - * 通过输入流读取文本 - * - * @param in - * @param size - * @param encode - * @return - */ - public static String getStringFromInputStream(InputStream in, int size, String encode) { - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - byte[] b = new byte[size]; - int i = 0; - - while ((i = in.read(b)) > 0) { - bos.write(b, 0, i); - } - - bos.close(); - return new String(bos.toByteArray(), encode); - } catch (IOException e) { - MsgUtils.warn("输入流读取出错: &4" + e.getMessage()); - } - return null; - } - - /** - * 通过文件读取文本 - * - * @param file - * @param size - * @param encode - * @return - */ - public static String getStringFromFile(File file, int size, String encode) { - try { - FileInputStream fin = new FileInputStream(file); - BufferedInputStream bin = new BufferedInputStream(fin); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - byte[] b = new byte[size]; - int i = 0; - - while ((i = bin.read(b)) > 0) { - bos.write(b, 0, i); - } - - bos.close(); - bin.close(); - fin.close(); - return new String(bos.toByteArray(), encode); - } catch (IOException e) { - MsgUtils.warn("文件读取出错: &4" + e.getMessage()); - } - return null; - } - - /** - * 通过 URL 读取文本 - * - * @param url - * @param size - * @return - */ - public static String getStringFromURL(String url, int size) { - try { - URLConnection conn = new URL(url).openConnection(); - BufferedInputStream bin = new BufferedInputStream(conn.getInputStream()); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - byte[] b = new byte[size]; - int i = 0; - - while ((i = bin.read(b)) > 0) { - bos.write(b, 0, i); - } - - bos.close(); - bin.close(); - return new String(bos.toByteArray(), conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding()); - } catch (IOException e) { - MsgUtils.warn("网络访问出错: &4" + e.getMessage()); - } - return null; - } + } + } + } + + /** + * 通过输入流读取文本 + * + * @param in + * @param size + * @param encode + * @return + */ + public static String getStringFromInputStream(InputStream in, int size, String encode) { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + byte[] b = new byte[size]; + int i = 0; + + while ((i = in.read(b)) > 0) { + bos.write(b, 0, i); + } + + bos.close(); + return new String(bos.toByteArray(), encode); + } catch (IOException e) { + MsgUtils.warn("输入流读取出错: &4" + e.getMessage()); + } + return null; + } + + /** + * 通过文件读取文本 + * + * @param file + * @param size + * @param encode + * @return + */ + public static String getStringFromFile(File file, int size, String encode) { + try { + FileInputStream fin = new FileInputStream(file); + BufferedInputStream bin = new BufferedInputStream(fin); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + byte[] b = new byte[size]; + int i = 0; + + while ((i = bin.read(b)) > 0) { + bos.write(b, 0, i); + } + + bos.close(); + bin.close(); + fin.close(); + return new String(bos.toByteArray(), encode); + } catch (IOException e) { + MsgUtils.warn("文件读取出错: &4" + e.getMessage()); + } + return null; + } + + /** + * 通过 URL 读取文本 + * + * @param url + * @param size + * @return + */ + public static String getStringFromURL(String url, int size) { + try { + URLConnection conn = new URL(url).openConnection(); + BufferedInputStream bin = new BufferedInputStream(conn.getInputStream()); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + byte[] b = new byte[size]; + int i = 0; + + while ((i = bin.read(b)) > 0) { + bos.write(b, 0, i); + } + + bos.close(); + bin.close(); + return new String(bos.toByteArray(), conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding()); + } catch (IOException e) { + MsgUtils.warn("网络访问出错: &4" + e.getMessage()); + } + return null; + } + + public static String getStringFromURL(String url, String def) { + String s = getStringFromURL(url, 1024); + return s == null ? def : s; + } - public static String getStringFromURL(String url, String def) { - String s = getStringFromURL(url, 1024); - return s == null ? def : s; - } - /** * 下载文件 - * + * * @param urlStr * @param filename * @param saveDir */ public static void download(String urlStr, String filename, File saveDir) { - try { - URL url = new URL(urlStr); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - - // 超时时间 - conn.setConnectTimeout(5 * 1000); - // 防止屏蔽程序抓取而返回 403 错误 - conn.setRequestProperty("User-Agent", "Mozilla/31.0 (compatible; MSIE 10.0; Windows NT; DigExt)"); - - // 得到输入流 - InputStream inputStream = conn.getInputStream(); - // 获取数组 - byte[] data = read(inputStream); - - // 创建文件夹 - if (!saveDir.exists()) { - saveDir.mkdirs(); - } - - // 保存文件 - File file = new File(saveDir, filename); - FileOutputStream fos = new FileOutputStream(file); - - // 写入文件 - fos.write(data); - - // 结束 - fos.close(); - inputStream.close(); - } - catch (Exception e) { - e.printStackTrace(); - } - } - - public static byte[] read(InputStream in) { - byte[] buffer = new byte[1024]; - int len = 0; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - while((len = in.read(buffer)) != -1) { - bos.write(buffer, 0, len); - } - } - catch (Exception ignored) { - } - return bos.toByteArray(); - } - - public static void close(Closeable closeable) { - try { - if (closeable != null) { - closeable.close(); - } - } catch (Exception ignored) { - } - } + try { + URL url = new URL(urlStr); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + + // 超时时间 + conn.setConnectTimeout(5 * 1000); + // 防止屏蔽程序抓取而返回 403 错误 + conn.setRequestProperty("User-Agent", "Mozilla/31.0 (compatible; MSIE 10.0; Windows NT; DigExt)"); + + // 得到输入流 + InputStream inputStream = conn.getInputStream(); + // 获取数组 + byte[] data = read(inputStream); + + // 创建文件夹 + if (!saveDir.exists()) { + saveDir.mkdirs(); + } + + // 保存文件 + File file = new File(saveDir, filename); + FileOutputStream fos = new FileOutputStream(file); + + // 写入文件 + fos.write(data); + + // 结束 + fos.close(); + inputStream.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static byte[] read(InputStream in) { + byte[] buffer = new byte[1024]; + int len = 0; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + while ((len = in.read(buffer)) != -1) { + bos.write(buffer, 0, len); + } + } catch (Exception ignored) { + } + return bos.toByteArray(); + } + + public static void close(Closeable closeable) { + try { + if (closeable != null) { + closeable.close(); + } + } catch (Exception ignored) { + } + } } diff --git a/src/main/java/me/skymc/taboolib/fileutils/LogUtils.java b/src/main/java/me/skymc/taboolib/fileutils/LogUtils.java index 3915139..08517d1 100644 --- a/src/main/java/me/skymc/taboolib/fileutils/LogUtils.java +++ b/src/main/java/me/skymc/taboolib/fileutils/LogUtils.java @@ -1,58 +1,47 @@ package me.skymc.taboolib.fileutils; +import me.skymc.taboolib.Main; +import me.skymc.taboolib.other.DateUtils; +import org.bukkit.plugin.Plugin; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; -import org.bukkit.plugin.Plugin; - -import me.skymc.taboolib.Main; -import me.skymc.taboolib.other.DateUtils; - @Deprecated public class LogUtils { - - public static void Log(String s, String s2) - { - try - { - File file = new File(Main.getInst().getDataFolder(), s2+".txt"); - if(!file.exists()) - { + + public static void Log(String s, String s2) { + try { + File file = new File(Main.getInst().getDataFolder(), s2 + ".txt"); + if (!file.exists()) { file.createNewFile(); } - + FileWriter fileWritter = new FileWriter(file, true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(s); bufferWritter.newLine(); bufferWritter.close(); - } - catch (Exception e) - { - Main.getInst().getLogger().warning(s2+":"+s); + } catch (Exception e) { + Main.getInst().getLogger().warning(s2 + ":" + s); } } - - public static void newLog(Plugin main, String s, String s2) - { - try - { - File file = new File(main.getDataFolder(), s2+".txt"); - if(!file.exists()) - { + + public static void newLog(Plugin main, String s, String s2) { + try { + File file = new File(main.getDataFolder(), s2 + ".txt"); + if (!file.exists()) { file.createNewFile(); } - + FileWriter fileWritter = new FileWriter(file, true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); - bufferWritter.write("["+DateUtils.CH_ALL.format(System.currentTimeMillis())+"]"+s); + bufferWritter.write("[" + DateUtils.CH_ALL.format(System.currentTimeMillis()) + "]" + s); bufferWritter.newLine(); bufferWritter.close(); - } - catch (Exception e) - { - Main.getInst().getLogger().warning(s2+":"+s); + } catch (Exception e) { + Main.getInst().getLogger().warning(s2 + ":" + s); } } diff --git a/src/main/java/me/skymc/taboolib/inventory/DropUtils.java b/src/main/java/me/skymc/taboolib/inventory/DropUtils.java index 3392a17..538eb06 100644 --- a/src/main/java/me/skymc/taboolib/inventory/DropUtils.java +++ b/src/main/java/me/skymc/taboolib/inventory/DropUtils.java @@ -1,48 +1,46 @@ package me.skymc.taboolib.inventory; +import me.skymc.taboolib.other.NumberUtils; import org.bukkit.Location; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; -import me.skymc.taboolib.other.NumberUtils; - public class DropUtils { - - public static Item drop(Player player, ItemStack itemStack, double bulletSpread, double radius) { - Location location = player.getLocation(); - location.setY(location.getY() + 1.5); - - Item item = player.getWorld().dropItem(location, itemStack); - + + public static Item drop(Player player, ItemStack itemStack, double bulletSpread, double radius) { + Location location = player.getLocation(); + location.setY(location.getY() + 1.5); + + Item item = player.getWorld().dropItem(location, itemStack); + double yaw = Math.toRadians(-player.getLocation().getYaw() - 90.0F); double pitch = Math.toRadians(-player.getLocation().getPitch()); - + double x = 0; double y = 0; double z = 0; - + if (bulletSpread > 0) { - double[] spread = { 1.0D, 1.0D, 1.0D }; + double[] spread = {1.0D, 1.0D, 1.0D}; for (int t = 0; t < 3; t++) { - spread[t] = ((NumberUtils.getRand().nextDouble() - NumberUtils.getRand().nextDouble()) * bulletSpread * 0.1D); + spread[t] = ((NumberUtils.getRand().nextDouble() - NumberUtils.getRand().nextDouble()) * bulletSpread * 0.1D); } - + x = Math.cos(pitch) * Math.cos(yaw) + spread[0]; y = Math.sin(pitch) + spread[1]; z = -Math.sin(yaw) * Math.cos(pitch) + spread[2]; - } - else { - x = Math.cos(pitch) * Math.cos(yaw); + } else { + x = Math.cos(pitch) * Math.cos(yaw); y = Math.sin(pitch); z = -Math.sin(yaw) * Math.cos(pitch); } Vector dirVel = new Vector(x, y, z); dirVel.normalize().multiply(radius); - + item.setVelocity(dirVel); return item; - } + } } diff --git a/src/main/java/me/skymc/taboolib/inventory/InventoryUtil.java b/src/main/java/me/skymc/taboolib/inventory/InventoryUtil.java index 6bea382..7cc3c40 100644 --- a/src/main/java/me/skymc/taboolib/inventory/InventoryUtil.java +++ b/src/main/java/me/skymc/taboolib/inventory/InventoryUtil.java @@ -1,119 +1,117 @@ package me.skymc.taboolib.inventory; -import java.util.Arrays; -import java.util.LinkedList; - import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import java.util.Arrays; +import java.util.LinkedList; + public class InventoryUtil { - - public final static LinkedList SLOT_OF_CENTENTS = new LinkedList<>(Arrays.asList( - 10, 11, 12, 13, 14, 15, 16, - 19, 20, 21, 22, 23, 24, 25, - 28, 29, 30, 31, 32, 33, 34, - 37, 38, 39, 40, 41, 42, 43)); - - @Deprecated - public static boolean isEmpey(Player p) { + + public final static LinkedList SLOT_OF_CENTENTS = new LinkedList<>(Arrays.asList( + 10, 11, 12, 13, 14, 15, 16, + 19, 20, 21, 22, 23, 24, 25, + 28, 29, 30, 31, 32, 33, 34, + 37, 38, 39, 40, 41, 42, 43)); + + @Deprecated + public static boolean isEmpey(Player p) { return isEmpty(p, 0); } - - /** - * 检查背包是否有空位 - * - * @param p 玩家 - * @param i 起始位置 - */ - public static boolean isEmpty(Player p, int i) { + + /** + * 检查背包是否有空位 + * + * @param p 玩家 + * @param i 起始位置 + */ + public static boolean isEmpty(Player p, int i) { while (i < 35) { if (p.getInventory().getItem(i) == null) { - return true; + return true; } i++; } return false; } - - /** - * 检测玩家是否有指定物品 - * - * @param player 玩家 - * @param item 物品 - * @param amount 数量 - * @param remove 是否删除 - */ - public static boolean hasItem(Player player, ItemStack item, int amount, boolean remove) { - int hasAmount = 0; - for (ItemStack _item : player.getInventory()) { - if (item.isSimilar(_item)) { - hasAmount += _item.getAmount(); - } - } - if (hasAmount < amount) { - return false; - } - int requireAmount = amount; - for (int i = 0; i < player.getInventory().getSize() && remove; i++) { - ItemStack _item = player.getInventory().getItem(i); - if (_item != null && _item.isSimilar(item)) { - if (_item.getAmount() < requireAmount) { - player.getInventory().setItem(i, null); - requireAmount -= _item.getAmount(); + + /** + * 检测玩家是否有指定物品 + * + * @param player 玩家 + * @param item 物品 + * @param amount 数量 + * @param remove 是否删除 + */ + public static boolean hasItem(Player player, ItemStack item, int amount, boolean remove) { + int hasAmount = 0; + for (ItemStack _item : player.getInventory()) { + if (item.isSimilar(_item)) { + hasAmount += _item.getAmount(); + } + } + if (hasAmount < amount) { + return false; + } + int requireAmount = amount; + for (int i = 0; i < player.getInventory().getSize() && remove; i++) { + ItemStack _item = player.getInventory().getItem(i); + if (_item != null && _item.isSimilar(item)) { + if (_item.getAmount() < requireAmount) { + player.getInventory().setItem(i, null); + requireAmount -= _item.getAmount(); } else if (_item.getAmount() == requireAmount) { - player.getInventory().setItem(i, null); - return true; + player.getInventory().setItem(i, null); + return true; } else { - _item.setAmount(_item.getAmount() - requireAmount); - return true; - } - } - } - return true; - } - - @Deprecated - public static boolean hasItem(Inventory targetInventory, ItemStack targetItem, Integer amount) { - int inventoryAmount = 0; - for (ItemStack item : targetInventory) { - if (item != null) { - if (item.isSimilar(targetItem)) { - inventoryAmount += item.getAmount(); - } - } - } + _item.setAmount(_item.getAmount() - requireAmount); + return true; + } + } + } + return true; + } + + @Deprecated + public static boolean hasItem(Inventory targetInventory, ItemStack targetItem, Integer amount) { + int inventoryAmount = 0; + for (ItemStack item : targetInventory) { + if (item != null) { + if (item.isSimilar(targetItem)) { + inventoryAmount += item.getAmount(); + } + } + } return inventoryAmount >= amount; } - - @Deprecated - public static boolean takeItem2(Inventory inv, ItemStack takeitem, Integer amount) { - for (int i = 0; i < inv.getSize(); ++i) { - if (amount <= 0) { - return true; - } - - ItemStack item = inv.getItem(i); - if (item == null) { - continue; - } - if (!item.isSimilar(takeitem)) { - continue; - } - if (item.getAmount() >= amount) { - if (item.getAmount() - amount == 0) { - inv.setItem(i, null); - } - else { - item.setAmount(item.getAmount() - amount); - } - return true; - } - else { - amount -= item.getAmount(); - inv.setItem(i, null); - } - } - return false; - } + + @Deprecated + public static boolean takeItem2(Inventory inv, ItemStack takeitem, Integer amount) { + for (int i = 0; i < inv.getSize(); ++i) { + if (amount <= 0) { + return true; + } + + ItemStack item = inv.getItem(i); + if (item == null) { + continue; + } + if (!item.isSimilar(takeitem)) { + continue; + } + if (item.getAmount() >= amount) { + if (item.getAmount() - amount == 0) { + inv.setItem(i, null); + } else { + item.setAmount(item.getAmount() - amount); + } + return true; + } else { + amount -= item.getAmount(); + inv.setItem(i, null); + } + } + return false; + } } diff --git a/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java b/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java index 4f85c9d..997be6c 100644 --- a/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java +++ b/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java @@ -1,10 +1,16 @@ package me.skymc.taboolib.inventory; -import java.io.File; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; - +import me.clip.placeholderapi.PlaceholderAPI; +import me.skymc.taboolib.Main; +import me.skymc.taboolib.TabooLib; +import me.skymc.taboolib.fileutils.ConfigUtils; +import me.skymc.taboolib.itemnbtapi.NBTItem; +import me.skymc.taboolib.itemnbtapi.NBTList; +import me.skymc.taboolib.itemnbtapi.NBTListCompound; +import me.skymc.taboolib.itemnbtapi.NBTType; +import me.skymc.taboolib.message.MsgUtils; +import me.skymc.taboolib.other.NumberUtils; +import me.skymc.taboolib.string.Language; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; @@ -21,235 +27,237 @@ import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import lombok.Getter; -import me.clip.placeholderapi.PlaceholderAPI; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.fileutils.ConfigUtils; -import me.skymc.taboolib.itemnbtapi.NBTItem; -import me.skymc.taboolib.itemnbtapi.NBTList; -import me.skymc.taboolib.itemnbtapi.NBTListCompound; -import me.skymc.taboolib.itemnbtapi.NBTType; -import me.skymc.taboolib.message.MsgUtils; -import me.skymc.taboolib.other.NumberUtils; -import me.skymc.taboolib.string.Language; +import java.io.File; +import java.util.*; +import java.util.stream.IntStream; public class ItemUtils { - - @Getter - private static FileConfiguration itemdir = null; - - @Getter - private static FileConfiguration itemCache = null; - - @Getter - private static File finalItemsFolder; - - @Getter - private static LinkedHashMap itemlib = new LinkedHashMap<>(); - - @Getter - private static LinkedHashMap itemCaches = new LinkedHashMap<>(); - - @Getter - private static LinkedHashMap itemCachesFinal = new LinkedHashMap<>(); - - /** - * 获取物品缓存 - * 检测顺序: - * 1. 固定物品库 - * 2. 动态物品库 - * - * @param name 物品名称 - * @return - */ - public static ItemStack getCacheItem(String name) { - // 检测固定物品库是否存在该物品 - if (itemCachesFinal.containsKey(name)) { - return itemCachesFinal.get(name); - } - // 返回动态物品库 - return itemCaches.get(name); - } - - public static boolean isExists(String name) { - return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name); - } - - public static void LoadLib() { - try { - reloadItemName(); - reloadItemCache(); - itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR"))); - } catch (Exception e) { - MsgUtils.warn("物品库载入失败: &4" + e.getMessage()); - } - } - - public static void loadItemsFile(File file, boolean finalFile) { - FileConfiguration conf = ConfigUtils.load(Main.getInst(), file); - for (String name : conf.getConfigurationSection("").getKeys(false)) { - if (isExists(name)) { - MsgUtils.warn("无法载入载入物品 &4" + name + "&c, 因为它已经存在了"); - } else if (finalFile) { - itemCachesFinal.put(name, loadItem(conf, name)); - } else { - itemCaches.put(name, loadItem(conf, name)); - } - } - } - - public static void reloadItemCache() { - itemCaches.clear(); - itemCachesFinal.clear(); - loadItemsFile(getItemCacheFile(), false); - // 创建固定物品库 - finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems"); - if (!finalItemsFolder.exists()) { - finalItemsFolder.mkdir(); - } - // 检查固定物品库中的物品 - for (File file : finalItemsFolder.listFiles()) { - loadItemsFile(file, true); - } - MsgUtils.send("载入 " + (itemCaches.size() + itemCachesFinal.size()) + " 项缓存物品"); - } - - public static void reloadItemName() { - FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration(); - itemlib.clear(); - for (String a : conf.getConfigurationSection("").getKeys(false)) { - itemlib.put(a, conf.getString(a)); - } - MsgUtils.send("载入 " + itemlib.size() + " 项物品名称"); - } - - public static File getItemCacheFile() { - File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml"); - if (!itemCacheFile.exists()) { - Main.getInst().saveResource("items.yml", true); - } - return itemCacheFile; - } - - public static String getCustomName(ItemStack item) { - if (item == null || item.getType().equals(Material.AIR)) { - return "空"; - } - int data = item.getType().getMaxDurability() == 0 ? item.getDurability() : 0; - return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : itemlib.get(item.getType() + ":" + data) == null ? item.getType().toString() : itemlib.get(item.getType() + ":" + data); - } - - public static ItemStack getItemFromDir(String name) { - if (itemdir != null) { - return itemdir.getItemStack("item." + name); - } - return null; - } - - @SuppressWarnings("deprecation") + + private static FileConfiguration itemdir = null; + + private static FileConfiguration itemCache = null; + + private static File finalItemsFolder; + + private static LinkedHashMap itemlib = new LinkedHashMap<>(); + + private static LinkedHashMap itemCaches = new LinkedHashMap<>(); + + private static LinkedHashMap itemCachesFinal = new LinkedHashMap<>(); + + public static FileConfiguration getItemdir() { + return itemdir; + } + + public static FileConfiguration getItemCache() { + return itemCache; + } + + public static File getFinalItemsFolder() { + return finalItemsFolder; + } + + public static LinkedHashMap getItemlib() { + return itemlib; + } + + public static LinkedHashMap getItemCaches() { + return itemCaches; + } + + public static LinkedHashMap getItemCachesFinal() { + return itemCachesFinal; + } + + /** + * 获取物品缓存 + * 检测顺序: + * 1. 固定物品库 + * 2. 动态物品库 + * + * @param name 物品名称 + * @return + */ + public static ItemStack getCacheItem(String name) { + // 检测固定物品库是否存在该物品 + if (itemCachesFinal.containsKey(name)) { + return itemCachesFinal.get(name); + } + // 返回动态物品库 + return itemCaches.get(name); + } + + public static boolean isExists(String name) { + return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name); + } + + public static void LoadLib() { + try { + reloadItemName(); + reloadItemCache(); + itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR"))); + } catch (Exception e) { + MsgUtils.warn("物品库载入失败: &4" + e.getMessage()); + } + } + + public static void loadItemsFile(File file, boolean finalFile) { + FileConfiguration conf = ConfigUtils.load(Main.getInst(), file); + for (String name : conf.getConfigurationSection("").getKeys(false)) { + if (isExists(name)) { + MsgUtils.warn("无法载入载入物品 &4" + name + "&c, 因为它已经存在了"); + } else if (finalFile) { + itemCachesFinal.put(name, loadItem(conf, name)); + } else { + itemCaches.put(name, loadItem(conf, name)); + } + } + } + + public static void reloadItemCache() { + itemCaches.clear(); + itemCachesFinal.clear(); + loadItemsFile(getItemCacheFile(), false); + // 创建固定物品库 + finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems"); + if (!finalItemsFolder.exists()) { + finalItemsFolder.mkdir(); + } + // 检查固定物品库中的物品 + for (File file : Objects.requireNonNull(finalItemsFolder.listFiles())) { + loadItemsFile(file, true); + } + MsgUtils.send("载入 " + (itemCaches.size() + itemCachesFinal.size()) + " 项缓存物品"); + } + + public static void reloadItemName() { + FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration(); + itemlib.clear(); + for (String a : conf.getConfigurationSection("").getKeys(false)) { + itemlib.put(a, conf.getString(a)); + } + MsgUtils.send("载入 " + itemlib.size() + " 项物品名称"); + } + + public static File getItemCacheFile() { + File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml"); + if (!itemCacheFile.exists()) { + Main.getInst().saveResource("items.yml", true); + } + return itemCacheFile; + } + + public static String getCustomName(ItemStack item) { + if (item == null || item.getType().equals(Material.AIR)) { + return "空"; + } + int data = item.getType().getMaxDurability() == 0 ? item.getDurability() : 0; + return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : itemlib.get(item.getType() + ":" + data) == null ? item.getType().toString() : itemlib.get(item.getType() + ":" + data); + } + + public static ItemStack getItemFromDir(String name) { + if (itemdir != null) { + return itemdir.getItemStack("item." + name); + } + return null; + } + + @SuppressWarnings("deprecation") public static ItemStack item(int n, int a, int d) { return new ItemStack(n, a, (short) d); } - + public static ItemStack setName(ItemStack i, String n) { ItemMeta meta = i.getItemMeta(); meta.setDisplayName(n); i.setItemMeta(meta); return i; } - + public static ItemStack Enchant(ItemStack i, Enchantment e, int l) { ItemMeta meta = i.getItemMeta(); meta.addEnchant(e, l, false); i.setItemMeta(meta); return i; } - + public static ItemStack addFlag(ItemStack i, ItemFlag f) { ItemMeta meta = i.getItemMeta(); meta.addItemFlags(f); i.setItemMeta(meta); return i; } - + public static boolean isNull(ItemStack item) { - return item == null || item.getType().equals(Material.AIR); + return item == null || item.getType().equals(Material.AIR); } - + public static boolean isName(ItemStack i, String a) { return isNamed(i) && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null && i.getItemMeta().getDisplayName().equals(a); } - + public static boolean isNameAs(ItemStack i, String a) { return isNamed(i) && i.getItemMeta().getDisplayName().contains(a); } - + public static String asString(String args, Player placeholderPlayer) { - if (placeholderPlayer == null) { - return args.replace("&", "§"); - } - return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§")); + if (placeholderPlayer == null) { + return args.replace("&", "§"); + } + return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§")); } - + public static List asString(List args, Player placeholderPlayer) { - for (int i = 0 ; i < args.size() ; i ++) { - args.set(i, asString(args.get(i), placeholderPlayer)); - } - return args; + IntStream.range(0, args.size()).forEach(i -> args.set(i, asString(args.get(i), placeholderPlayer))); + return args; } - + public static ItemFlag asItemFlag(String flag) { - try { - return ItemFlag.valueOf(flag); - } - catch (Exception e) { - return null; - } + try { + return ItemFlag.valueOf(flag); + } catch (Exception e) { + return null; + } } - + @SuppressWarnings("deprecation") - public static Material asMaterial(String args) { - try { - Material material = Material.getMaterial(args); - return material != null ? material : Material.getMaterial(Integer.valueOf(args)); - } - catch (Exception e) { - return Material.STONE; - } - } - - @SuppressWarnings({ "deprecation" }) - public static Enchantment asEnchantment(String enchant) { - try { - Enchantment enchantment = Enchantment.getByName(enchant); - return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant)); - } - catch (Exception e) { - return null; - } + public static Material asMaterial(String args) { + try { + Material material = Material.getMaterial(args); + return material != null ? material : Material.getMaterial(Integer.valueOf(args)); + } catch (Exception e) { + return Material.STONE; + } } - + + @SuppressWarnings({"deprecation"}) + public static Enchantment asEnchantment(String enchant) { + try { + Enchantment enchantment = Enchantment.getByName(enchant); + return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant)); + } catch (Exception e) { + return null; + } + } + @SuppressWarnings("deprecation") - public static PotionEffectType asPotionEffectType(String potion) { - try { - PotionEffectType type = PotionEffectType.getByName(potion); - return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion)); - } - catch (Exception e) { - return null; - } + public static PotionEffectType asPotionEffectType(String potion) { + try { + PotionEffectType type = PotionEffectType.getByName(potion); + return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion)); + } catch (Exception e) { + return null; + } } - + public static Color asColor(String color) { - try { - return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2])); - } - catch (Exception e) { - return Color.fromBGR(0, 0, 0); - } + try { + return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2])); + } catch (Exception e) { + return Color.fromBGR(0, 0, 0); + } } - + public static String asAttribute(String name) { switch (name.toLowerCase()) { case "damage": @@ -267,320 +275,297 @@ public class ItemUtils { case "luck": return "generic.luck"; } - return null; + return null; } - + /** * 包含介绍 - * + * * @param i 物品 * @param a 关键字 */ public static boolean hasLore(ItemStack i, String a) { return isLored(i) && i.getItemMeta().getLore().toString().contains(a); } - + /** * 如果已描述 - * + * * @param i * @return */ public static boolean isLored(ItemStack i) { return i != null && i.getItemMeta() != null && i.getItemMeta().getLore() != null; } - + /** * 如果已命名 - * + * * @param i * @return */ - public static boolean isNamed(ItemStack i) { + public static boolean isNamed(ItemStack i) { return i != null && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null; } - + /** * 添加描述 - * - * @param is 物品 + * + * @param is 物品 * @param lore 描述 */ public static ItemStack addLore(ItemStack is, String lore) { - ItemMeta meta = is.getItemMeta(); - - List _lore = meta.hasLore() ? meta.getLore() : new ArrayList<>(); - _lore.add(lore.replaceAll("&", "§")); - + ItemMeta meta = is.getItemMeta(); + + List _lore = meta.hasLore() ? meta.getLore() : Collections.emptyList(); + _lore.add(lore.replaceAll("&", "§")); + is.setItemMeta(meta); return is; } - + /** * 移除描述 - * - * @param is 物品 + * + * @param is 物品 * @param line 行数 */ public static ItemStack delLore(ItemStack is, int line) { - ItemMeta meta = is.getItemMeta(); + ItemMeta meta = is.getItemMeta(); if (meta.hasLore()) { - List l = meta.getLore(); - if (l.size() >= line) { - l.remove(line); - meta.setLore(l); - is.setItemMeta(meta); - } + List l = meta.getLore(); + if (l.size() >= line) { + l.remove(line); + meta.setLore(l); + is.setItemMeta(meta); + } } return is; } - + /** * 获取介绍所在行数 - * + * * @param i 物品 * @param a 关键字 */ public static int getLore(ItemStack i, String a) { - if (isLored(i)) { - for (int j = 0; j < i.getItemMeta().getLore().size() ; j++) { - if (i.getItemMeta().getLore().get(j).contains(a)) { - return j; - } - } - } - return 0; + return isLored(i) ? IntStream.range(0, i.getItemMeta().getLore().size()).filter(j -> i.getItemMeta().getLore().get(j).contains(a)).findFirst().orElse(0) : 0; } - + /** * 添加耐久 - * + * * @param i 物品 * @param d 耐久 */ public static ItemStack addDurability(ItemStack i, int d) { - i.setDurability((short) (i.getDurability() + d)); - int min = i.getDurability(); - int max = i.getType().getMaxDurability(); - if (min >= max) { - i.setType(Material.AIR); - } - return i; + i.setDurability((short) (i.getDurability() + d)); + int min = i.getDurability(); + int max = i.getType().getMaxDurability(); + if (min >= max) { + i.setType(Material.AIR); + } + return i; } - + /** * 替换描述 - * - * @param i 物品 + * + * @param i 物品 * @param l1 关键字1 * @param l2 关键字2 */ public static ItemStack repalceLore(ItemStack i, String l1, String l2) { - if (!isLored(i)) { - return i; - } - else { - ItemMeta meta = i.getItemMeta(); - List lore = meta.getLore(); - for (int j = 0 ; j < lore.size() ; j++) { - lore.set(j, lore.get(j).replace(l1, l2)); - } - meta.setLore(lore); - i.setItemMeta(meta); - } - return i; + if (!isLored(i)) { + return i; + } else { + ItemMeta meta = i.getItemMeta(); + List lore = meta.getLore(); + IntStream.range(0, lore.size()).forEach(j -> lore.set(j, lore.get(j).replace(l1, l2))); + meta.setLore(lore); + i.setItemMeta(meta); + } + return i; } - + public static ItemStack loadItem(FileConfiguration f, String s) { - return loadItem(f, s, null); + return loadItem(f, s, null); } - + public static ItemStack loadItem(FileConfiguration f, String s, Player papiPlayer) { - return loadItem(f.getConfigurationSection(s), papiPlayer); + return loadItem(f.getConfigurationSection(s), papiPlayer); } - + public static ItemStack loadItem(ConfigurationSection section, Player papiPlayer) { - if (section.get("bukkit") instanceof ItemStack) { - return section.getItemStack("bukkit"); - } - // 材质 - ItemStack item = new ItemStack(asMaterial(section.get("material").toString())); - // 数量 - item.setAmount(section.contains("amount") ? section.getInt("amount") : 1); - // 耐久 - item.setDurability((short) section.getInt("data")); - // 元数据 - ItemMeta meta = item.getItemMeta(); - // 展示名 - if (section.contains("name")) { - meta.setDisplayName(asString(section.getString("name"), papiPlayer)); - } - // 描述 - if (section.contains("lore")) { - meta.setLore(asString(section.getStringList("lore"), papiPlayer)); - } - // 附魔 - if (section.contains("enchants")) { - for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) { - Enchantment enchant = asEnchantment(preEnchant); - if (enchant != null) { - meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true); - } - else { - MsgUtils.warn("&8" + preEnchant + " &c不是一个有效的附魔名称"); - MsgUtils.warn("&c输入 &4/taboolib enchants&c 查看所有附魔"); - } - } - } - // 标签 - if (section.contains("flags") && TabooLib.getVerint() > 10700) { - for (String preFlag : section.getStringList("flags")) { - ItemFlag flag = asItemFlag(preFlag); - if (flag != null) { - meta.addItemFlags(flag); - } - else { - MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称"); - MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签"); - } - } - } - // 皮革 - if (meta instanceof LeatherArmorMeta && section.contains("color")) { - ((LeatherArmorMeta) meta).setColor(asColor(section.getString("color"))); - } - // 药水 - if (meta instanceof PotionMeta && section.contains("potions")) { - PotionMeta potionMeta = (PotionMeta) meta; - for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) { - PotionEffectType potionEffectType = asPotionEffectType(prePotionName); - if (potionEffectType != null) { - potionMeta.addCustomEffect(new PotionEffect( - potionEffectType, - NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]), - NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true); - } - else { - MsgUtils.warn("&8" + potionEffectType + " &c不是一个有效的药水名称"); - MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水"); - } - } - } - // 元数据 - item.setItemMeta(meta); - // 数据 - NBTItem nbt = new NBTItem(item); - // 物品标签 - if (section.contains("nbt")) { - for (String name : section.getConfigurationSection("nbt").getKeys(false)) { - Object obj = section.get("nbt." + name); - if (obj instanceof String) { - nbt.setString(name, obj.toString()); - } - else if (obj instanceof Double) { - nbt.setDouble(name, Double.valueOf(obj.toString())); - } - else if (obj instanceof Integer) { - nbt.setInteger(name, Integer.valueOf(obj.toString())); - } - else if (obj instanceof Long) { - nbt.setLong(name, Long.valueOf(obj.toString())); - } - else { - nbt.setObject(name, obj); - } - } - } - // 物品属性 - if (section.contains("attributes")) { - NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); - for (String hand : section.getConfigurationSection("attributes").getKeys(false)) { - for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) { - if (asAttribute(name) != null) { - try { - NBTListCompound _attr = attr.addCompound(); - Object num = section.get("attributes." + hand + "." + name); - if (num.toString().contains("%")) { - _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); - _attr.setInteger("Operation", 1); - } - else { - _attr.setDouble("Amount", Double.valueOf(num.toString())); - _attr.setInteger("Operation", 0); - } - _attr.setString("AttributeName", asAttribute(name)); - _attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); - _attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); - _attr.setString("Name", asAttribute(name)); - if (!hand.equals("all")) { - _attr.setString("Slot", hand); - } - } - catch (Exception e) { - MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); - } - } - else { - MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称"); - MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性"); - } - } - } - } - return nbt.getItem(); + if (section.get("bukkit") instanceof ItemStack) { + return section.getItemStack("bukkit"); + } + // 材质 + ItemStack item = new ItemStack(asMaterial(section.get("material").toString())); + // 数量 + item.setAmount(section.contains("amount") ? section.getInt("amount") : 1); + // 耐久 + item.setDurability((short) section.getInt("data")); + // 元数据 + ItemMeta meta = item.getItemMeta(); + // 展示名 + if (section.contains("name")) { + meta.setDisplayName(asString(section.getString("name"), papiPlayer)); + } + // 描述 + if (section.contains("lore")) { + meta.setLore(asString(section.getStringList("lore"), papiPlayer)); + } + // 附魔 + if (section.contains("enchants")) { + for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) { + Enchantment enchant = asEnchantment(preEnchant); + if (enchant != null) { + meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true); + } else { + MsgUtils.warn("&8" + preEnchant + " &c不是一个有效的附魔名称"); + MsgUtils.warn("&c输入 &4/taboolib enchants&c 查看所有附魔"); + } + } + } + // 标签 + if (section.contains("flags") && TabooLib.getVerint() > 10700) { + for (String preFlag : section.getStringList("flags")) { + ItemFlag flag = asItemFlag(preFlag); + if (flag != null) { + meta.addItemFlags(flag); + } else { + MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称"); + MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签"); + } + } + } + // 皮革 + if (meta instanceof LeatherArmorMeta && section.contains("color")) { + ((LeatherArmorMeta) meta).setColor(asColor(section.getString("color"))); + } + // 药水 + if (meta instanceof PotionMeta && section.contains("potions")) { + PotionMeta potionMeta = (PotionMeta) meta; + for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) { + PotionEffectType potionEffectType = asPotionEffectType(prePotionName); + if (potionEffectType != null) { + potionMeta.addCustomEffect(new PotionEffect( + potionEffectType, + NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]), + NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true); + } else { + MsgUtils.warn("&8" + prePotionName + " &c不是一个有效的药水名称"); + MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水"); + } + } + } + // 元数据 + item.setItemMeta(meta); + // 数据 + NBTItem nbt = new NBTItem(item); + // 物品标签 + if (section.contains("nbt")) { + for (String name : section.getConfigurationSection("nbt").getKeys(false)) { + Object obj = section.get("nbt." + name); + if (obj instanceof String) { + nbt.setString(name, obj.toString()); + } else if (obj instanceof Double) { + nbt.setDouble(name, Double.valueOf(obj.toString())); + } else if (obj instanceof Integer) { + nbt.setInteger(name, Integer.valueOf(obj.toString())); + } else if (obj instanceof Long) { + nbt.setLong(name, Long.valueOf(obj.toString())); + } else { + nbt.setObject(name, obj); + } + } + } + // 物品属性 + if (section.contains("attributes")) { + NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); + for (String hand : section.getConfigurationSection("attributes").getKeys(false)) { + for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) { + if (asAttribute(name) != null) { + try { + NBTListCompound _attr = attr.addCompound(); + Object num = section.get("attributes." + hand + "." + name); + if (num.toString().contains("%")) { + _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); + _attr.setInteger("Operation", 1); + } else { + _attr.setDouble("Amount", Double.valueOf(num.toString())); + _attr.setInteger("Operation", 0); + } + _attr.setString("AttributeName", asAttribute(name)); + _attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); + _attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); + _attr.setString("Name", asAttribute(name)); + if (!hand.equals("all")) { + _attr.setString("Slot", hand); + } + } catch (Exception e) { + MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); + } + } else { + MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称"); + MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性"); + } + } + } + } + return nbt.getItem(); } - + public static NBTItem setAttribute(NBTItem nbt, String name, Object num, String hand) { - NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); - if (asAttribute(name) != null) { - try { - NBTListCompound _attr = null; - for (int i = 0 ; i < attr.size() ; i++) { - NBTListCompound nlc = attr.getCompound(i); - if (nlc.getString("AttributeName").equals(asAttribute(name))) { - _attr = nlc; - } - } - if (_attr == null) { - _attr = attr.addCompound(); - } - if (num.toString().contains("%")) { - _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); - _attr.setInteger("Operation", 1); - } - else { - _attr.setDouble("Amount", Double.valueOf(num.toString())); - _attr.setInteger("Operation", 0); - } - _attr.setString("AttributeName", asAttribute(name)); - _attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); - _attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); - _attr.setString("Name", asAttribute(name)); - if (!hand.equals("all")) { - _attr.setString("Slot", hand); - } - } - catch (Exception e) { - MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); - } - } - else { - MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称"); - MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性"); - } - return nbt; + NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); + if (asAttribute(name) != null) { + try { + NBTListCompound _attr = null; + for (int i = 0; i < attr.size(); i++) { + NBTListCompound nlc = attr.getCompound(i); + if (nlc.getString("AttributeName").equals(asAttribute(name))) { + _attr = nlc; + } + } + if (_attr == null) { + _attr = attr.addCompound(); + } + if (num.toString().contains("%")) { + _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); + _attr.setInteger("Operation", 1); + } else { + _attr.setDouble("Amount", Double.valueOf(num.toString())); + _attr.setInteger("Operation", 0); + } + _attr.setString("AttributeName", asAttribute(name)); + _attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); + _attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); + _attr.setString("Name", asAttribute(name)); + if (!hand.equals("all")) { + _attr.setString("Slot", hand); + } + } catch (Exception e) { + MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); + } + } else { + MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称"); + MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性"); + } + return nbt; } - + @Deprecated public static void putO(ItemStack item, Inventory inv, int i) { - inv.setItem(i, item); - inv.setItem(i+1, item); - inv.setItem(i+2, item); - inv.setItem(i+9, item); - inv.setItem(i+10, null); - inv.setItem(i+11, item); - inv.setItem(i+18, item); - inv.setItem(i+19, item); - inv.setItem(i+20, item); - } + inv.setItem(i, item); + inv.setItem(i + 1, item); + inv.setItem(i + 2, item); + inv.setItem(i + 9, item); + inv.setItem(i + 10, null); + inv.setItem(i + 11, item); + inv.setItem(i + 18, item); + inv.setItem(i + 19, item); + inv.setItem(i + 20, item); + } } diff --git a/src/main/java/me/skymc/taboolib/inventory/speciaitem/SpecialItem.java b/src/main/java/me/skymc/taboolib/inventory/speciaitem/SpecialItem.java index 044a470..b25bb1a 100644 --- a/src/main/java/me/skymc/taboolib/inventory/speciaitem/SpecialItem.java +++ b/src/main/java/me/skymc/taboolib/inventory/speciaitem/SpecialItem.java @@ -1,8 +1,8 @@ package me.skymc.taboolib.inventory.speciaitem; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - +import me.skymc.taboolib.Main; +import me.skymc.taboolib.inventory.ItemUtils; +import me.skymc.taboolib.message.MsgUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -12,141 +12,144 @@ import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.plugin.Plugin; -import lombok.Getter; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.message.MsgUtils; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; /** * @author sky * @since 2018年2月17日 下午8:34:12 */ public class SpecialItem implements Listener { - - private static SpecialItem specialItem = null; - - private final List ITEM_DATA = new CopyOnWriteArrayList<>(); - - @Getter - private boolean isLoaded; - - /** - * 构造方法 - */ - private SpecialItem() { - - } - - /** - * 获取工具对象 - * - * @return {@link SpecialItem} - */ - public static SpecialItem getInst() { - if (specialItem == null) { - synchronized (SpecialItem.class) { - if (specialItem == null) { - specialItem = new SpecialItem(); - // 注册监听器 - Bukkit.getPluginManager().registerEvents(specialItem, Main.getInst()); - } - } - } - return specialItem; - } - - /** - * 注册接口 - * - * @param item 接口对象 - */ - public void register(AbstractSpecialItem item) { - if (contains(item.getName())) { - MsgUtils.warn("特殊物品接口已存在, 检查名称 &4" + item.getName() + " &c是否重复"); - } - else { - ITEM_DATA.add(item); - if (isLoaded) { - item.onEnable(); - } - } - } - - /** - * 注销接口 - * - * @param name 注册名称 - */ - public void cancel(String name) { - for (AbstractSpecialItem specialitem : ITEM_DATA) { - if (specialitem.getName() != null && specialitem.getName().equals(specialitem.getName())) { - specialitem.onDisable(); - ITEM_DATA.remove(specialitem); - } - } - } - - /** - * 注销接口 - * - * @param plugin 注册插件 - */ - public void cancel(Plugin plugin) { - for (AbstractSpecialItem specialitem : ITEM_DATA) { - if (specialitem.getPlugin() != null && specialitem.getPlugin().equals(plugin)) { - specialitem.onDisable(); - ITEM_DATA.remove(specialitem); - } - } - } - - /** - * 判断名称是否存在 - * - * @param name 注册名称 - * @return boolean - */ - public boolean contains(String name) { - for (AbstractSpecialItem specialitem : ITEM_DATA) { - if (specialitem.getName().equals(name)) { - return true; - } - } - return false; - } - - /** - * 载入所有已注册接口 - */ - public void loadItems() { + + private static SpecialItem specialItem = null; + + private final List ITEM_DATA = new CopyOnWriteArrayList<>(); + + private boolean isLoaded; + + public boolean isLoaded() { + return isLoaded; + } + + /** + * 构造方法 + */ + private SpecialItem() { + + } + + /** + * 获取工具对象 + * + * @return {@link SpecialItem} + */ + public static SpecialItem getInst() { + if (specialItem == null) { + synchronized (SpecialItem.class) { + if (specialItem == null) { + specialItem = new SpecialItem(); + // 注册监听器 + Bukkit.getPluginManager().registerEvents(specialItem, Main.getInst()); + } + } + } + return specialItem; + } + + /** + * 注册接口 + * + * @param item 接口对象 + */ + public void register(AbstractSpecialItem item) { + if (contains(item.getName())) { + MsgUtils.warn("特殊物品接口已存在, 检查名称 &4" + item.getName() + " &c是否重复"); + } else { + ITEM_DATA.add(item); + if (isLoaded) { + item.onEnable(); + } + } + } + + /** + * 注销接口 + * + * @param name 注册名称 + */ + public void cancel(String name) { + for (AbstractSpecialItem specialitem : ITEM_DATA) { + if (specialitem.getName() != null && specialitem.getName().equals(specialitem.getName())) { + specialitem.onDisable(); + ITEM_DATA.remove(specialitem); + } + } + } + + /** + * 注销接口 + * + * @param plugin 注册插件 + */ + public void cancel(Plugin plugin) { + for (AbstractSpecialItem specialitem : ITEM_DATA) { + if (specialitem.getPlugin() != null && specialitem.getPlugin().equals(plugin)) { + specialitem.onDisable(); + ITEM_DATA.remove(specialitem); + } + } + } + + /** + * 判断名称是否存在 + * + * @param name 注册名称 + * @return boolean + */ + public boolean contains(String name) { + for (AbstractSpecialItem specialitem : ITEM_DATA) { + if (specialitem.getName().equals(name)) { + return true; + } + } + return false; + } + + /** + * 载入所有已注册接口 + */ + public void loadItems() { ITEM_DATA.forEach(AbstractSpecialItem::onEnable); - isLoaded = true; - } - - /** - * 注销所有已注册接口 - */ - public void unloadItems() { + isLoaded = true; + } + + /** + * 注销所有已注册接口 + */ + public void unloadItems() { ITEM_DATA.forEach(AbstractSpecialItem::onDisable); - ITEM_DATA.clear(); - } - - @EventHandler - public void onDisable(PluginDisableEvent e) { - cancel(e.getPlugin()); - } - - @EventHandler (priority = EventPriority.MONITOR) - public void click(InventoryClickEvent e) { - if (e.isCancelled()) { - return; - } - if (ItemUtils.isNull(e.getCurrentItem()) || ItemUtils.isNull(e.getCursor())) { - return; - } - Player player = (Player) e.getWhoClicked(); - for (AbstractSpecialItem specialitem : ITEM_DATA) { - for (SpecialItemResult result : specialitem.isCorrectClick(player, e.getCurrentItem(), e.getCursor())) { + ITEM_DATA.clear(); + } + + @EventHandler + public void onDisable(PluginDisableEvent e) { + cancel(e.getPlugin()); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void click(InventoryClickEvent e) { + if (e.isCancelled()) { + return; + } + if (ItemUtils.isNull(e.getCurrentItem()) || ItemUtils.isNull(e.getCursor())) { + return; + } + Player player = (Player) e.getWhoClicked(); + for (AbstractSpecialItem specialItem : ITEM_DATA) { + for (SpecialItemResult result : specialItem.isCorrectClick(player, e.getCurrentItem(), e.getCursor())) { + if (result == null) { + break; + } switch (result) { case CANCEL: e.setCancelled(true); @@ -173,8 +176,8 @@ public class SpecialItem implements Listener { e.getWhoClicked().setItemOnCursor(null); } break; - } - } - } - } + } + } + } + } } diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTContainer.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTContainer.java index 988283a..119a0d8 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTContainer.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTContainer.java @@ -1,6 +1,6 @@ package me.skymc.taboolib.itemnbtapi; -public class NBTContainer extends NBTCompound{ +public class NBTContainer extends NBTCompound { private Object nbt; @@ -8,29 +8,29 @@ public class NBTContainer extends NBTCompound{ super(null, null); nbt = NBTReflectionUtil.getNewNBTTag(); } - - protected NBTContainer(Object nbt){ + + protected NBTContainer(Object nbt) { super(null, null); this.nbt = nbt; } public NBTContainer(String nbtString) throws IllegalArgumentException { super(null, null); - try{ + try { nbt = NBTReflectionUtil.parseNBT(nbtString); - }catch(Exception ex){ + } catch (Exception ex) { ex.printStackTrace(); throw new IllegalArgumentException("Malformed Json: " + ex.getMessage()); } } @Override - protected Object getCompound() { + protected Object getCompound() { return nbt; } @Override - protected void setCompound(Object tag) { + protected void setCompound(Object tag) { nbt = tag; } diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTFile.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTFile.java index 2228a8a..2bc2faa 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTFile.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTFile.java @@ -36,12 +36,12 @@ public class NBTFile extends NBTCompound { } @Override - protected Object getCompound() { + protected Object getCompound() { return nbt; } @Override - protected void setCompound(Object compound) { + protected void setCompound(Object compound) { nbt = compound; } diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTItem.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTItem.java index 526612d..c7fec77 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTItem.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTItem.java @@ -12,12 +12,12 @@ public class NBTItem extends NBTCompound { } @Override - protected Object getCompound() { + protected Object getCompound() { return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem)); } @Override - protected void setCompound(Object compound) { + protected void setCompound(Object compound) { bukkitItem = NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.setNBTTag(compound, NBTReflectionUtil.getNMSItemStack(bukkitItem))); } @@ -28,12 +28,12 @@ public class NBTItem extends NBTCompound { protected void setItem(ItemStack item) { bukkitItem = item; } - - public static NBTContainer convertItemtoNBT(ItemStack item){ + + public static NBTContainer convertItemtoNBT(ItemStack item) { return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(item)); } - - public static ItemStack convertNBTtoItem(NBTCompound comp){ + + public static ItemStack convertNBTtoItem(NBTCompound comp) { return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp)); } diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTList.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTList.java index b75d74e..86f1a8a 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTList.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTList.java @@ -1,10 +1,10 @@ package me.skymc.taboolib.itemnbtapi; -import java.lang.reflect.Method; - import me.skymc.taboolib.itemnbtapi.utils.MethodNames; import me.skymc.taboolib.message.MsgUtils; +import java.lang.reflect.Method; + public class NBTList { private String listName; @@ -37,7 +37,7 @@ public class NBTList { method.invoke(listObject, compound); return new NBTListCompound(this, compound); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -52,7 +52,7 @@ public class NBTList { Object compound = method.invoke(listObject, id); return new NBTListCompound(this, compound); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -66,7 +66,7 @@ public class NBTList { Method method = listObject.getClass().getMethod("getString", int.class); return (String) method.invoke(listObject, i); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -82,7 +82,7 @@ public class NBTList { method.invoke(listObject, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); save(); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -97,7 +97,7 @@ public class NBTList { method.invoke(listObject, i, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); save(); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -107,7 +107,7 @@ public class NBTList { method.invoke(listObject, i); save(); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -116,7 +116,7 @@ public class NBTList { Method method = listObject.getClass().getMethod("size"); return (int) method.invoke(listObject); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return -1; } diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTListCompound.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTListCompound.java index f2386a4..750f968 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTListCompound.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTListCompound.java @@ -1,10 +1,10 @@ package me.skymc.taboolib.itemnbtapi; +import me.skymc.taboolib.message.MsgUtils; + import java.util.HashSet; import java.util.Set; -import me.skymc.taboolib.message.MsgUtils; - public class NBTListCompound { private NBTList owner; @@ -24,7 +24,7 @@ public class NBTListCompound { compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value); owner.save(); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -33,7 +33,7 @@ public class NBTListCompound { compound.getClass().getMethod("setInt", String.class, int.class).invoke(compound, key, value); owner.save(); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -41,7 +41,7 @@ public class NBTListCompound { try { return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return 0; } @@ -51,7 +51,7 @@ public class NBTListCompound { compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value); owner.save(); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -59,7 +59,7 @@ public class NBTListCompound { try { return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return 0; } @@ -69,7 +69,7 @@ public class NBTListCompound { try { return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return ""; } @@ -78,7 +78,7 @@ public class NBTListCompound { try { return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return false; } @@ -88,7 +88,7 @@ public class NBTListCompound { try { return (Set) compound.getClass().getMethod("c").invoke(compound); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return new HashSet<>(); } @@ -97,7 +97,7 @@ public class NBTListCompound { try { compound.getClass().getMethod("remove", String.class).invoke(compound, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTReflectionUtil.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTReflectionUtil.java index e53893d..4e2c012 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTReflectionUtil.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTReflectionUtil.java @@ -1,5 +1,14 @@ package me.skymc.taboolib.itemnbtapi; +import me.skymc.taboolib.TabooLib; +import me.skymc.taboolib.itemnbtapi.utils.GsonWrapper; +import me.skymc.taboolib.itemnbtapi.utils.MethodNames; +import me.skymc.taboolib.message.MsgUtils; +import org.bukkit.Bukkit; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; + import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; @@ -8,28 +17,18 @@ import java.lang.reflect.Method; import java.util.Set; import java.util.Stack; -import org.bukkit.Bukkit; -import org.bukkit.block.BlockState; -import org.bukkit.entity.Entity; -import org.bukkit.inventory.ItemStack; - -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.itemnbtapi.utils.GsonWrapper; -import me.skymc.taboolib.itemnbtapi.utils.MethodNames; -import me.skymc.taboolib.message.MsgUtils; - // TODO: finish codestyle cleanup -sgdc3 public class NBTReflectionUtil { private static final String version = TabooLib.getVersion(); - + @SuppressWarnings("rawtypes") private static Class getCraftItemStack() { try { return Class.forName("org.bukkit.craftbukkit." + version + ".inventory.CraftItemStack"); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } @@ -39,7 +38,7 @@ public class NBTReflectionUtil { try { return Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftEntity"); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } @@ -49,7 +48,7 @@ public class NBTReflectionUtil { try { return Class.forName("net.minecraft.server." + version + ".NBTBase"); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } @@ -59,19 +58,19 @@ public class NBTReflectionUtil { try { return Class.forName("net.minecraft.server." + version + ".NBTTagString"); } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } - + @SuppressWarnings("rawtypes") protected static Class getNMSItemStack() { try { return Class.forName("net.minecraft.server." + version + ".ItemStack"); } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } @@ -81,8 +80,8 @@ public class NBTReflectionUtil { try { return Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } @@ -92,19 +91,19 @@ public class NBTReflectionUtil { try { return Class.forName("net.minecraft.server." + version + ".NBTCompressedStreamTools"); } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } - + @SuppressWarnings("rawtypes") protected static Class getMojangsonParser() { try { return Class.forName("net.minecraft.server." + version + ".MojangsonParser"); } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } @@ -114,8 +113,8 @@ public class NBTReflectionUtil { try { return Class.forName("net.minecraft.server." + version + ".TileEntity"); } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } @@ -125,8 +124,8 @@ public class NBTReflectionUtil { try { return Class.forName("org.bukkit.craftbukkit." + version + ".CraftWorld"); } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } @@ -138,8 +137,8 @@ public class NBTReflectionUtil { Class c = Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); return c.newInstance(); } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } @@ -151,8 +150,8 @@ public class NBTReflectionUtil { Class clazz = Class.forName("net.minecraft.server." + version + ".BlockPosition"); return clazz.getConstructor(int.class, int.class, int.class).newInstance(x, y, z); } catch (Exception ex) { - - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); return null; } } @@ -164,7 +163,7 @@ public class NBTReflectionUtil { method.invoke(NMSItem, NBTTag); return NMSItem; } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -178,7 +177,7 @@ public class NBTReflectionUtil { method = clazz.getMethod("asNMSCopy", ItemStack.class); return method.invoke(clazz, item); } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } @@ -192,7 +191,7 @@ public class NBTReflectionUtil { method = clazz.getMethod("getHandle"); return method.invoke(getCraftEntity().cast(entity)); } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } @@ -206,11 +205,11 @@ public class NBTReflectionUtil { method = cis.getMethod("parse", String.class); return method.invoke(null, json); } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } - + @SuppressWarnings({"unchecked"}) public static Object readNBTFile(FileInputStream stream) { @SuppressWarnings("rawtypes") @@ -220,7 +219,7 @@ public class NBTReflectionUtil { method = clazz.getMethod("a", InputStream.class); return method.invoke(clazz, stream); } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } @@ -234,7 +233,7 @@ public class NBTReflectionUtil { method = clazz.getMethod("a", getNBTTagCompound(), OutputStream.class); return method.invoke(clazz, nbt, stream); } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } @@ -249,7 +248,7 @@ public class NBTReflectionUtil { Object answer = method.invoke(clazz, item); return (ItemStack) answer; } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } @@ -263,11 +262,11 @@ public class NBTReflectionUtil { method = clazz.getMethod("getTag"); return method.invoke(nmsitem); } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } - + @SuppressWarnings({"unchecked"}) public static Object convertNBTCompoundtoNMSItem(NBTCompound nbtcompound) { @SuppressWarnings("rawtypes") @@ -275,11 +274,11 @@ public class NBTReflectionUtil { try { return clazz.getConstructor(getNBTTagCompound()).newInstance(nbtcompound.getCompound()); } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } - + @SuppressWarnings({"unchecked"}) public static NBTContainer convertNMSItemtoNBTCompound(Object nmsitem) { @SuppressWarnings("rawtypes") @@ -290,7 +289,7 @@ public class NBTReflectionUtil { Object answer = method.invoke(nmsitem, getNewNBTTag()); return new NBTContainer(answer); } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } @@ -308,7 +307,7 @@ public class NBTReflectionUtil { answer = nbt; return answer; } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } @@ -320,7 +319,7 @@ public class NBTReflectionUtil { method.invoke(NMSItem, NBTTag); return NMSItem; } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -339,7 +338,7 @@ public class NBTReflectionUtil { answer = tag; return answer; } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } @@ -354,7 +353,7 @@ public class NBTReflectionUtil { method = getTileEntity().getMethod("a", getNBTTagCompound()); method.invoke(o, comp); } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } } @@ -368,7 +367,7 @@ public class NBTReflectionUtil { method = c.getMethod("getCompound", String.class); return method.invoke(compound, name); } catch (Exception e) { - MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); } return null; } @@ -390,7 +389,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, name, getNBTTagCompound().newInstance()); comp.setCompound(nbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -416,7 +415,7 @@ public class NBTReflectionUtil { } return nbttag; } - + public static void addOtherNBTCompound(NBTCompound comp, NBTCompound nbtcompound) { Object rootnbttag = comp.getCompound(); if (rootnbttag == null) { @@ -430,7 +429,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, nbtcompound.getCompound()); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -451,7 +450,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key, text); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -467,7 +466,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("getString", String.class); return (String) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -484,7 +483,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("get", String.class); return method.invoke(workingtag, key).toString(); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -506,7 +505,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key, i); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -522,7 +521,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("getInt", String.class); return (Integer) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -544,7 +543,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key, b); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -560,7 +559,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("getByteArray", String.class); return (byte[]) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -582,7 +581,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key, i); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -598,7 +597,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("getIntArray", String.class); return (int[]) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -620,7 +619,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key, f); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -636,7 +635,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("getFloat", String.class); return (Float) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -658,7 +657,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key, f); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -674,7 +673,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("getLong", String.class); return (Long) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -696,7 +695,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key, f); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -712,7 +711,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("getShort", String.class); return (Short) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -734,7 +733,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key, f); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -750,7 +749,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("getByte", String.class); return (Byte) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -772,7 +771,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key, d); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -788,7 +787,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("getDouble", String.class); return (Double) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -805,7 +804,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod(MethodNames.getTypeMethodName(), String.class); return (byte) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return 0; } @@ -827,7 +826,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key, d); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -843,7 +842,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("getBoolean", String.class); return (Boolean) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -868,7 +867,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key, val); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -884,7 +883,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("getList", String.class, int.class); return new NBTList(comp, key, type, method.invoke(workingtag, key, type.getId())); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -894,7 +893,7 @@ public class NBTReflectionUtil { String json = GsonWrapper.getString(value); setString(comp, key, json); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -919,7 +918,7 @@ public class NBTReflectionUtil { method.invoke(workingtag, key); comp.setCompound(rootnbttag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } } @@ -935,7 +934,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("hasKey", String.class); return (Boolean) method.invoke(workingtag, key); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } @@ -953,7 +952,7 @@ public class NBTReflectionUtil { method = workingtag.getClass().getMethod("c"); return (Set) method.invoke(workingtag); } catch (Exception ex) { - MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); + MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); } return null; } diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTTileEntity.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTTileEntity.java index 21024e9..3b25d70 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTTileEntity.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTTileEntity.java @@ -12,12 +12,12 @@ public class NBTTileEntity extends NBTCompound { } @Override - protected Object getCompound() { + protected Object getCompound() { return NBTReflectionUtil.getTileEntityNBTTagCompound(tile); } @Override - protected void setCompound(Object compound) { + protected void setCompound(Object compound) { NBTReflectionUtil.setTileEntityNBTTagCompound(tile, compound); } diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTType.java b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTType.java index 4fa85b9..c208638 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/NBTType.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/NBTType.java @@ -1,6 +1,7 @@ package me.skymc.taboolib.itemnbtapi; public enum NBTType { + NBTTagEnd(0), NBTTagByte(1), NBTTagShort(2), diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/utils/GsonWrapper.java b/src/main/java/me/skymc/taboolib/itemnbtapi/utils/GsonWrapper.java index 8fbfa9a..581a6d7 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/utils/GsonWrapper.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/utils/GsonWrapper.java @@ -1,7 +1,6 @@ package me.skymc.taboolib.itemnbtapi.utils; import com.google.gson.Gson; - import me.skymc.taboolib.message.MsgUtils; public class GsonWrapper { diff --git a/src/main/java/me/skymc/taboolib/itemnbtapi/utils/MethodNames.java b/src/main/java/me/skymc/taboolib/itemnbtapi/utils/MethodNames.java index 70b4548..7c02ebe 100644 --- a/src/main/java/me/skymc/taboolib/itemnbtapi/utils/MethodNames.java +++ b/src/main/java/me/skymc/taboolib/itemnbtapi/utils/MethodNames.java @@ -11,7 +11,7 @@ public class MethodNames { public static String getEntityNbtSetterMethodName() { return "a"; } - + public static String getTileDataMethodName() { if (TabooLib.getVerint() <= 10800) { return "b"; diff --git a/src/main/java/me/skymc/taboolib/javascript/JavaScriptUtils.java b/src/main/java/me/skymc/taboolib/javascript/JavaScriptUtils.java index ee79a93..e551099 100644 --- a/src/main/java/me/skymc/taboolib/javascript/JavaScriptUtils.java +++ b/src/main/java/me/skymc/taboolib/javascript/JavaScriptUtils.java @@ -1,77 +1,76 @@ package me.skymc.taboolib.javascript; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; +import me.skymc.taboolib.Main; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; -import me.skymc.taboolib.Main; - +@Deprecated public class JavaScriptUtils { - - private static ScriptEngineManager manager = new ScriptEngineManager(); - - public static ScriptEngineManager getScriptManager() { - return manager; - } - - public static void invokeJavaScript(File jsFile, String method, Object... o) { - ScriptEngine engine = manager.getEngineByName("javascript"); - try { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(Main.class.getClassLoader()); - - FileReader reader = new FileReader(jsFile); - engine.eval(reader); - - // TODO run - - Thread.currentThread().setContextClassLoader(classLoader); - } - catch (Exception e) { - // TODO: handle exception - } - } - - @Deprecated - public static Object JavaScriptInterface(String jsFile, Object... o) { - - ScriptEngine engine = manager.getEngineByName("javascript"); - try { - FileReader reader = new FileReader(jsFile); - engine.eval(reader); - - if (engine instanceof Invocable) { - return ((Invocable) engine).invokeFunction("main", o); - } - - reader.close(); - } catch (NoSuchMethodException | IOException | ScriptException e) { - e.printStackTrace(); - } - return null; - } - - @Deprecated - public static void JavaScriptExecute(String jsFile, Object... o) { - - ScriptEngine engine = manager.getEngineByName("javascript"); - try { - FileReader reader = new FileReader(jsFile); - engine.eval(reader); - - if (engine instanceof Invocable) { - ((Invocable) engine).invokeFunction("main", o); - } - - reader.close(); - } catch (NoSuchMethodException | IOException | ScriptException e) { - e.printStackTrace(); - } - } + + private static ScriptEngineManager manager = new ScriptEngineManager(); + + public static ScriptEngineManager getScriptManager() { + return manager; + } + + public static void invokeJavaScript(File jsFile, String method, Object... o) { + ScriptEngine engine = manager.getEngineByName("javascript"); + try { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(Main.class.getClassLoader()); + + FileReader reader = new FileReader(jsFile); + engine.eval(reader); + + // TODO run + + Thread.currentThread().setContextClassLoader(classLoader); + } catch (Exception e) { + // TODO: handle exception + } + } + + @Deprecated + public static Object JavaScriptInterface(String jsFile, Object... o) { + + ScriptEngine engine = manager.getEngineByName("javascript"); + try { + FileReader reader = new FileReader(jsFile); + engine.eval(reader); + + if (engine instanceof Invocable) { + return ((Invocable) engine).invokeFunction("main", o); + } + + reader.close(); + } catch (NoSuchMethodException | IOException | ScriptException e) { + e.printStackTrace(); + } + return null; + } + + @Deprecated + public static void JavaScriptExecute(String jsFile, Object... o) { + + ScriptEngine engine = manager.getEngineByName("javascript"); + try { + FileReader reader = new FileReader(jsFile); + engine.eval(reader); + + if (engine instanceof Invocable) { + ((Invocable) engine).invokeFunction("main", o); + } + + reader.close(); + } catch (NoSuchMethodException | IOException | ScriptException e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/me/skymc/taboolib/javashell/JavaShell.java b/src/main/java/me/skymc/taboolib/javashell/JavaShell.java index 67adb68..51e794f 100644 --- a/src/main/java/me/skymc/taboolib/javashell/JavaShell.java +++ b/src/main/java/me/skymc/taboolib/javashell/JavaShell.java @@ -1,8 +1,6 @@ package me.skymc.taboolib.javashell; import com.ilummc.tlib.dependency.TDependencyLoader; -import lombok.Getter; -import lombok.Setter; import me.skymc.taboolib.Main; import me.skymc.taboolib.message.MsgUtils; import org.apache.commons.lang.ArrayUtils; @@ -16,41 +14,78 @@ import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; +import java.util.Arrays; import java.util.HashMap; +import java.util.Objects; public class JavaShell { - @Getter - @Setter private static String paths = ""; - @Getter - @Setter private static File javaShellFolder; - @Getter - @Setter private static File scriptFolder; - @Getter - @Setter private static File cacheFolder; - @Getter - @Setter private static File libFolder; - @Getter - @Setter private static HashMap> shells = new HashMap<>(); + public static String getPaths() { + return paths; + } + + public static void setPaths(String paths) { + JavaShell.paths = paths; + } + + public static File getJavaShellFolder() { + return javaShellFolder; + } + + public static void setJavaShellFolder(File javaShellFolder) { + JavaShell.javaShellFolder = javaShellFolder; + } + + public static File getScriptFolder() { + return scriptFolder; + } + + public static void setScriptFolder(File scriptFolder) { + JavaShell.scriptFolder = scriptFolder; + } + + public static File getCacheFolder() { + return cacheFolder; + } + + public static void setCacheFolder(File cacheFolder) { + JavaShell.cacheFolder = cacheFolder; + } + + public static File getLibFolder() { + return libFolder; + } + + public static void setLibFolder(File libFolder) { + JavaShell.libFolder = libFolder; + } + + public static HashMap> getShells() { + return shells; + } + + public static void setShells(HashMap> shells) { + JavaShell.shells = shells; + } + public static void javaShellSetup() { File dataFolder = Main.getInst().getDataFolder(); File pluginsFolder = dataFolder.getParentFile(); File serverRoot = Bukkit.getWorldContainer(); File[] rootJars = serverRoot.listFiles((dir, name) -> name.toLowerCase().endsWith("jar")); - File[] pluginJars = pluginsFolder.listFiles((dir, name) -> name.toLowerCase().endsWith("jar")); for (File file : (File[]) ArrayUtils.addAll(rootJars, pluginJars)) { @@ -85,27 +120,23 @@ public class JavaShell { } loadLibrary(); + new BukkitRunnable() { @Override public void run() { long time = System.currentTimeMillis(); - for (File file : scriptFolder.listFiles()) { - if (!file.getName().startsWith("-")) { - reloadShell(file.getName()); - } - } + Arrays.stream(Objects.requireNonNull(scriptFolder.listFiles())).filter(file -> !file.getName().startsWith("-")).map(File::getName).forEach(JavaShell::reloadShell); MsgUtils.send("载入 " + shells.size() + " 个脚本, 耗时 &f" + (System.currentTimeMillis() - time) + "ms"); } }.runTask(Main.getInst()); } public static void javaShellCancel() { - for (File cacheFile : cacheFolder.listFiles()) { - cacheFile.delete(); - } - for (String name : shells.keySet()) { - invokeMethod(name, "onDisable"); + try { + Arrays.stream(Objects.requireNonNull(cacheFolder.listFiles())).forEach(File::delete); + shells.keySet().forEach(name -> invokeMethod(name, "onDisable")); + } catch (Exception ignored) { } } @@ -117,8 +148,7 @@ public class JavaShell { if (disableMethod != null) { disableMethod.invoke(clazz.newInstance()); } - } catch (Exception e) { - // + } catch (Exception ignored) { } } } @@ -128,15 +158,10 @@ public class JavaShell { Class clazz = shells.remove(shell); try { if (clazz.newInstance() instanceof Listener) { - for (RegisteredListener listener : HandlerList.getRegisteredListeners(Main.getInst())) { - if (listener.getListener().getClass().getName().equals(clazz.getName())) { - HandlerList.unregisterAll(listener.getListener()); - } - } + HandlerList.getRegisteredListeners(Main.getInst()).stream().filter(listener -> listener.getListener().getClass().getName().equals(clazz.getName())).map(RegisteredListener::getListener).forEach(HandlerList::unregisterAll); MsgUtils.send("已为脚本 &f" + shell + " &7注销监听器"); } - } catch (Exception e) { - // + } catch (Exception ignored) { } } @@ -189,13 +214,6 @@ public class JavaShell { } private static void loadLibrary() { - for (File jar : libFolder.listFiles()) { - try { - TDependencyLoader.addToPath(Main.getInst(), jar); - MsgUtils.send("成功载入 &f" + jar.getName() + " &7到运行库"); - } catch (Exception e) { - // - } - } + Arrays.stream(Objects.requireNonNull(libFolder.listFiles())).forEach(jar -> TDependencyLoader.addToPath(Main.getInst(), jar)); } } diff --git a/src/main/java/me/skymc/taboolib/json/CDL.java b/src/main/java/me/skymc/taboolib/json/CDL.java index e5fa3da..22b7947 100644 --- a/src/main/java/me/skymc/taboolib/json/CDL.java +++ b/src/main/java/me/skymc/taboolib/json/CDL.java @@ -10,52 +10,49 @@ public class CDL { c = x.next(); } while (c == ' ' || c == '\t'); switch (c) { - case 0: - return null; - case '"': - case '\'': - q = c; - sb = new StringBuffer(); - for (;;) { - c = x.next(); - if (c == q) { - break; + case 0: + return null; + case '"': + case '\'': + q = c; + sb = new StringBuffer(); + for (; ; ) { + c = x.next(); + if (c == q) { + break; + } + if (c == 0 || c == '\n' || c == '\r') { + throw x.syntaxError("Missing close quote '" + q + "'."); + } + sb.append(c); } - if (c == 0 || c == '\n' || c == '\r') { - throw x.syntaxError("Missing close quote '" + q + "'."); - } - sb.append(c); - } - return sb.toString(); - case ',': - x.back(); - return ""; - default: - x.back(); - return x.nextTo(','); + return sb.toString(); + case ',': + x.back(); + return ""; + default: + x.back(); + return x.nextTo(','); } } public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { JSONArray ja = new JSONArray(); - for (;;) { + for (; ; ) { String value = getValue(x); char c = x.next(); - if (value == null || + if (value == null || (ja.length() == 0 && value.length() == 0 && c != ',')) { return null; } ja.put(value); - for (;;) { - if (c == ',') { - break; - } + while (c != ',') { if (c != ' ') { if (c == '\n' || c == '\r' || c == 0) { return ja; } throw x.syntaxError("Bad character '" + c + "' (" + - (int)c + ")."); + (int) c + ")."); } c = x.next(); } @@ -65,7 +62,7 @@ public class CDL { public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws JSONException { JSONArray ja = rowToJSONArray(x); - return ja != null ? ja.toJSONObject(names) : null; + return ja != null ? ja.toJSONObject(names) : null; } public static String rowToString(JSONArray ja) { @@ -77,8 +74,8 @@ public class CDL { Object object = ja.opt(i); if (object != null) { String string = object.toString(); - if (string.length() > 0 && (string.indexOf(',') >= 0 || - string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || + if (string.length() > 0 && (string.indexOf(',') >= 0 || + string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || string.indexOf(0) >= 0 || string.charAt(0) == '"')) { sb.append('"'); int length = string.length(); @@ -117,7 +114,7 @@ public class CDL { return null; } JSONArray ja = new JSONArray(); - for (;;) { + for (; ; ) { JSONObject jo = rowToJSONObject(names, x); if (jo == null) { break; diff --git a/src/main/java/me/skymc/taboolib/json/Cookie.java b/src/main/java/me/skymc/taboolib/json/Cookie.java index 5e0d431..3022d0c 100644 --- a/src/main/java/me/skymc/taboolib/json/Cookie.java +++ b/src/main/java/me/skymc/taboolib/json/Cookie.java @@ -3,16 +3,16 @@ package me.skymc.taboolib.json; public class Cookie { public static String escape(String string) { - char c; - String s = string.trim(); + char c; + String s = string.trim(); StringBuilder sb = new StringBuilder(); - int length = s.length(); + int length = s.length(); for (int i = 0; i < length; i += 1) { c = s.charAt(i); if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { sb.append('%'); - sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); - sb.append(Character.forDigit((char)(c & 0x0f), 16)); + sb.append(Character.forDigit((char) ((c >>> 4) & 0x0f), 16)); + sb.append(Character.forDigit((char) (c & 0x0f), 16)); } else { sb.append(c); } @@ -21,9 +21,9 @@ public class Cookie { } public static JSONObject toJSONObject(String string) throws JSONException { - String name; - JSONObject jo = new JSONObject(); - Object value; + String name; + JSONObject jo = new JSONObject(); + Object value; JSONTokener x = new JSONTokener(string); jo.put("name", x.nextTo('=')); x.next('='); @@ -81,7 +81,7 @@ public class Cookie { int d = JSONTokener.dehexchar(string.charAt(i + 1)); int e = JSONTokener.dehexchar(string.charAt(i + 2)); if (d >= 0 && e >= 0) { - c = (char)(d * 16 + e); + c = (char) (d * 16 + e); i += 2; } } diff --git a/src/main/java/me/skymc/taboolib/json/CookieList.java b/src/main/java/me/skymc/taboolib/json/CookieList.java index 9bf43bb..439ed6f 100644 --- a/src/main/java/me/skymc/taboolib/json/CookieList.java +++ b/src/main/java/me/skymc/taboolib/json/CookieList.java @@ -17,10 +17,10 @@ public class CookieList { } @SuppressWarnings("rawtypes") - public static String toString(JSONObject jo) throws JSONException { - boolean b = false; - Iterator keys = jo.keys(); - String string; + public static String toString(JSONObject jo) throws JSONException { + boolean b = false; + Iterator keys = jo.keys(); + String string; StringBuilder sb = new StringBuilder(); while (keys.hasNext()) { string = keys.next().toString(); diff --git a/src/main/java/me/skymc/taboolib/json/HTTP.java b/src/main/java/me/skymc/taboolib/json/HTTP.java index 3466b69..b0b4552 100644 --- a/src/main/java/me/skymc/taboolib/json/HTTP.java +++ b/src/main/java/me/skymc/taboolib/json/HTTP.java @@ -7,9 +7,9 @@ public class HTTP { public static final String CRLF = "\r\n"; public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - HTTPTokener x = new HTTPTokener(string); - String token; + JSONObject jo = new JSONObject(); + HTTPTokener x = new HTTPTokener(string); + String token; token = x.nextToken(); if (token.toUpperCase().startsWith("HTTP")) { @@ -32,9 +32,9 @@ public class HTTP { } @SuppressWarnings("rawtypes") - public static String toString(JSONObject jo) throws JSONException { - Iterator keys = jo.keys(); - String string; + public static String toString(JSONObject jo) throws JSONException { + Iterator keys = jo.keys(); + String string; StringBuilder sb = new StringBuilder(); if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { sb.append(jo.getString("HTTP-Version")); @@ -56,9 +56,9 @@ public class HTTP { sb.append(CRLF); while (keys.hasNext()) { string = keys.next().toString(); - if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && + if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && - !"Request-URI".equals(string) && !jo.isNull(string)) { + !"Request-URI".equals(string) && !jo.isNull(string)) { sb.append(string); sb.append(": "); sb.append(jo.getString(string)); diff --git a/src/main/java/me/skymc/taboolib/json/HTTPTokener.java b/src/main/java/me/skymc/taboolib/json/HTTPTokener.java index a03f1c2..d04b607 100644 --- a/src/main/java/me/skymc/taboolib/json/HTTPTokener.java +++ b/src/main/java/me/skymc/taboolib/json/HTTPTokener.java @@ -15,7 +15,7 @@ public class HTTPTokener extends JSONTokener { } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; - for (;;) { + for (; ; ) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); @@ -25,8 +25,8 @@ public class HTTPTokener extends JSONTokener { } sb.append(c); } - } - for (;;) { + } + for (; ; ) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } diff --git a/src/main/java/me/skymc/taboolib/json/JSONArray.java b/src/main/java/me/skymc/taboolib/json/JSONArray.java index b0345cd..793a100 100644 --- a/src/main/java/me/skymc/taboolib/json/JSONArray.java +++ b/src/main/java/me/skymc/taboolib/json/JSONArray.java @@ -24,7 +24,7 @@ public class JSONArray { } if (x.nextClean() != ']') { x.back(); - for (;;) { + for (; ; ) { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(JSONObject.NULL); @@ -33,17 +33,17 @@ public class JSONArray { this.myArrayList.add(x.nextValue()); } switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == ']') { + case ';': + case ',': + if (x.nextClean() == ']') { + return; + } + x.back(); + break; + case ']': return; - } - x.back(); - break; - case ']': - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); + default: + throw x.syntaxError("Expected a ',' or ']'"); } } } @@ -86,11 +86,11 @@ public class JSONArray { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && - ((String)object).equalsIgnoreCase("false"))) { + ((String) object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && - ((String)object).equalsIgnoreCase("true"))) { + ((String) object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); @@ -100,11 +100,11 @@ public class JSONArray { Object object = this.get(index); try { return object instanceof Number - ? ((Number)object).doubleValue() - : Double.parseDouble((String)object); + ? ((Number) object).doubleValue() + : Double.parseDouble((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + - "] is not a number."); + "] is not a number."); } } @@ -112,18 +112,18 @@ public class JSONArray { Object object = this.get(index); try { return object instanceof Number - ? ((Number)object).intValue() - : Integer.parseInt((String)object); + ? ((Number) object).intValue() + : Integer.parseInt((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + - "] is not a number."); + "] is not a number."); } } public JSONArray getJSONArray(int index) throws JSONException { Object object = this.get(index); if (object instanceof JSONArray) { - return (JSONArray)object; + return (JSONArray) object; } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); @@ -132,28 +132,28 @@ public class JSONArray { public JSONObject getJSONObject(int index) throws JSONException { Object object = this.get(index); if (object instanceof JSONObject) { - return (JSONObject)object; + return (JSONObject) object; } throw new JSONException("JSONArray[" + index + - "] is not a JSONObject."); + "] is not a JSONObject."); } public long getLong(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number - ? ((Number)object).longValue() - : Long.parseLong((String)object); + ? ((Number) object).longValue() + : Long.parseLong((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + - "] is not a number."); + "] is not a number."); } } public String getString(int index) throws JSONException { Object object = this.get(index); if (object instanceof String) { - return (String)object; + return (String) object; } throw new JSONException("JSONArray[" + index + "] not a string."); } @@ -181,15 +181,15 @@ public class JSONArray { public Object opt(int index) { return (index < 0 || index >= this.length()) - ? null - : this.myArrayList.get(index); + ? null + : this.myArrayList.get(index); } - public boolean optBoolean(int index) { + public boolean optBoolean(int index) { return this.optBoolean(index, false); } - public boolean optBoolean(int index, boolean defaultValue) { + public boolean optBoolean(int index, boolean defaultValue) { try { return this.getBoolean(index); } catch (Exception e) { @@ -223,12 +223,12 @@ public class JSONArray { public JSONArray optJSONArray(int index) { Object o = this.opt(index); - return o instanceof JSONArray ? (JSONArray)o : null; + return o instanceof JSONArray ? (JSONArray) o : null; } public JSONObject optJSONObject(int index) { Object o = this.opt(index); - return o instanceof JSONObject ? (JSONObject)o : null; + return o instanceof JSONObject ? (JSONObject) o : null; } public long optLong(int index) { @@ -250,7 +250,7 @@ public class JSONArray { public String optString(int index, String defaultValue) { Object object = this.opt(index); return JSONObject.NULL.equals(object) - ? defaultValue : object + ? defaultValue : object .toString(); } @@ -355,7 +355,7 @@ public class JSONArray { } @Override - public String toString() { + public String toString() { try { return '[' + this.join(",") + ']'; } catch (Exception e) { @@ -407,7 +407,7 @@ public class JSONArray { writer.write(']'); return writer; } catch (IOException e) { - throw new JSONException(e); + throw new JSONException(e); } } } diff --git a/src/main/java/me/skymc/taboolib/json/JSONML.java b/src/main/java/me/skymc/taboolib/json/JSONML.java index 9f5ab21..2353bfc 100644 --- a/src/main/java/me/skymc/taboolib/json/JSONML.java +++ b/src/main/java/me/skymc/taboolib/json/JSONML.java @@ -5,19 +5,15 @@ import java.util.Iterator; @SuppressWarnings({"rawtypes"}) public class JSONML { - private static Object parse( - XMLTokener x, - boolean arrayForm, - JSONArray ja - ) throws JSONException { - String attribute; - char c; - String closeTag = null; - int i; - JSONArray newja = null; - JSONObject newjo = null; - Object token; - String tagName = null; + private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException { + String attribute; + char c; + String closeTag; + int i; + JSONArray newja; + JSONObject newjo; + Object token; + String tagName; while (true) { if (!x.more()) { @@ -32,7 +28,7 @@ public class JSONML { if (!(token instanceof String)) { throw new JSONException( "Expected a closing name instead of '" + - token + "'."); + token + "'."); } if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped close tag"); @@ -81,7 +77,7 @@ public class JSONML { if (!(token instanceof String)) { throw x.syntaxError("Bad tagName '" + token + "'."); } - tagName = (String)token; + tagName = (String) token; newja = new JSONArray(); newjo = new JSONObject(); if (arrayForm) { @@ -96,7 +92,7 @@ public class JSONML { } } token = null; - for (;;) { + for (; ; ) { if (token == null) { token = x.nextToken(); } @@ -106,7 +102,7 @@ public class JSONML { if (!(token instanceof String)) { break; } - attribute = (String)token; + attribute = (String) token; if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { throw x.syntaxError("Reserved attribute."); } @@ -116,7 +112,7 @@ public class JSONML { if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } - newjo.accumulate(attribute, XML.stringToValue((String)token)); + newjo.accumulate(attribute, XML.stringToValue((String) token)); token = null; } else { newjo.accumulate(attribute, ""); @@ -140,13 +136,12 @@ public class JSONML { if (token != XML.GT) { throw x.syntaxError("Misshaped tag"); } - closeTag = (String)parse(x, arrayForm, newja); + closeTag = (String) parse(x, arrayForm, newja); if (closeTag != null) { if (!closeTag.equals(tagName)) { throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); } - tagName = null; if (!arrayForm && newja.length() > 0) { newjo.put("childNodes", newja); } @@ -163,8 +158,8 @@ public class JSONML { } else { if (ja != null) { ja.put(token instanceof String - ? XML.stringToValue((String)token) - : token); + ? XML.stringToValue((String) token) + : token); } } } @@ -175,11 +170,11 @@ public class JSONML { } public static JSONArray toJSONArray(XMLTokener x) throws JSONException { - return (JSONArray)parse(x, true, null); + return (JSONArray) parse(x, true, null); } public static JSONObject toJSONObject(XMLTokener x) throws JSONException { - return (JSONObject)parse(x, false, null); + return (JSONObject) parse(x, false, null); } public static JSONObject toJSONObject(String string) throws JSONException { @@ -187,15 +182,15 @@ public class JSONML { } public static String toString(JSONArray ja) throws JSONException { - int i; - JSONObject jo; - String key; - Iterator keys; - int length; - Object object; + int i; + JSONObject jo; + String key; + Iterator keys; + int length; + Object object; StringBuilder sb = new StringBuilder(); - String tagName; - String value; + String tagName; + String value; tagName = ja.getString(0); XML.noSpace(tagName); tagName = XML.escape(tagName); @@ -205,7 +200,7 @@ public class JSONML { object = ja.opt(1); if (object instanceof JSONObject) { i = 2; - jo = (JSONObject)object; + jo = (JSONObject) object; keys = jo.keys(); while (keys.hasNext()) { key = keys.next().toString(); @@ -236,9 +231,9 @@ public class JSONML { if (object instanceof String) { sb.append(XML.escape(object.toString())); } else if (object instanceof JSONObject) { - sb.append(toString((JSONObject)object)); + sb.append(toString((JSONObject) object)); } else if (object instanceof JSONArray) { - sb.append(toString((JSONArray)object)); + sb.append(toString((JSONArray) object)); } } } while (i < length); @@ -252,14 +247,14 @@ public class JSONML { public static String toString(JSONObject jo) throws JSONException { StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - String key; - Iterator keys; - int length; - Object object; - String tagName; - String value; + int i; + JSONArray ja; + String key; + Iterator keys; + int length; + Object object; + String tagName; + String value; tagName = jo.optString("tagName"); if (tagName == null) { return XML.escape(jo.toString()); @@ -297,9 +292,9 @@ public class JSONML { if (object instanceof String) { sb.append(XML.escape(object.toString())); } else if (object instanceof JSONObject) { - sb.append(toString((JSONObject)object)); + sb.append(toString((JSONObject) object)); } else if (object instanceof JSONArray) { - sb.append(toString((JSONArray)object)); + sb.append(toString((JSONArray) object)); } else { sb.append(object.toString()); } diff --git a/src/main/java/me/skymc/taboolib/json/JSONObject.java b/src/main/java/me/skymc/taboolib/json/JSONObject.java index 19fdb2d..70667e9 100644 --- a/src/main/java/me/skymc/taboolib/json/JSONObject.java +++ b/src/main/java/me/skymc/taboolib/json/JSONObject.java @@ -6,31 +6,25 @@ import java.io.Writer; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.ResourceBundle; +import java.util.*; @SuppressWarnings({"rawtypes", "unchecked"}) public class JSONObject { - private static final class Null { + private static final class Null { @Override - protected final Object clone() { + protected final Object clone() { return this; } @Override - public boolean equals(Object object) { + public boolean equals(Object object) { return object == null || object == this; } @Override - public String toString() { + public String toString() { return "null"; } } @@ -61,16 +55,16 @@ public class JSONObject { if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } - for (;;) { + for (; ; ) { c = x.nextClean(); switch (c) { - case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); - case '}': - return; - default: - x.back(); - key = x.nextValue().toString(); + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + x.back(); + key = x.nextValue().toString(); } c = x.nextClean(); if (c == '=') { @@ -82,17 +76,17 @@ public class JSONObject { } this.putOnce(key, x.nextValue()); switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == '}') { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + x.back(); + break; + case '}': return; - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); + default: + throw x.syntaxError("Expected a ',' or '}'"); } } } @@ -138,7 +132,7 @@ public class JSONObject { while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (key instanceof String) { - String[] path = ((String)key).split("\\."); + String[] path = ((String) key).split("\\."); int last = path.length - 1; JSONObject target = this; for (int i = 0; i < last; i += 1) { @@ -150,15 +144,12 @@ public class JSONObject { } target = nextTarget; } - target.put(path[last], bundle.getString((String)key)); + target.put(path[last], bundle.getString((String) key)); } } } - - public JSONObject accumulate( - String key, - Object value - ) throws JSONException { + + public void accumulate(String key, Object value) throws JSONException { testValidity(value); Object object = this.opt(key); if (object == null) { @@ -166,20 +157,19 @@ public class JSONObject { ? new JSONArray().put(value) : value); } else if (object instanceof JSONArray) { - ((JSONArray)object).put(value); + ((JSONArray) object).put(value); } else { this.put(key, new JSONArray().put(object).put(value)); } - return this; } - + public JSONObject append(String key, Object value) throws JSONException { testValidity(value); Object object = this.opt(key); if (object == null) { this.put(key, new JSONArray().put(value)); } else if (object instanceof JSONArray) { - this.put(key, ((JSONArray)object).put(value)); + this.put(key, ((JSONArray) object).put(value)); } else { throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); @@ -220,11 +210,11 @@ public class JSONObject { Object object = this.get(key); if (object.equals(Boolean.FALSE) || (object instanceof String && - ((String)object).equalsIgnoreCase("false"))) { + ((String) object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && - ((String)object).equalsIgnoreCase("true"))) { + ((String) object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + @@ -235,11 +225,11 @@ public class JSONObject { Object object = this.get(key); try { return object instanceof Number - ? ((Number)object).doubleValue() - : Double.parseDouble((String)object); + ? ((Number) object).doubleValue() + : Double.parseDouble((String) object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + - "] is not a number."); + "] is not a number."); } } @@ -247,18 +237,18 @@ public class JSONObject { Object object = this.get(key); try { return object instanceof Number - ? ((Number)object).intValue() - : Integer.parseInt((String)object); + ? ((Number) object).intValue() + : Integer.parseInt((String) object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + - "] is not an int."); + "] is not an int."); } } public JSONArray getJSONArray(String key) throws JSONException { Object object = this.get(key); if (object instanceof JSONArray) { - return (JSONArray)object; + return (JSONArray) object; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); @@ -267,7 +257,7 @@ public class JSONObject { public JSONObject getJSONObject(String key) throws JSONException { Object object = this.get(key); if (object instanceof JSONObject) { - return (JSONObject)object; + return (JSONObject) object; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); @@ -277,11 +267,11 @@ public class JSONObject { Object object = this.get(key); try { return object instanceof Number - ? ((Number)object).longValue() - : Long.parseLong((String)object); + ? ((Number) object).longValue() + : Long.parseLong((String) object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + - "] is not a long."); + "] is not a long."); } } @@ -294,7 +284,7 @@ public class JSONObject { String[] names = new String[length]; int i = 0; while (iterator.hasNext()) { - names[i] = (String)iterator.next(); + names[i] = (String) iterator.next(); i += 1; } return names; @@ -320,10 +310,10 @@ public class JSONObject { public String getString(String key) throws JSONException { Object object = this.get(key); if (object instanceof String) { - return (String)object; + return (String) object; } throw new JSONException("JSONObject[" + quote(key) + - "] not a string."); + "] not a string."); } public boolean has(String key) { @@ -381,7 +371,7 @@ public class JSONObject { public JSONArray names() { JSONArray ja = new JSONArray(); - Iterator keys = this.keys(); + Iterator keys = this.keys(); while (keys.hasNext()) { ja.put(keys.next()); } @@ -449,12 +439,12 @@ public class JSONObject { public JSONArray optJSONArray(String key) { Object o = this.opt(key); - return o instanceof JSONArray ? (JSONArray)o : null; + return o instanceof JSONArray ? (JSONArray) o : null; } public JSONObject optJSONObject(String key) { Object object = this.opt(key); - return object instanceof JSONObject ? (JSONObject)object : null; + return object instanceof JSONObject ? (JSONObject) object : null; } public long optLong(String key) { @@ -489,7 +479,7 @@ public class JSONObject { } catch (Exception e) { throw new JSONException(e); } - if (object instanceof String) { + if (object != null) { return (String) object; } throw new JSONException("Bad value from toJSONString: " + object); @@ -601,53 +591,52 @@ public class JSONObject { b = c; c = string.charAt(i); switch (c) { - case '\\': - case '"': - w.write('\\'); - w.write(c); - break; - case '/': - if (b == '<') { + case '\\': + case '"': w.write('\\'); - } - w.write(c); - break; - case '\b': - w.write("\\b"); - break; - case '\t': - w.write("\\t"); - break; - case '\n': - w.write("\\n"); - break; - case '\f': - w.write("\\f"); - break; - case '\r': - w.write("\\r"); - break; - default: - if (c < ' ' || (c >= '\u0080' && c < '\u00a0') - || (c >= '\u2000' && c < '\u2100')) { - hhhh = "000" + Integer.toHexString(c); - w.write("\\u" + hhhh.substring(hhhh.length() - 4)); - } else { w.write(c); - } + break; + case '/': + if (b == '<') { + w.write('\\'); + } + w.write(c); + break; + case '\b': + w.write("\\b"); + break; + case '\t': + w.write("\\t"); + break; + case '\n': + w.write("\\n"); + break; + case '\f': + w.write("\\f"); + break; + case '\r': + w.write("\\r"); + break; + default: + if (c < ' ' || (c >= '\u0080' && c < '\u00a0') + || (c >= '\u2000' && c < '\u2100')) { + hhhh = "000" + Integer.toHexString(c); + w.write("\\u" + hhhh.substring(hhhh.length() - 4)); + } else { + w.write(c); + } } } w.write('"'); return w; } - + public Object remove(String key) { return this.map.remove(key); } - static Writer writeValue(Writer writer, Object value, - int indentFactor, int indent) throws JSONException, IOException { - if (value == null || value == null) { + static void writeValue(Writer writer, Object value, int indentFactor, int indent) throws JSONException, IOException { + if (value == null) { writer.write("null"); } else if (value instanceof JSONObject) { ((JSONObject) value).write(writer, indentFactor, indent); @@ -675,20 +664,19 @@ public class JSONObject { } else { quote(value.toString(), writer); } - return writer; } public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { - if (((Double)o).isInfinite() || ((Double)o).isNaN()) { + if (((Double) o).isInfinite() || ((Double) o).isNaN()) { throw new JSONException( - "JSON does not allow non-finite numbers."); + "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { - if (((Float)o).isInfinite() || ((Float)o).isNaN()) { + if (((Float) o).isInfinite() || ((Float) o).isNaN()) { throw new JSONException( - "JSON does not allow non-finite numbers."); + "JSON does not allow non-finite numbers."); } } } @@ -706,7 +694,7 @@ public class JSONObject { } @Override - public String toString() { + public String toString() { try { return this.toString(0); } catch (Exception e) { @@ -727,48 +715,48 @@ public class JSONObject { } } - public static Object wrap(Object object) { - try { - if (object == null) { - return NULL; - } - if (object instanceof JSONObject || object instanceof JSONArray || - NULL.equals(object) || object instanceof JSONString || - object instanceof Byte || object instanceof Character || - object instanceof Short || object instanceof Integer || - object instanceof Long || object instanceof Boolean || - object instanceof Float || object instanceof Double || - object instanceof String || object instanceof Enum) { - return object; - } + public static Object wrap(Object object) { + try { + if (object == null) { + return NULL; + } + if (object instanceof JSONObject || object instanceof JSONArray || + NULL.equals(object) || object instanceof JSONString || + object instanceof Byte || object instanceof Character || + object instanceof Short || object instanceof Integer || + object instanceof Long || object instanceof Boolean || + object instanceof Float || object instanceof Double || + object instanceof String || object instanceof Enum) { + return object; + } - if (object instanceof Collection) { - return new JSONArray((Collection)object); - } - if (object.getClass().isArray()) { - return new JSONArray(object); - } - if (object instanceof Map) { - return new JSONObject((Map)object); - } - Package objectPackage = object.getClass().getPackage(); - String objectPackageName = objectPackage != null - ? objectPackage.getName() - : ""; - if ( - objectPackageName.startsWith("java.") || - objectPackageName.startsWith("javax.") || - object.getClass().getClassLoader() == null - ) { - return object.toString(); - } - return new JSONObject(object); - } catch(Exception exception) { - return null; - } - } + if (object instanceof Collection) { + return new JSONArray((Collection) object); + } + if (object.getClass().isArray()) { + return new JSONArray(object); + } + if (object instanceof Map) { + return new JSONObject((Map) object); + } + Package objectPackage = object.getClass().getPackage(); + String objectPackageName = objectPackage != null + ? objectPackage.getName() + : ""; + if ( + objectPackageName.startsWith("java.") || + objectPackageName.startsWith("javax.") || + object.getClass().getClassLoader() == null + ) { + return object.toString(); + } + return new JSONObject(object); + } catch (Exception exception) { + return null; + } + } - public Writer write(Writer writer) throws JSONException { + public Writer write(Writer writer) throws JSONException { return this.write(writer, 0, 0); } @@ -880,5 +868,5 @@ public class JSONObject { } catch (IOException exception) { throw new JSONException(exception); } - } + } } diff --git a/src/main/java/me/skymc/taboolib/json/JSONTokener.java b/src/main/java/me/skymc/taboolib/json/JSONTokener.java index 1bb311e..d659a66 100644 --- a/src/main/java/me/skymc/taboolib/json/JSONTokener.java +++ b/src/main/java/me/skymc/taboolib/json/JSONTokener.java @@ -1,27 +1,22 @@ package me.skymc.taboolib.json; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; +import java.io.*; public class JSONTokener { - private long character; + private long character; private boolean eof; - private long index; - private long line; - private char previous; - private Reader reader; + private long index; + private long line; + private char previous; + private Reader reader; private boolean usePrevious; public JSONTokener(Reader reader) { this.reader = reader.markSupported() - ? reader - : new BufferedReader(reader); + ? reader + : new BufferedReader(reader); this.eof = false; this.usePrevious = false; this.previous = 0; @@ -114,26 +109,26 @@ public class JSONTokener { return n; } - public String next(int n) throws JSONException { - if (n == 0) { - return ""; - } + public String next(int n) throws JSONException { + if (n == 0) { + return ""; + } - char[] chars = new char[n]; - int pos = 0; + char[] chars = new char[n]; + int pos = 0; - while (pos < n) { - chars[pos] = this.next(); - if (this.end()) { - throw this.syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(chars); - } + while (pos < n) { + chars[pos] = this.next(); + if (this.end()) { + throw this.syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(chars); + } public char nextClean() throws JSONException { - for (;;) { + for (; ; ) { char c = this.next(); if (c == 0 || c > ' ') { return c; @@ -144,56 +139,56 @@ public class JSONTokener { public String nextString(char quote) throws JSONException { char c; StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = this.next(); switch (c) { - case 0: - case '\n': - case '\r': - throw this.syntaxError("Unterminated string"); - case '\\': - c = this.next(); - switch (c) { - case 'b': - sb.append('\b'); - break; - case 't': - sb.append('\t'); - break; - case 'n': - sb.append('\n'); - break; - case 'f': - sb.append('\f'); - break; - case 'r': - sb.append('\r'); - break; - case 'u': - sb.append((char)Integer.parseInt(this.next(4), 16)); - break; - case '"': - case '\'': + case 0: + case '\n': + case '\r': + throw this.syntaxError("Unterminated string"); case '\\': - case '/': - sb.append(c); + c = this.next(); + switch (c) { + case 'b': + sb.append('\b'); + break; + case 't': + sb.append('\t'); + break; + case 'n': + sb.append('\n'); + break; + case 'f': + sb.append('\f'); + break; + case 'r': + sb.append('\r'); + break; + case 'u': + sb.append((char) Integer.parseInt(this.next(4), 16)); + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw this.syntaxError("Illegal escape."); + } break; default: - throw this.syntaxError("Illegal escape."); - } - break; - default: - if (c == quote) { - return sb.toString(); - } - sb.append(c); + if (c == quote) { + return sb.toString(); + } + sb.append(c); } } } public String nextTo(char delimiter) throws JSONException { StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { char c = this.next(); if (c == delimiter || c == 0 || c == '\n' || c == '\r') { if (c != 0) { @@ -208,7 +203,7 @@ public class JSONTokener { public String nextTo(String delimiters) throws JSONException { char c; StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = this.next(); if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { @@ -281,8 +276,8 @@ public class JSONTokener { } @Override - public String toString() { + public String toString() { return " at " + this.index + " [character " + this.character + " line " + - this.line + "]"; + this.line + "]"; } } diff --git a/src/main/java/me/skymc/taboolib/json/JSONWriter.java b/src/main/java/me/skymc/taboolib/json/JSONWriter.java index 1323258..51074c0 100644 --- a/src/main/java/me/skymc/taboolib/json/JSONWriter.java +++ b/src/main/java/me/skymc/taboolib/json/JSONWriter.java @@ -4,7 +4,7 @@ import java.io.IOException; import java.io.Writer; public class JSONWriter { - + private static final int maxdepth = 200; private boolean comma; @@ -60,8 +60,8 @@ public class JSONWriter { private JSONWriter end(char mode, char c) throws JSONException { if (this.mode != mode) { throw new JSONException(mode == 'a' - ? "Misplaced endArray." - : "Misplaced endObject."); + ? "Misplaced endArray." + : "Misplaced endObject."); } this.pop(mode); try { @@ -127,10 +127,10 @@ public class JSONWriter { } this.top -= 1; this.mode = this.top == 0 - ? 'd' - : this.stack[this.top - 1] == null - ? 'a' - : 'k'; + ? 'd' + : this.stack[this.top - 1] == null + ? 'a' + : 'k'; } private void push(JSONObject jo) throws JSONException { diff --git a/src/main/java/me/skymc/taboolib/json/XML.java b/src/main/java/me/skymc/taboolib/json/XML.java index 7a0f8ad..6d98271 100644 --- a/src/main/java/me/skymc/taboolib/json/XML.java +++ b/src/main/java/me/skymc/taboolib/json/XML.java @@ -29,23 +29,23 @@ public class XML { for (int i = 0, length = string.length(); i < length; i++) { char c = string.charAt(i); switch (c) { - case '&': - sb.append("&"); - break; - case '<': - sb.append("<"); - break; - case '>': - sb.append(">"); - break; - case '"': - sb.append("""); - break; - case '\'': - sb.append("'"); - break; - default: - sb.append(c); + case '&': + sb.append("&"); + break; + case '<': + sb.append("<"); + break; + case '>': + sb.append(">"); + break; + case '"': + sb.append("""); + break; + case '\'': + sb.append("'"); + break; + default: + sb.append(c); } } return sb.toString(); @@ -58,7 +58,7 @@ public class XML { } for (i = 0; i < length; i += 1) { if (Character.isWhitespace(string.charAt(i))) { - throw new JSONException("'" + string + + throw new JSONException("'" + string + "' contains a space character."); } } @@ -66,12 +66,12 @@ public class XML { private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { - char c; - int i; + char c; + int i; JSONObject jsonobject = null; - String string; - String tagName; - Object token; + String string; + String tagName; + Object token; token = x.nextToken(); if (token == BANG) { c = x.next(); @@ -113,7 +113,7 @@ public class XML { token = x.nextToken(); if (name == null) { throw x.syntaxError("Mismatched close tag " + token); - } + } if (!token.equals(name)) { throw x.syntaxError("Mismatched " + name + " and " + token); } @@ -125,23 +125,23 @@ public class XML { } else if (token instanceof Character) { throw x.syntaxError("Misshaped tag"); } else { - tagName = (String)token; + tagName = (String) token; token = null; jsonobject = new JSONObject(); - for (;;) { + for (; ; ) { if (token == null) { token = x.nextToken(); } if (token instanceof String) { - string = (String)token; + string = (String) token; token = x.nextToken(); if (token == EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } - jsonobject.accumulate(string, - XML.stringToValue((String)token)); + jsonobject.accumulate(string, + XML.stringToValue((String) token)); token = null; } else { jsonobject.accumulate(string, ""); @@ -157,7 +157,7 @@ public class XML { } return false; } else if (token == GT) { - for (;;) { + for (; ; ) { token = x.nextContent(); if (token == null) { if (tagName != null) { @@ -165,9 +165,9 @@ public class XML { } return false; } else if (token instanceof String) { - string = (String)token; + string = (String) token; if (string.length() > 0) { - jsonobject.accumulate("content", + jsonobject.accumulate("content", XML.stringToValue(string)); } } else if (token == LT) { @@ -175,8 +175,8 @@ public class XML { if (jsonobject.length() == 0) { context.accumulate(tagName, ""); } else if (jsonobject.length() == 1 && - jsonobject.opt("content") != null) { - context.accumulate(tagName, + jsonobject.opt("content") != null) { + context.accumulate(tagName, jsonobject.opt("content")); } else { context.accumulate(tagName, jsonobject); @@ -230,7 +230,7 @@ public class XML { } } } - } catch (Exception ignore) { + } catch (Exception ignore) { } return string; } @@ -248,24 +248,23 @@ public class XML { return toString(object, null); } - public static String toString(Object object, String tagName) - throws JSONException { + public static String toString(Object object, String tagName) throws JSONException { StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - JSONObject jo; - String key; - Iterator keys; - int length; - String string; - Object value; + int i; + JSONArray ja; + JSONObject jo; + String key; + Iterator keys; + int length; + String string; + Object value; if (object instanceof JSONObject) { if (tagName != null) { sb.append('<'); sb.append(tagName); sb.append('>'); } - jo = (JSONObject)object; + jo = (JSONObject) object; keys = jo.keys(); while (keys.hasNext()) { key = keys.next().toString(); @@ -273,14 +272,9 @@ public class XML { if (value == null) { value = ""; } - if (value instanceof String) { - string = (String)value; - } else { - string = null; - } if ("content".equals(key)) { if (value instanceof JSONArray) { - ja = (JSONArray)value; + ja = (JSONArray) value; length = ja.length(); for (i = 0; i < length; i += 1) { if (i > 0) { @@ -292,7 +286,7 @@ public class XML { sb.append(escape(value.toString())); } } else if (value instanceof JSONArray) { - ja = (JSONArray)value; + ja = (JSONArray) value; length = ja.length(); for (i = 0; i < length; i += 1) { value = ja.get(i); @@ -327,17 +321,17 @@ public class XML { object = new JSONArray(object); } if (object instanceof JSONArray) { - ja = (JSONArray)object; + ja = (JSONArray) object; length = ja.length(); for (i = 0; i < length; i += 1) { sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); } return sb.toString(); } else { - string = (object == null) ? "null" : escape(object.toString()); + string = escape(object.toString()); return (tagName == null) ? "\"" + string + "\"" : - (string.length() == 0) ? "<" + tagName + "/>" : - "<" + tagName + ">" + string + ""; + (string.length() == 0) ? "<" + tagName + "/>" : + "<" + tagName + ">" + string + ""; } } } diff --git a/src/main/java/me/skymc/taboolib/json/XMLTokener.java b/src/main/java/me/skymc/taboolib/json/XMLTokener.java index c88bd4c..c242bd0 100644 --- a/src/main/java/me/skymc/taboolib/json/XMLTokener.java +++ b/src/main/java/me/skymc/taboolib/json/XMLTokener.java @@ -3,26 +3,26 @@ package me.skymc.taboolib.json; @SuppressWarnings({"rawtypes", "unchecked"}) public class XMLTokener extends JSONTokener { - public static final java.util.HashMap entity; + public static final java.util.HashMap entity; - static { - entity = new java.util.HashMap(8); - entity.put("amp", XML.AMP); - entity.put("apos", XML.APOS); - entity.put("gt", XML.GT); - entity.put("lt", XML.LT); - entity.put("quot", XML.QUOT); - } + static { + entity = new java.util.HashMap(8); + entity.put("amp", XML.AMP); + entity.put("apos", XML.APOS); + entity.put("gt", XML.GT); + entity.put("lt", XML.LT); + entity.put("quot", XML.QUOT); + } public XMLTokener(String s) { super(s); } public String nextCDATA() throws JSONException { - char c; - int i; + char c; + int i; StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = next(); if (end()) { throw syntaxError("Unclosed CDATA"); @@ -30,7 +30,7 @@ public class XMLTokener extends JSONTokener { sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && - sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { + sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } @@ -38,7 +38,7 @@ public class XMLTokener extends JSONTokener { } public Object nextContent() throws JSONException { - char c; + char c; StringBuffer sb; do { c = next(); @@ -50,7 +50,7 @@ public class XMLTokener extends JSONTokener { return XML.LT; } sb = new StringBuffer(); - for (;;) { + for (; ; ) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); @@ -66,7 +66,7 @@ public class XMLTokener extends JSONTokener { public Object nextEntity(char ampersand) throws JSONException { StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { char c = next(); if (Character.isLetterOrDigit(c) || c == '#') { sb.append(Character.toLowerCase(c)); @@ -88,52 +88,52 @@ public class XMLTokener extends JSONTokener { c = next(); } while (Character.isWhitespace(c)); switch (c) { - case 0: - throw syntaxError("Misshaped meta tag"); - case '<': - return XML.LT; - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - case '"': - case '\'': - q = c; - for (;;) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); + case 0: + throw syntaxError("Misshaped meta tag"); + case '<': + return XML.LT; + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; + case '"': + case '\'': + q = c; + for (; ; ) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return Boolean.TRUE; + } } - if (c == q) { - return Boolean.TRUE; + default: + for (; ; ) { + c = next(); + if (Character.isWhitespace(c)) { + return Boolean.TRUE; + } + switch (c) { + case 0: + case '<': + case '>': + case '/': + case '=': + case '!': + case '?': + case '"': + case '\'': + back(); + return Boolean.TRUE; + } } - } - default: - for (;;) { - c = next(); - if (Character.isWhitespace(c)) { - return Boolean.TRUE; - } - switch (c) { - case 0: - case '<': - case '>': - case '/': - case '=': - case '!': - case '?': - case '"': - case '\'': - back(); - return Boolean.TRUE; - } - } } } @@ -145,64 +145,64 @@ public class XMLTokener extends JSONTokener { c = next(); } while (Character.isWhitespace(c)); switch (c) { - case 0: - throw syntaxError("Misshaped element"); - case '<': - throw syntaxError("Misplaced '<'"); - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - case '"': - case '\'': - q = c; - sb = new StringBuffer(); - for (;;) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); + case 0: + throw syntaxError("Misshaped element"); + case '<': + throw syntaxError("Misplaced '<'"); + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; + case '"': + case '\'': + q = c; + sb = new StringBuffer(); + for (; ; ) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return sb.toString(); + } + if (c == '&') { + sb.append(nextEntity(c)); + } else { + sb.append(c); + } } - if (c == q) { - return sb.toString(); - } - if (c == '&') { - sb.append(nextEntity(c)); - } else { + default: + sb = new StringBuffer(); + for (; ; ) { sb.append(c); + c = next(); + if (Character.isWhitespace(c)) { + return sb.toString(); + } + switch (c) { + case 0: + return sb.toString(); + case '>': + case '/': + case '=': + case '!': + case '?': + case '[': + case ']': + back(); + return sb.toString(); + case '<': + case '"': + case '\'': + throw syntaxError("Bad character in a name"); + } } - } - default: - sb = new StringBuffer(); - for (;;) { - sb.append(c); - c = next(); - if (Character.isWhitespace(c)) { - return sb.toString(); - } - switch (c) { - case 0: - return sb.toString(); - case '>': - case '/': - case '=': - case '!': - case '?': - case '[': - case ']': - back(); - return sb.toString(); - case '<': - case '"': - case '\'': - throw syntaxError("Bad character in a name"); - } - } } } @@ -222,7 +222,7 @@ public class XMLTokener extends JSONTokener { } circle[i] = c; } - for (;;) { + for (; ; ) { j = offset; b = true; for (i = 0; i < length; i += 1) { diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java b/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java index df230f3..e8e7a3f 100644 --- a/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java +++ b/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java @@ -1,431 +1,447 @@ package me.skymc.taboolib.jsonformatter; +import me.skymc.taboolib.json.JSONArray; +import me.skymc.taboolib.json.JSONObject; +import me.skymc.taboolib.jsonformatter.click.ClickEvent; +import me.skymc.taboolib.jsonformatter.hover.HoverEvent; +import me.skymc.taboolib.nms.NMSUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import me.skymc.taboolib.json.JSONArray; -import me.skymc.taboolib.json.JSONObject; -import me.skymc.taboolib.jsonformatter.click.ClickEvent; -import me.skymc.taboolib.jsonformatter.hover.HoverEvent; -import me.skymc.taboolib.nms.NMSUtils; - public class JSONFormatter { - - private JSONArray ja = new JSONArray(); - private Builder builder = new Builder(); - private String color = ""; + + public static void sendRawMessage(Player player, String message) { + try { + Object entityplayer = NMSUtils.getHandle(player); + Object ppco = ppc.get(entityplayer); + Object packet = ppocc.newInstance(message); + sp.invoke(ppco, packet); + } catch (Exception e) { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + message); + } + } + + private JSONArray ja = new JSONArray(); + private Builder builder = new Builder(); + private String color = ""; private List all = new ArrayList<>(); - private boolean newline = true; - - public JSONFormatter(){ - } - - public JSONFormatter(boolean newline){ - this.newline = newline; - } - - public JSONFormatter append(JSONFormatter json){ - if(json.ja.length() == 0) - return this; - try{ - if(newline && json.newline){ - all.addAll(json.all); - } - for(int i = 0; i < json.ja.length(); i++){ - add(json.ja.get(i)); - } - }catch(Exception e){ - e.printStackTrace(); - } - return this; - } - - public int getSize(){ - if(newline){ return 1; } - return all.size() + 1; - } - - public JSONFormatter newLine(){ - if(newline){ - append("\n"); - }else{ - all.add(ja); - ja = new JSONArray(); - } - resetAll(); - return this; - } - - public JSONFormatter newLine(int amount){ - for(int i = 0; i < amount; i++) - newLine(); - return this; - } - - public void clear(){ - ja = new JSONArray(); - builder = new Builder(); - color = ""; - } - - public JSONFormatter resetAll(){ - return resetColors().resetModifiers(); - } - - public JSONFormatter resetColors(){ - color = ""; - return this; - } - - public JSONFormatter resetModifiers(){ - builder = new Builder(); - return this; - } - - public String toJSON(){ - JSONObject jo = new JSONObject(); - try{ - if(ja.length() > 0) - jo.put("extra", ja); - jo.put("text", ""); - }catch(Exception e){ - e.printStackTrace(); - } - return jo.toString(); - } - - public List toJSONList(){ + private boolean newline = true; + + public JSONFormatter() { + } + + public JSONFormatter(boolean newline) { + this.newline = newline; + } + + public JSONFormatter append(JSONFormatter json) { + if (json.ja.length() == 0) + return this; + try { + if (newline && json.newline) { + all.addAll(json.all); + } + for (int i = 0; i < json.ja.length(); i++) { + add(json.ja.get(i)); + } + } catch (Exception e) { + e.printStackTrace(); + } + return this; + } + + public int getSize() { + if (newline) { + return 1; + } + return all.size() + 1; + } + + public JSONFormatter newLine() { + if (newline) { + append("\n"); + } else { + all.add(ja); + ja = new JSONArray(); + } + resetAll(); + return this; + } + + public JSONFormatter newLine(int amount) { + for (int i = 0; i < amount; i++) + newLine(); + return this; + } + + public void clear() { + ja = new JSONArray(); + builder = new Builder(); + color = ""; + } + + public JSONFormatter resetAll() { + return resetColors().resetModifiers(); + } + + public JSONFormatter resetColors() { + color = ""; + return this; + } + + public JSONFormatter resetModifiers() { + builder = new Builder(); + return this; + } + + public String toJSON() { + JSONObject jo = new JSONObject(); + try { + if (ja.length() > 0) + jo.put("extra", ja); + jo.put("text", ""); + } catch (Exception e) { + e.printStackTrace(); + } + return jo.toString(); + } + + public List toJSONList() { List list = new ArrayList<>(); - try{ - for(JSONArray ja : all){ - JSONObject jo = new JSONObject(); - if(ja.length() > 0) - jo.put("extra", ja); - jo.put("text", ""); - list.add(jo.toString()); - } - JSONObject jo = new JSONObject(); - if(ja.length() > 0) - jo.put("extra", ja); - jo.put("text", ""); - list.add(jo.toString()); - return list; - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - public Object toSerialized(){ - try{ - return a.invoke(null, toJSON()); - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - public List toSerializedList(){ + try { + for (JSONArray ja : all) { + JSONObject jo = new JSONObject(); + if (ja.length() > 0) + jo.put("extra", ja); + jo.put("text", ""); + list.add(jo.toString()); + } + JSONObject jo = new JSONObject(); + if (ja.length() > 0) + jo.put("extra", ja); + jo.put("text", ""); + list.add(jo.toString()); + return list; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public Object toSerialized() { + try { + return a.invoke(null, toJSON()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public List toSerializedList() { List list = new ArrayList<>(); - try{ - for(String s : toJSONList()){ - list.add(a.invoke(null, s)); - } - return list; - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - public JSONFormatter send(Player player){ - JSONFormatter.send(player, this); - return this; - } - - private void add(Object jo){ - if(ja == null) - ja = new JSONArray(); - if(jo != null) - ja.put(jo); - } - - private JSONFormatter append(String text, BuilderMaker bm){ - builder = new Builder(builder); - for(int i = 0; i < text.length(); i++){ - char c = text.charAt(i); - switch(c){ - case '§':{ - if((i + 1) == text.length()){ - builder.append(c); - continue; - } - ChatColor cc = ChatColor.getByChar(text.charAt(i + 1)); - if(cc == null){ - builder.append(c); - break; - } - add(bm.make()); - switch(cc){ - case BOLD: - builder = new Builder(builder); - builder.bold = true; - break; - case ITALIC: - builder = new Builder(builder); - builder.italic = true; - break; - case MAGIC: - builder = new Builder(builder); - builder.magic = true; - break; - case RESET: - builder = new Builder(); - color = ""; - break; - case STRIKETHROUGH: - builder = new Builder(builder); - builder.strikethrough = true; - break; - case UNDERLINE: - builder = new Builder(builder); - builder.underline = true; - break; - default:{ - builder = new Builder(); - color = cc.name().toLowerCase(); - break; - } - } - i++; - break; - } - default:{ - builder.append(c); - } - } - } - add(bm.make()); - return this; - } - - public JSONFormatter append(String text){ - return append(text, new BuilderMaker(){ - @Override - public JSONObject make(){ - return builder.toString(color); - } - }); - } - - public JSONFormatter appendHover(String text, final HoverEvent hevent){ - return append(text, new BuilderMaker(){ - @Override - public JSONObject make(){ - return builder.toStringHover(color, hevent); - } - }); - } - - public JSONFormatter appendClick(String text, final ClickEvent cevent){ - return append(text, new BuilderMaker(){ - @Override - public JSONObject make(){ - return builder.toStringClick(color, cevent); - } - }); - } - - public JSONFormatter appendHoverClick(String text, final HoverEvent hevent, final ClickEvent cevent){ - return append(text, new BuilderMaker(){ - @Override - public JSONObject make(){ - return builder.toStringHoverClick(color, hevent, cevent); - } - }); - } - - public Object getPacket(){ - try{ - return ppocc.newInstance(toSerialized()); + try { + for (String s : toJSONList()) { + list.add(a.invoke(null, s)); + } + return list; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public JSONFormatter send(Player player) { + JSONFormatter.send(player, this); + return this; + } + + private void add(Object jo) { + if (ja == null) + ja = new JSONArray(); + if (jo != null) + ja.put(jo); + } + + private JSONFormatter append(String text, BuilderMaker bm) { + builder = new Builder(builder); + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + switch (c) { + case '§': { + if ((i + 1) == text.length()) { + builder.append(c); + continue; + } + ChatColor cc = ChatColor.getByChar(text.charAt(i + 1)); + if (cc == null) { + builder.append(c); + break; + } + add(bm.make()); + switch (cc) { + case BOLD: + builder = new Builder(builder); + builder.bold = true; + break; + case ITALIC: + builder = new Builder(builder); + builder.italic = true; + break; + case MAGIC: + builder = new Builder(builder); + builder.magic = true; + break; + case RESET: + builder = new Builder(); + color = ""; + break; + case STRIKETHROUGH: + builder = new Builder(builder); + builder.strikethrough = true; + break; + case UNDERLINE: + builder = new Builder(builder); + builder.underline = true; + break; + default: { + builder = new Builder(); + color = cc.name().toLowerCase(); + break; + } + } + i++; + break; + } + default: { + builder.append(c); + } + } + } + add(bm.make()); + return this; + } + + public JSONFormatter append(String text) { + return append(text, new BuilderMaker() { + @Override + public JSONObject make() { + return builder.toString(color); + } + }); + } + + public JSONFormatter appendHover(String text, final HoverEvent hevent) { + return append(text, new BuilderMaker() { + @Override + public JSONObject make() { + return builder.toStringHover(color, hevent); + } + }); + } + + public JSONFormatter appendClick(String text, final ClickEvent cevent) { + return append(text, new BuilderMaker() { + @Override + public JSONObject make() { + return builder.toStringClick(color, cevent); + } + }); + } + + public JSONFormatter appendHoverClick(String text, final HoverEvent hevent, final ClickEvent cevent) { + return append(text, new BuilderMaker() { + @Override + public JSONObject make() { + return builder.toStringHoverClick(color, hevent, cevent); + } + }); + } + + public Object getPacket() { + try { + return ppocc.newInstance(toSerialized()); } catch (Exception ignored) { - } - return null; - } - - public List getPacketList(){ + } + return null; + } + + public List getPacketList() { List list = new ArrayList<>(); - try{ - for(Object o : toSerializedList()){ - list.add(ppocc.newInstance(o)); - } - return list; + try { + for (Object o : toSerializedList()) { + list.add(ppocc.newInstance(o)); + } + return list; } catch (Exception ignored) { - } - return null; - } - - private static Class cs = NMSUtils.getNMSClassSilent("ChatSerializer", "IChatBaseComponent"), icbc = NMSUtils.getNMSClassSilent("IChatBaseComponent"), ppoc = NMSUtils.getNMSClassSilent("PacketPlayOutChat"), pc = NMSUtils.getNMSClassSilent("PlayerConnection"), - p = NMSUtils.getNMSClassSilent("Packet"), ep = NMSUtils.getNMSClassSilent("EntityPlayer"); - private static Method a = NMSUtils.getMethodSilent(cs, "a", String.class), sp = NMSUtils.getMethodSilent(pc, "sendPacket", p); - private static Field ppc = NMSUtils.getFieldSilent(ep, "playerConnection"); - private static Constructor ppocc = NMSUtils.getConstructorSilent(ppoc, icbc); - private static boolean b = check(cs, icbc, ppoc, pc, p, ep, a, sp, ppc, ppocc); - - private static boolean check(Object... o){ - for(Object a : o){ - if(a == null) - return false; - } - return true; - } - - private static void send(Player player, JSONFormatter jf){ - if(!jf.newline){ - send1(player, jf); - }else if(b){ - try{ - Object entityplayer = NMSUtils.getHandle(player); - Object ppco = ppc.get(entityplayer); - sp.invoke(ppco, jf.getPacket()); - } catch(Exception e){ - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON()); - } - }else{ - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON()); - } - } - - private static void send1(Player player, JSONFormatter jf){ - if(b){ - try{ - Object entityplayer = NMSUtils.getHandle(player); - Object ppco = ppc.get(entityplayer); - List packets = jf.getPacketList(); - List jsons = null; - for(int i = 0; i < packets.size(); i++){ - try{ - sp.invoke(ppco, packets.get(i)); - }catch(Exception e){ - if(jsons == null){ - jsons = jf.toJSONList(); - } - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jsons.get(i)); - } - } - }catch(Exception e){ - e.printStackTrace(); - } - }else{ - for(String json : jf.toJSONList()){ - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + json); - } - } - } - - private class Builder{ - - private StringBuilder sb = new StringBuilder(""); - private boolean bold = false, italic = false, magic = false, strikethrough = false, underline = false, changed = false; - - public Builder(){ - } - - public Builder(Builder b){ - bold = b.bold; - italic = b.italic; - magic = b.magic; - strikethrough = b.strikethrough; - underline = b.underline; - } - - public void append(char c){ - sb.append(c); - changed = true; - } - - private JSONObject toString(String color, BuilderHelper bh){ - String string = sb.toString(); - if(!changed) - return null; - if(string.length() == 0) - return null; - JSONObject jo = new JSONObject(); - try{ - if(!color.equals("")) - jo.put("color", color); - if(bold) - jo.put("bold", true); - if(italic) - jo.put("italic", true); - if(magic) - jo.put("obfuscated", true); - if(strikethrough) - jo.put("strikethrough", true); - if(underline) - jo.put("underlined", true); - bh.add(jo); - jo.put("text", string); - }catch(Exception e){ - e.printStackTrace(); - } - return jo; - } - - public JSONObject toString(String color){ - return toString(color, new BuilderHelper(){ - @Override + } + return null; + } + + private static Class cs = NMSUtils.getNMSClassSilent("ChatSerializer", "IChatBaseComponent"); + private static Class icbc = NMSUtils.getNMSClassSilent("IChatBaseComponent"); + private static Class ppoc = NMSUtils.getNMSClassSilent("PacketPlayOutChat"); + private static Class pc = NMSUtils.getNMSClassSilent("PlayerConnection"); + private static Class p = NMSUtils.getNMSClassSilent("Packet"); + private static Class ep = NMSUtils.getNMSClassSilent("EntityPlayer"); + private static Method a = NMSUtils.getMethodSilent(cs, "a", String.class), sp = NMSUtils.getMethodSilent(pc, "sendPacket", p); + private static Field ppc = NMSUtils.getFieldSilent(ep, "playerConnection"); + private static Constructor ppocc = NMSUtils.getConstructorSilent(ppoc, icbc); + private static boolean b = check(cs, icbc, ppoc, pc, p, ep, a, sp, ppc, ppocc); + + private static boolean check(Object... o) { + for (Object a : o) { + if (a == null) + return false; + } + return true; + } + + private static void send(Player player, JSONFormatter jf) { + if (!jf.newline) { + send1(player, jf); + } else if (b) { + try { + Object entityplayer = NMSUtils.getHandle(player); + Object ppco = ppc.get(entityplayer); + sp.invoke(ppco, jf.getPacket()); + } catch (Exception e) { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON()); + } + } else { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON()); + } + } + + private static void send1(Player player, JSONFormatter jf) { + if (b) { + try { + Object entityplayer = NMSUtils.getHandle(player); + Object ppco = ppc.get(entityplayer); + List packets = jf.getPacketList(); + List jsons = null; + for (int i = 0; i < packets.size(); i++) { + try { + sp.invoke(ppco, packets.get(i)); + } catch (Exception e) { + if (jsons == null) { + jsons = jf.toJSONList(); + } + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jsons.get(i)); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } else { + for (String json : jf.toJSONList()) { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + json); + } + } + } + + private class Builder { + + private StringBuilder sb = new StringBuilder(""); + private boolean bold = false, italic = false, magic = false, strikethrough = false, underline = false, changed = false; + + public Builder() { + } + + public Builder(Builder b) { + bold = b.bold; + italic = b.italic; + magic = b.magic; + strikethrough = b.strikethrough; + underline = b.underline; + } + + public void append(char c) { + sb.append(c); + changed = true; + } + + private JSONObject toString(String color, BuilderHelper bh) { + String string = sb.toString(); + if (!changed) + return null; + if (string.length() == 0) + return null; + JSONObject jo = new JSONObject(); + try { + if (!color.equals("")) + jo.put("color", color); + if (bold) + jo.put("bold", true); + if (italic) + jo.put("italic", true); + if (magic) + jo.put("obfuscated", true); + if (strikethrough) + jo.put("strikethrough", true); + if (underline) + jo.put("underlined", true); + bh.add(jo); + jo.put("text", string); + } catch (Exception e) { + e.printStackTrace(); + } + return jo; + } + + public JSONObject toString(String color) { + return toString(color, new BuilderHelper() { + @Override public void add(JSONObject jo) { - } - }); - } - - public JSONObject toStringHover(String color, final HoverEvent event){ - return toString(color, new BuilderHelper(){ - @Override - public void add(JSONObject jo) throws Exception{ - if(event.getEvent().length() > 1) - jo.put("hoverEvent", event.getEvent()); - } - }); - } - - public JSONObject toStringClick(String color, final ClickEvent event){ - return toString(color, new BuilderHelper(){ - @Override - public void add(JSONObject jo) throws Exception{ - if(event.getEvent().length() > 1) - jo.put("clickEvent", event.getEvent()); - } - }); - } - - public JSONObject toStringHoverClick(String color, final HoverEvent hevent, final ClickEvent cevent){ - return toString(color, new BuilderHelper(){ - @Override - public void add(JSONObject jo) throws Exception{ - if(hevent.getEvent().length() > 1) - jo.put("hoverEvent", hevent.getEvent()); - if(cevent.getEvent().length() > 1) - jo.put("clickEvent", cevent.getEvent()); - } - }); - } - - } - - private abstract class BuilderMaker{ - public abstract JSONObject make(); - } - - private abstract class BuilderHelper{ - public abstract void add(JSONObject jo) throws Exception; - } + } + }); + } + + public JSONObject toStringHover(String color, final HoverEvent event) { + return toString(color, new BuilderHelper() { + @Override + public void add(JSONObject jo) throws Exception { + if (event.getEvent().length() > 1) + jo.put("hoverEvent", event.getEvent()); + } + }); + } + + public JSONObject toStringClick(String color, final ClickEvent event) { + return toString(color, new BuilderHelper() { + @Override + public void add(JSONObject jo) throws Exception { + if (event.getEvent().length() > 1) + jo.put("clickEvent", event.getEvent()); + } + }); + } + + public JSONObject toStringHoverClick(String color, final HoverEvent hevent, final ClickEvent cevent) { + return toString(color, new BuilderHelper() { + @Override + public void add(JSONObject jo) throws Exception { + if (hevent.getEvent().length() > 1) + jo.put("hoverEvent", hevent.getEvent()); + if (cevent.getEvent().length() > 1) + jo.put("clickEvent", cevent.getEvent()); + } + }); + } + + } + + private abstract class BuilderMaker { + public abstract JSONObject make(); + } + + private abstract class BuilderHelper { + public abstract void add(JSONObject jo) throws Exception; + } } diff --git a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerJump.java b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerJump.java index c8306c8..659efd7 100644 --- a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerJump.java +++ b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerJump.java @@ -1,7 +1,6 @@ package me.skymc.taboolib.listener; -import java.util.HashMap; - +import me.skymc.taboolib.events.PlayerJumpEvent; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; @@ -13,48 +12,40 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; -import me.skymc.taboolib.events.PlayerJumpEvent; +import java.util.HashMap; -public class ListenerPlayerJump - implements Listener -{ - public HashMap cooldown = new HashMap<>(); - - @EventHandler(priority=EventPriority.HIGH) - public void onJump(PlayerMoveEvent event) - { - if ((!event.getPlayer().isFlying()) && (event.getPlayer().getGameMode() != GameMode.CREATIVE) && (event.getFrom().getY() + 0.5D != event.getTo().getY()) && (event.getFrom().getY() + 0.419D < event.getTo().getY())) { - Location loc = event.getFrom(); - loc.setY(event.getFrom().getY() - 1.0D); - if (loc.getBlock().getType() != Material.AIR) - { - if (!this.cooldown.containsKey(event.getPlayer())) - { - this.cooldown.put(event.getPlayer(), System.currentTimeMillis() + 350L); - PlayerJumpEvent evt = new PlayerJumpEvent(event.isCancelled(), event.getPlayer()); - Bukkit.getPluginManager().callEvent(evt); - if (evt.isCancelled()) - { - event.setCancelled(true); - } - } else if (this.cooldown.get(event.getPlayer()) <= System.currentTimeMillis()) - { - this.cooldown.put(event.getPlayer(), System.currentTimeMillis() + 350L); - PlayerJumpEvent evt = new PlayerJumpEvent(event.isCancelled(), event.getPlayer()); +public class ListenerPlayerJump implements Listener { - Bukkit.getPluginManager().callEvent(evt); - if (evt.isCancelled()) - { - event.setCancelled(true); - } - } - } - } - } - - @EventHandler - public void onQuit(PlayerQuitEvent event) - { - this.cooldown.remove(event.getPlayer()); - } + public HashMap cooldown = new HashMap<>(); + + @EventHandler(priority = EventPriority.HIGH) + public void onJump(PlayerMoveEvent event) { + if ((!event.getPlayer().isFlying()) && (event.getPlayer().getGameMode() != GameMode.CREATIVE) && (event.getFrom().getY() + 0.5D != event.getTo().getY()) && (event.getFrom().getY() + 0.419D < event.getTo().getY())) { + Location loc = event.getFrom(); + loc.setY(event.getFrom().getY() - 1.0D); + if (loc.getBlock().getType() != Material.AIR) { + if (!this.cooldown.containsKey(event.getPlayer())) { + this.cooldown.put(event.getPlayer(), System.currentTimeMillis() + 350L); + PlayerJumpEvent evt = new PlayerJumpEvent(event.isCancelled(), event.getPlayer()); + Bukkit.getPluginManager().callEvent(evt); + if (evt.isCancelled()) { + event.setCancelled(true); + } + } else if (this.cooldown.get(event.getPlayer()) <= System.currentTimeMillis()) { + this.cooldown.put(event.getPlayer(), System.currentTimeMillis() + 350L); + PlayerJumpEvent evt = new PlayerJumpEvent(event.isCancelled(), event.getPlayer()); + + Bukkit.getPluginManager().callEvent(evt); + if (evt.isCancelled()) { + event.setCancelled(true); + } + } + } + } + } + + @EventHandler + public void onQuit(PlayerQuitEvent event) { + this.cooldown.remove(event.getPlayer()); + } } diff --git a/src/main/java/me/skymc/taboolib/listener/ListenerPluginDisable.java b/src/main/java/me/skymc/taboolib/listener/ListenerPluginDisable.java index 119744d..37732f9 100644 --- a/src/main/java/me/skymc/taboolib/listener/ListenerPluginDisable.java +++ b/src/main/java/me/skymc/taboolib/listener/ListenerPluginDisable.java @@ -1,59 +1,57 @@ package me.skymc.taboolib.listener; -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.scheduler.BukkitRunnable; - import me.skymc.taboolib.Main; import me.skymc.taboolib.message.MsgUtils; import me.skymc.taboolib.mysql.MysqlUtils; import me.skymc.taboolib.mysql.protect.MySQLConnection; import me.skymc.taboolib.timecycle.TimeCycleManager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.List; public class ListenerPluginDisable implements Listener { - - @EventHandler - public void disable(PluginDisableEvent e) { - // 注销时间周期 - TimeCycleManager.cancel(e.getPlugin()); - - // 获取连接 - List conns = new ArrayList<>(); - for (MySQLConnection conn : MysqlUtils.CONNECTIONS) { - if (conn.getPlugin().equals(e.getPlugin())) { - conns.add(conn); - MysqlUtils.CONNECTIONS.remove(conn); - } - } - - // 异步注销 - BukkitRunnable runnable = new BukkitRunnable() { - - @Override - public void run() { - int i = 0; - for (MySQLConnection conn : conns) { - conn.setFallReconnection(false); - conn.closeConnection(); - i++; - } - if (i > 0) { - MsgUtils.send("已停止插件 &f" + e.getPlugin().getName() + "&7 的 &f" + i + "&7 条数据库连接"); - } - } - }; - - // 如果插件关闭 - try { - runnable.runTaskLater(Main.getInst(), 40); - } - catch (Exception err) { - MsgUtils.warn("异步任务失败, 执行方式改为同步执行"); - runnable.run(); - } - } + + @EventHandler + public void disable(PluginDisableEvent e) { + // 注销时间周期 + TimeCycleManager.cancel(e.getPlugin()); + + // 获取连接 + List conns = new ArrayList<>(); + for (MySQLConnection conn : MysqlUtils.CONNECTIONS) { + if (conn.getPlugin().equals(e.getPlugin())) { + conns.add(conn); + MysqlUtils.CONNECTIONS.remove(conn); + } + } + + // 异步注销 + BukkitRunnable runnable = new BukkitRunnable() { + + @Override + public void run() { + int i = 0; + for (MySQLConnection conn : conns) { + conn.setFallReconnection(false); + conn.closeConnection(); + i++; + } + if (i > 0) { + MsgUtils.send("已停止插件 &f" + e.getPlugin().getName() + "&7 的 &f" + i + "&7 条数据库连接"); + } + } + }; + + // 如果插件关闭 + try { + runnable.runTaskLater(Main.getInst(), 40); + } catch (Exception err) { + MsgUtils.warn("异步任务失败, 执行方式改为同步执行"); + runnable.run(); + } + } } diff --git a/src/main/java/me/skymc/taboolib/location/LocationUtils.java b/src/main/java/me/skymc/taboolib/location/LocationUtils.java index 21ae208..6854edb 100644 --- a/src/main/java/me/skymc/taboolib/location/LocationUtils.java +++ b/src/main/java/me/skymc/taboolib/location/LocationUtils.java @@ -6,62 +6,59 @@ import org.bukkit.Material; import org.bukkit.block.Block; public class LocationUtils { - - /** - * 序列化 - * - * @param location - * @return - */ - public static String fromString(Location location) { - return location.getWorld().getName() + "," + location.getX() + "," + location.getY() + "," + location.getZ() + "," + location.getYaw() + "," + location.getPitch(); - } - - /** - * 反序列化 - * - * @param string - * @return - */ - public static Location toString(String string) { - Location location = new Location(null, 0, 0, 0); - try { - location.setWorld(Bukkit.getWorld(string.split(",")[0])); - location.setX(Double.valueOf(string.split(",")[1])); - location.setY(Double.valueOf(string.split(",")[2])); - location.setZ(Double.valueOf(string.split(",")[3])); - location.setYaw(Float.valueOf(string.split(",")[4])); - location.setPitch(Float.valueOf(string.split(",")[5])); - } - catch (Exception e) { - // TODO: handle exception - } - return location; - } - - public static double getBetween(Location l1, Location l2) { - if (l1.getWorld().equals(l2.getWorld())) { - return Math.ceil(l1.distance(l2)); - } - return -1D; - } - - @Deprecated - public static Block findBlockByLocation(Location l) { - while(l.getY() < 255 && l.getBlock().getType() != Material.AIR) { - l.add(0, 1, 0); + + /** + * 序列化 + * + * @param location + * @return + */ + public static String fromString(Location location) { + return location.getWorld().getName() + "," + location.getX() + "," + location.getY() + "," + location.getZ() + "," + location.getYaw() + "," + location.getPitch(); + } + + /** + * 反序列化 + * + * @param string + * @return + */ + public static Location toString(String string) { + Location location = new Location(null, 0, 0, 0); + try { + location.setWorld(Bukkit.getWorld(string.split(",")[0])); + location.setX(Double.valueOf(string.split(",")[1])); + location.setY(Double.valueOf(string.split(",")[2])); + location.setZ(Double.valueOf(string.split(",")[3])); + location.setYaw(Float.valueOf(string.split(",")[4])); + location.setPitch(Float.valueOf(string.split(",")[5])); + } catch (Exception e) { + // TODO: handle exception } + return location; + } + + public static double getBetween(Location l1, Location l2) { + if (l1.getWorld().equals(l2.getWorld())) { + return Math.ceil(l1.distance(l2)); + } + return -1D; + } + + @Deprecated + public static Block findBlockByLocation(Location l) { + while (l.getY() < 255 && l.getBlock().getType() != Material.AIR) l.add(0, 1, 0); return l.getY() < 255 && l.getBlock().getType() == Material.AIR ? l.getBlock() : null; } - - @Deprecated - public static String formatToString(Location l) { - return l.getWorld().getName() + "," + String.valueOf(l.getX()).replace(".", "#") + "," + String.valueOf(l.getY()).replace(".", "#") + "," + String.valueOf(l.getZ()).replace(".", "#"); - } - @Deprecated - public static Location parsedToLocation(String string) { - String[] values = string.split(","); - return new Location(Bukkit.getWorld(values[0]), Double.valueOf(values[1].replace("#", ".")), Double.valueOf(values[2].replace("#", ".")), Double.valueOf(values[3].replace("#", "."))); - } + @Deprecated + public static String formatToString(Location l) { + return l.getWorld().getName() + "," + String.valueOf(l.getX()).replace(".", "#") + "," + String.valueOf(l.getY()).replace(".", "#") + "," + String.valueOf(l.getZ()).replace(".", "#"); + } + + @Deprecated + public static Location parsedToLocation(String string) { + String[] values = string.split(","); + return new Location(Bukkit.getWorld(values[0]), Double.valueOf(values[1].replace("#", ".")), Double.valueOf(values[2].replace("#", ".")), Double.valueOf(values[3].replace("#", "."))); + } } diff --git a/src/main/java/me/skymc/taboolib/message/ChatCatcher.java b/src/main/java/me/skymc/taboolib/message/ChatCatcher.java index 2ed8bad..125bd58 100644 --- a/src/main/java/me/skymc/taboolib/message/ChatCatcher.java +++ b/src/main/java/me/skymc/taboolib/message/ChatCatcher.java @@ -1,69 +1,68 @@ package me.skymc.taboolib.message; -import java.util.HashMap; -import java.util.LinkedList; - import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerQuitEvent; -import lombok.Getter; +import java.util.HashMap; +import java.util.LinkedList; public class ChatCatcher implements Listener { - - @Getter - private static HashMap> playerdata = new HashMap<>(); - - public static boolean contains(Player player) { - return playerdata.containsKey(player.getName()) && playerdata.get(player.getName()).size() > 0; - } - - public static void call(Player player, Catcher catcher) { - if (!playerdata.containsKey(player.getName())) { - playerdata.put(player.getName(), new LinkedList<>()); - } - playerdata.get(player.getName()).add(catcher.before()); - } - - @EventHandler - public void quit(PlayerQuitEvent e) { - playerdata.remove(e.getPlayer().getName()); - } - - @EventHandler - public void chat(AsyncPlayerChatEvent e) { - if (playerdata.containsKey(e.getPlayer().getName()) && playerdata.get(e.getPlayer().getName()).size() > 0) { - e.setCancelled(true); - - if (e.getMessage().equalsIgnoreCase("quit()")) { - // 退出引导 - playerdata.get(e.getPlayer().getName()).removeFirst().cancel(); - // 清理数据 - clearData(e.getPlayer()); - } - else { - Catcher catcher = playerdata.get(e.getPlayer().getName()).getFirst(); - // 如果终止引导 - if (!catcher.after(e.getMessage())) { - // 移除 - playerdata.get(e.getPlayer().getName()).removeFirst(); - // 清理 - clearData(e.getPlayer()); - } - else { - catcher.before(); - } - } - } - } - - private void clearData(Player player) { - if (playerdata.containsKey(player.getName()) && playerdata.get(player.getName()).size() == 0) { - playerdata.remove(player.getName()); - } - } + + private static HashMap> playerdata = new HashMap<>(); + + public static HashMap> getPlayerdata() { + return playerdata; + } + + public static boolean contains(Player player) { + return playerdata.containsKey(player.getName()) && playerdata.get(player.getName()).size() > 0; + } + + public static void call(Player player, Catcher catcher) { + if (!playerdata.containsKey(player.getName())) { + playerdata.put(player.getName(), new LinkedList<>()); + } + playerdata.get(player.getName()).add(catcher.before()); + } + + @EventHandler + public void quit(PlayerQuitEvent e) { + playerdata.remove(e.getPlayer().getName()); + } + + @EventHandler + public void chat(AsyncPlayerChatEvent e) { + if (playerdata.containsKey(e.getPlayer().getName()) && playerdata.get(e.getPlayer().getName()).size() > 0) { + e.setCancelled(true); + + if (e.getMessage().equalsIgnoreCase("quit()")) { + // 退出引导 + playerdata.get(e.getPlayer().getName()).removeFirst().cancel(); + // 清理数据 + clearData(e.getPlayer()); + } else { + Catcher catcher = playerdata.get(e.getPlayer().getName()).getFirst(); + // 如果终止引导 + if (!catcher.after(e.getMessage())) { + // 移除 + playerdata.get(e.getPlayer().getName()).removeFirst(); + // 清理 + clearData(e.getPlayer()); + } else { + catcher.before(); + } + } + } + } + + private void clearData(Player player) { + if (playerdata.containsKey(player.getName()) && playerdata.get(player.getName()).size() == 0) { + playerdata.remove(player.getName()); + } + } public interface Catcher { @@ -72,5 +71,5 @@ public class ChatCatcher implements Listener { boolean after(String message); void cancel(); - } + } } diff --git a/src/main/java/me/skymc/taboolib/message/MsgUtils.java b/src/main/java/me/skymc/taboolib/message/MsgUtils.java index 75dcb0f..2b881e8 100644 --- a/src/main/java/me/skymc/taboolib/message/MsgUtils.java +++ b/src/main/java/me/skymc/taboolib/message/MsgUtils.java @@ -1,73 +1,72 @@ package me.skymc.taboolib.message; +import me.skymc.taboolib.Main; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.plugin.Plugin; -import me.skymc.taboolib.Main; +public class MsgUtils { -public class MsgUtils{ - - public static void send(CommandSender sender, String s) { - sender.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - public static void send(org.bukkit.entity.Player player, String s) { - player.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - public static void send(String s) { - Bukkit.getConsoleSender().sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - public static void warn(String s) { - warn(s, Main.getInst()); - } - - public static void send(String s, Plugin plugin) { - Bukkit.getConsoleSender().sendMessage("§8[§3" + plugin.getName() + "§8] §7" + s.replaceAll("&", "§")); - } - - public static void warn(String s, Plugin plugin) { - Bukkit.getConsoleSender().sendMessage("§4[§c" + plugin.getName() + "§4][WARN #!] §c" + s.replaceAll("&", "§")); - } - - @Deprecated - public static void Console(String s) { - Bukkit.getConsoleSender().sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - @Deprecated - public static void System(String s) { - System.out.println("[TabooLib] " + s); - } - - @Deprecated - public static void Sender(CommandSender p, String s) { - p.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - @Deprecated - public static void Player(org.bukkit.entity.Player p, String s) { - p.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); - } - - @Deprecated - public static String noPe() { - String s = Main.getInst().getConfig().getString("NO-PERMISSION-MESSAGE").replaceAll("&", "§"); - if (s.equals("")) { - s = "§cCONFIG ERROR §8(NO-PERMISSION-MESSAGE)"; - } - return s; - } - - @Deprecated - public static String noClaim(String a) { - String s = Main.getInst().getConfig().getString("NO-CLAIM-MESSAGE").replaceAll("&", "§").replaceAll("%s%", a); - if (s.equals("")) { - s = "§cCONFIG ERROR §8(NO-CLAIM-MESSAGE)"; - } - return s; - } + public static void send(CommandSender sender, String s) { + sender.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); + } + + public static void send(org.bukkit.entity.Player player, String s) { + player.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); + } + + public static void send(String s) { + Bukkit.getConsoleSender().sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); + } + + public static void warn(String s) { + warn(s, Main.getInst()); + } + + public static void send(String s, Plugin plugin) { + Bukkit.getConsoleSender().sendMessage("§8[§3" + plugin.getName() + "§8] §7" + s.replaceAll("&", "§")); + } + + public static void warn(String s, Plugin plugin) { + Bukkit.getConsoleSender().sendMessage("§4[§c" + plugin.getName() + "§4][WARN #!] §c" + s.replaceAll("&", "§")); + } + + @Deprecated + public static void Console(String s) { + Bukkit.getConsoleSender().sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); + } + + @Deprecated + public static void System(String s) { + System.out.println("[TabooLib] " + s); + } + + @Deprecated + public static void Sender(CommandSender p, String s) { + p.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); + } + + @Deprecated + public static void Player(org.bukkit.entity.Player p, String s) { + p.sendMessage(Main.getPrefix() + s.replaceAll("&", "§")); + } + + @Deprecated + public static String noPe() { + String s = Main.getInst().getConfig().getString("NO-PERMISSION-MESSAGE").replaceAll("&", "§"); + if (s.equals("")) { + s = "§cCONFIG ERROR §8(NO-PERMISSION-MESSAGE)"; + } + return s; + } + + @Deprecated + public static String noClaim(String a) { + String s = Main.getInst().getConfig().getString("NO-CLAIM-MESSAGE").replaceAll("&", "§").replaceAll("%s%", a); + if (s.equals("")) { + s = "§cCONFIG ERROR §8(NO-CLAIM-MESSAGE)"; + } + return s; + } } 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 1b2fdfe..0069c43 100644 --- a/src/main/java/me/skymc/taboolib/mysql/protect/MySQLConnection.java +++ b/src/main/java/me/skymc/taboolib/mysql/protect/MySQLConnection.java @@ -1,820 +1,848 @@ package me.skymc.taboolib.mysql.protect; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +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 org.bukkit.plugin.Plugin; - -import lombok.Getter; -import lombok.Setter; -import me.skymc.taboolib.Main; - public class MySQLConnection { - - @Getter - private String url; - @Getter - private String user; - @Getter - private String port; - @Getter - private String password; - @Getter - private String database; - @Getter - private String connectionUrl; - @Getter - private Connection connection; - @Getter - @Setter - private Plugin plugin; - @Getter - @Setter - private boolean fallReconnection = true; - - private int recheck = 10; - private Thread recheckThread; - - public MySQLConnection(String url, String user, String port, String password, String database) { - this(url, user, port, password, database, 10, Main.getInst()); - } - - public MySQLConnection(String url, String user, String port, String password, String database, int recheck, Plugin plugin) { - // 检查驱动 - if (!loadDriverMySQL()) { - print("驱动器获取失败, 无法连接到数据库"); - return; - } - - // 设置信息 - this.plugin = plugin; - this.recheck = recheck; - - // 设置数据 - this.url = url == null ? "localhost" : url; - this.user = user == null ? "root" : user; - this.port = port == null ? "3306" : port; - this.password = password == null ? "" : password; - this.database = database == null ? "test" : database; - this.connectionUrl = "jdbc:mysql://" + this.url + ":" + this.port + "/" + this.database + "?characterEncoding=utf-8&useSSL=false"; - - // 连接数据库 - connect(); - - // 断线检测 - recheckThread = new Thread(() -> { - while (!Main.isDisable()) { - try { - Thread.sleep(getReCheckSeconds() * 1000); - if (connection == null) { - print("警告! 数据库尚未连接, 请检查配置文件后重启服务器! (" + (plugin.getName()) + ")"); - } else { - isExists("taboolib"); - } - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - } - } - }); - - // 启动检测 - if (isConnection()) { - recheckThread.start(); - print("启动数据库连接监控"); - } - } - - public void setReCheckSeconds(int s) { - this.recheck = s; - } - - public int getReCheckSeconds() { - return recheck; - } - - public boolean isConnection() { - try { - if (connection == null || connection.isClosed()) { - return false; - } - } catch (SQLException e) { - return false; - } - return true; - } - - @SuppressWarnings("deprecation") - public void closeConnection() { - try { - connection.close(); - } catch (Exception e) { - // - } - try { - recheckThread.stop(); - } catch (Exception e) { - // - } - } - - public boolean deleteTable(String name) { - return execute("drop table if exists " + name); - } - - /** - * 2018年1月17日 新增, TabooLib 版本 3.25 - */ - public boolean truncateTable(String name) { - return execute("truncate table " + name); - } - - public boolean clearTable(String name) { - return execute("delete from " + name); - } - - public boolean renameTable(String name, String newName) { - return execute("rename table `" + name + "` to `" + newName + "`"); - } - - public boolean deleteColumn(String name, String column) { - return execute("alter table `" + name + "` drop `" + column + "`"); - } - - public void addColumn(String name, Column... columns) { - for (Column column : columns) { - execute("alter table " + name + " add " + column.toString()); - } - } - - public boolean addColumn(String name, String column) { - if (!column.contains("/")) { - return execute("alter table " + name + " add `" + column + "` text"); - } - return execute("alter table " + name + " add `" + column.split("/")[0] + "` " + column.split("/")[1]); - } - - public boolean editColumn(String name, String oldColumn, Column newColumn) { - return execute("alter table " + name + " change `" + 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("alter table " + name + " change `" + oldColumn + "` `" + newColumn.split("/")[0] + "` " + newColumn.split("/")[1]); - } - - /** - * 删除数据 - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @return boolean - */ - public boolean deleteValue(String name, String column, Object columnValue) { - PreparedStatement pstmt = null; - ResultSet resultSet = null; - try { - pstmt = connection.prepareStatement("delete from `" + name + "` where `" + column + "` = ?"); - pstmt.setObject(1, columnValue); - pstmt.executeUpdate(); - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - return false; - } - - /** - * 写入数据 - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @param value 数据值 - * @return boolean - */ - public boolean setValue(String name, String column, Object columnValue, String valueColumn, Object value) { - return setValue(name, column, columnValue, valueColumn, value, false); - } - - /** - * 写入数据 - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @param value 数据值 - * @param append 是否追加(数据列类型必须为数字) - * @return boolean - */ - public boolean setValue(String name, String column, Object columnValue, String valueColumn, Object value, boolean append) { - PreparedStatement pstmt = null; - ResultSet resultSet = null; - try { - if (append) { - pstmt = connection.prepareStatement("update `" + name + "` set `" + valueColumn + "` = `" + valueColumn + "` + ? where `" + column + "` = ?"); - } else { - pstmt = connection.prepareStatement("update `" + name + "` set `" + valueColumn + "` = ? where `" + column + "` = ?"); - } - pstmt.setObject(1, value); - pstmt.setObject(2, columnValue); - pstmt.executeUpdate(); - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - return false; - } - - /** - * 插入数据 - * - * @param name 名称 - * @param values 值 - * @return boolean - */ - public boolean intoValue(String name, Object... values) { - StringBuilder sb = new StringBuilder(); - for (Object value : values) { - sb.append("?, "); - } - PreparedStatement pstmt = null; - ResultSet resultSet = null; - try { - pstmt = connection.prepareStatement("insert into `" + name + "` values(null, " + sb.substring(0, sb.length() - 2) + ")"); - for (int i = 0 ; i < values.length ; i++) { - pstmt.setObject(i + 1, values[i]); - } - pstmt.executeUpdate(); - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - return false; - } - - /** - * 创建数据表 - * - * @param name 名称 - * @param columns 列表 - * @return boolean - */ - 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) + ")"); - } - - /** - * 创建数据表 - * - * @param name 名称 - * @param columns 列表 - * @return boolean - */ - public boolean createTable(String name, String... columns) { - StringBuilder sb = new StringBuilder(); - for (String column : columns) { - if (!column.contains("/")) { - sb.append("`").append(column).append("` text, "); - } else { - sb.append("`").append(column.split("/")[0]).append("` ").append(column.split("/")[1]).append(", "); - } - } - return execute("create table if not exists " + name + " (id int(1) not null primary key auto_increment, " + sb.substring(0, sb.length() - 2) + ")"); - } - - /** - * 检查数据表是否存在 - * - * @param name 名称 - * @return boolean - */ - public boolean isExists(String name) { - PreparedStatement pstmt = 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(); - while (resultSet.next()) { - return true; - } - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - return false; - } - - /** - * 检查数据是否存在 - * - * @param name 名称 - * @param column 列表名 - * @param columnValue 列表值 - * @return boolean - */ - public boolean isExists(String name, String column, Object columnValue) { - PreparedStatement pstmt = null; - ResultSet resultSet = null; - try { - pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ?"); - pstmt.setObject(1, columnValue); - resultSet = pstmt.executeQuery(); - while (resultSet.next()) { - return true; - } - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - return false; - } - - /** - * 获取所有列表名称(不含主键) - * - * @param name 名称 - * @return {@link List} - */ - public List getColumns(String name) { - return getColumns(name, false); - } - - /** - * 获取所有列表名称 - * - * @param name 名称 - * @param primary 是否获取主键 - * @return {@link List} - */ - public List getColumns(String name, boolean primary) { - List list = new ArrayList<>(); - PreparedStatement pstmt = 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(); - while (resultSet.next()) { - list.add(resultSet.getString(1)); - } - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - // 是否获取主键 - if (!primary) { - list.remove("id"); - } - return list; - } - - /** - * 获取单项数据 - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @return Object - */ - public Object getValue(String name, String column, Object columnValue, String valueColumn) { - PreparedStatement pstmt = null; - ResultSet resultSet = null; - try { - pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? limit 1"); - pstmt.setObject(1, columnValue); - resultSet = pstmt.executeQuery(); - while (resultSet.next()) { - return resultSet.getObject(valueColumn); - } - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - return null; - } - - /** - * 获取单项数据(根据主键倒叙排列后的最后一项) - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @return Object - */ - public Object getValueLast(String name, String column, Object columnValue, String valueColumn) { - PreparedStatement pstmt = 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(); - while (resultSet.next()) { - return resultSet.getObject(valueColumn); - } - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - return null; - } - - /** - * 获取多项数据(根据主键倒叙排列后的最后一项) - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @return {@link HashMap} - */ - public HashMap getValueLast(String name, String column, Object columnValue, String... valueColumn) { - HashMap map = new HashMap<>(); - PreparedStatement pstmt = 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(); - while (resultSet.next()) { - for (String _column : valueColumn) { - map.put(_column, resultSet.getObject(_column)); - } - break; - } - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - return map; - } - - /** - * 获取多项数据(单项多列) - * - * @param name 名称 - * @param column 参考列 - * @param columnValue 参考值 - * @param valueColumn 数据列 - * @return {@link HashMap} - */ - public HashMap getValue(String name, String column, Object columnValue, String... valueColumn) { - HashMap map = new HashMap<>(); - PreparedStatement pstmt = null; - ResultSet resultSet = null; - try { - pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? limit 1"); - pstmt.setObject(1, columnValue); - resultSet = pstmt.executeQuery(); - while (resultSet.next()) { - for (String _column : valueColumn) { - map.put(_column, resultSet.getObject(_column)); - } - break; - } - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - return map; - } - - /** - * 获取多项数据(单列多列) - * - * @param name 名称 - * @param column 参考列 - * @param size 获取数量(-1 为无限制) - * @return {@link List} - */ - public List getValues(String name, String column, int size) { - return getValues(name, column, size, false); - } - - /** - * 获取多项数据(单列多列) - * - * @param name 名称 - * @param column 参考列 - * @param size 获取数量(-1 位无限制) - * @param desc 是否倒序 - * @return {@link List} - */ - public List getValues(String name, String column, int size, boolean desc) { - List list = new LinkedList<>(); - PreparedStatement pstmt = null; - ResultSet resultSet = null; - try { - if (desc) { - pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + column + "` desc " + (size < 0 ? "" : " limit " + size)); - } else { - pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + column + "` " + (size < 0 ? "" : " limit " + size)); - } - resultSet = pstmt.executeQuery(); - while (resultSet.next()) { - list.add(resultSet.getObject(column)); - } - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - return list; - } - - /** - * 获取多线数据(多项多列) - * - * @param name 名称 - * @param sortColumn 参考列(该列类型必须为数字) - * @param size 获取数量(-1 为无限制) - * @param valueColumn 获取数据列 - * @return {@link LinkedList} - */ - public LinkedList> getValues(String name, String sortColumn, int size, String... valueColumn) { - return getValues(name, sortColumn, size, false, valueColumn); - } - - /** - * 获取多项数据(多项多列) - * - * @param name 名称 - * @param sortColumn 参考列(该列类型必须为数字) - * @param size 获取数量(-1 为无限制) - * @param desc 是否倒序 - * @param valueColumn 获取数据列 - * @return {@link LinkedList} - */ - public LinkedList> getValues(String name, String sortColumn, int size, boolean desc, String... valueColumn) { - LinkedList> list = new LinkedList<>(); - PreparedStatement pstmt = null; - ResultSet resultSet = null; - try { - if (desc) { - pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + sortColumn + "` desc" + (size < 0 ? "" : " limit " + size)); - } else { - pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + sortColumn + "`" + (size < 0 ? "" : " limit " + size)); - } - resultSet = pstmt.executeQuery(); - while (resultSet.next()) { - HashMap map = new HashMap<>(); - for (String _column : valueColumn) { - map.put(_column, resultSet.getObject(_column)); - } - list.add(map); - } - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - // 重新连接 - if (fallReconnection && e.getMessage().contains("closed")) { - connect(); - } - } finally { - freeResult(resultSet, pstmt); - } - return list; - } - - public boolean execute(String sql) { - PreparedStatement pstmt = null; - try { - pstmt = connection.prepareStatement(sql); - pstmt.execute(); - return true; - } catch (Exception e) { - print("数据库命令执行出错"); - print("错误原因: " + e.getMessage()); - print("错误命令: " + sql); - // 重连 - if (e.getMessage().contains("closed")) { - connect(); - } - return false; - } finally { - try { - if (pstmt != null) { - pstmt.close(); - } - } - catch (Exception e) { - // - } - } - } - - public boolean connect() { - try { - print("正在连接数据库"); - print("地址: " + connectionUrl); - long time = System.currentTimeMillis(); - connection = DriverManager.getConnection(connectionUrl, this.user, this.password); - print("数据库连接成功 (" + (System.currentTimeMillis() - time) + "ms)"); - return true; - } - catch (SQLException e) { - print("数据库连接失败"); - print("错误原因: " + e.getMessage()); - print("错误代码: " + e.getErrorCode()); - return false; - } - } - - public void print(String message) { - 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 boolean loadDriverMySQL() { - try { - Class.forName("com.mysql.jdbc.Driver"); - return true; - } - catch (ClassNotFoundException e) { - return false; - } - } + private String url; + private String user; + private String port; + private String password; + private String database; + private String connectionUrl; + private Connection connection; + private Plugin plugin; + private boolean fallReconnection = true; + private int recheck = 10; + private Thread recheckThread; - public enum ColumnInteger { + public String getUrl() { + return url; + } - TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT - } + public String getUser() { + return user; + } - public enum ColumnFloat { + public String getPort() { + return port; + } - FLOAT, DOUBLE - } + public String getPassword() { + return password; + } - public enum ColumnChar { + public String getDatabase() { + return database; + } - CHAR, VARCHAR - } + public String getConnectionUrl() { + return connectionUrl; + } - public enum ColumnString { + public Connection getConnection() { + return connection; + } - TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT - } - - public static class Column { - - private String name; - private Object type; - private int a; - private int b; - - public Column(String name) { - this.name = name; - this.type = ColumnString.TEXT; - } - - public Column(String name, ColumnInteger type) { - this(name); - this.type = type; - this.a = 12; - } - - public Column(String name, ColumnInteger type, int m) { - this(name); - this.type = type; - this.a = m; - } - - public Column(String name, ColumnFloat type, int m, int d) { - this(name); - this.type = type; - this.a = m; - this.b = d; - } - - public Column(String name, ColumnChar type, int n) { - this(name); - this.type = type; - this.a = n; - } - - public Column(String name, ColumnString type) { - this(name); - this.type = type; - } - - @Override - public String toString() { - if (type instanceof ColumnInteger || type instanceof ColumnChar) { - return "`" + name + "` " + type.toString().toLowerCase() + "(" + a + ")"; - } - else if (type instanceof ColumnFloat) { - return "`" + name + "` " + type.toString().toLowerCase() + "(" + a + "," + b + ")"; - } - else { - return "`" + name + "` " + type.toString().toLowerCase(); - } - } - } + public Plugin getPlugin() { + return plugin; + } + + public boolean isFallReconnection() { + return fallReconnection; + } + + public void setPlugin(Plugin plugin) { + this.plugin = plugin; + } + + public void setFallReconnection(boolean fallReconnection) { + this.fallReconnection = fallReconnection; + } + + public int getRecheck() { + return recheck; + } + + public Thread getRecheckThread() { + return recheckThread; + } + + public MySQLConnection(String url, String user, String port, String password, String database) { + this(url, user, port, password, database, 10, Main.getInst()); + } + + public MySQLConnection(String url, String user, String port, String password, String database, int recheck, Plugin plugin) { + // 检查驱动 + if (!loadDriverMySQL()) { + print("驱动器获取失败, 无法连接到数据库"); + return; + } + + // 设置信息 + this.plugin = plugin; + this.recheck = recheck; + + // 设置数据 + this.url = url == null ? "localhost" : url; + this.user = user == null ? "root" : user; + this.port = port == null ? "3306" : port; + this.password = password == null ? "" : password; + this.database = database == null ? "test" : database; + this.connectionUrl = "jdbc:mysql://" + this.url + ":" + this.port + "/" + this.database + "?characterEncoding=utf-8&useSSL=false"; + + // 连接数据库 + connect(); + + // 断线检测 + recheckThread = new Thread(() -> { + while (!Main.isDisable()) { + try { + Thread.sleep(getReCheckSeconds() * 1000); + + if (connection == null) { + print("警告! 数据库尚未连接, 请检查配置文件后重启服务器! (" + (plugin.getName()) + ")"); + } else { + isExists("taboolib"); + } + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + } + } + }); + + // 启动检测 + if (isConnection()) { + recheckThread.start(); + print("启动数据库连接监控"); + } + } + + public void setReCheckSeconds(int s) { + this.recheck = s; + } + + public int getReCheckSeconds() { + return recheck; + } + + public boolean isConnection() { + try { + if (connection == null || connection.isClosed()) { + return false; + } + } catch (SQLException e) { + return false; + } + return true; + } + + @SuppressWarnings("deprecation") + public void closeConnection() { + try { + connection.close(); + } catch (Exception e) { + // + } + try { + recheckThread.stop(); + } catch (Exception e) { + // + } + } + + public boolean deleteTable(String name) { + return execute("drop table if exists " + name); + } + + /** + * 2018年1月17日 新增, TabooLib 版本 3.25 + */ + public void truncateTable(String name) { + execute("truncate table " + name); + } + + public boolean clearTable(String name) { + return execute("delete from " + name); + } + + public boolean renameTable(String name, String newName) { + return execute("rename table `" + name + "` to `" + newName + "`"); + } + + public boolean deleteColumn(String name, String column) { + return execute("alter table `" + name + "` drop `" + column + "`"); + } + + public void addColumn(String name, Column... columns) { + for (Column column : columns) { + execute("alter table " + name + " add " + column.toString()); + } + } + + public boolean addColumn(String name, String column) { + if (!column.contains("/")) { + return execute("alter table " + name + " add `" + column + "` text"); + } + return execute("alter table " + name + " add `" + column.split("/")[0] + "` " + column.split("/")[1]); + } + + public boolean editColumn(String name, String oldColumn, Column newColumn) { + return execute("alter table " + name + " change `" + 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("alter table " + name + " change `" + oldColumn + "` `" + newColumn.split("/")[0] + "` " + newColumn.split("/")[1]); + } + + /** + * 删除数据 + * + * @param name 名称 + * @param column 参考列 + * @param columnValue 参考值 + * @return boolean + */ + public boolean deleteValue(String name, String column, Object columnValue) { + PreparedStatement pstmt = null; + ResultSet resultSet = null; + try { + pstmt = connection.prepareStatement("delete from `" + name + "` where `" + column + "` = ?"); + pstmt.setObject(1, columnValue); + pstmt.executeUpdate(); + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(null, pstmt); + } + return false; + } + + /** + * 写入数据 + * + * @param name 名称 + * @param column 参考列 + * @param columnValue 参考值 + * @param valueColumn 数据列 + * @param value 数据值 + * @return boolean + */ + public boolean setValue(String name, String column, Object columnValue, String valueColumn, Object value) { + return setValue(name, column, columnValue, valueColumn, value, false); + } + + /** + * 写入数据 + * + * @param name 名称 + * @param column 参考列 + * @param columnValue 参考值 + * @param valueColumn 数据列 + * @param value 数据值 + * @param append 是否追加(数据列类型必须为数字) + * @return boolean + */ + public boolean setValue(String name, String column, Object columnValue, String valueColumn, Object value, boolean append) { + PreparedStatement pstmt = null; + ResultSet resultSet = null; + try { + if (append) { + pstmt = connection.prepareStatement("update `" + name + "` set `" + valueColumn + "` = `" + valueColumn + "` + ? where `" + column + "` = ?"); + } else { + pstmt = connection.prepareStatement("update `" + name + "` set `" + valueColumn + "` = ? where `" + column + "` = ?"); + } + pstmt.setObject(1, value); + pstmt.setObject(2, columnValue); + pstmt.executeUpdate(); + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(resultSet, pstmt); + } + return false; + } + + /** + * 插入数据 + * + * @param name 名称 + * @param values 值 + * @return boolean + */ + public boolean intoValue(String name, Object... values) { + StringBuilder sb = new StringBuilder(); + for (Object value : values) { + sb.append("?, "); + } + PreparedStatement pstmt = null; + ResultSet resultSet = null; + try { + pstmt = connection.prepareStatement("insert into `" + name + "` values(null, " + sb.substring(0, sb.length() - 2) + ")"); + for (int i = 0; i < values.length; i++) { + pstmt.setObject(i + 1, values[i]); + } + pstmt.executeUpdate(); + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(resultSet, pstmt); + } + return false; + } + + /** + * 创建数据表 + * + * @param name 名称 + * @param columns 列表 + * @return boolean + */ + 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) + ")"); + } + + /** + * 创建数据表 + * + * @param name 名称 + * @param columns 列表 + * @return boolean + */ + public boolean createTable(String name, String... columns) { + StringBuilder sb = new StringBuilder(); + for (String column : columns) { + if (!column.contains("/")) { + sb.append("`").append(column).append("` text, "); + } else { + sb.append("`").append(column.split("/")[0]).append("` ").append(column.split("/")[1]).append(", "); + } + } + return execute("create table if not exists " + name + " (id int(1) not null primary key auto_increment, " + sb.substring(0, sb.length() - 2) + ")"); + } + + /** + * 检查数据表是否存在 + * + * @param name 名称 + * @return boolean + */ + public boolean isExists(String name) { + PreparedStatement pstmt = 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(); + while (resultSet.next()) { + return true; + } + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(resultSet, pstmt); + } + return false; + } + + /** + * 检查数据是否存在 + * + * @param name 名称 + * @param column 列表名 + * @param columnValue 列表值 + * @return boolean + */ + public boolean isExists(String name, String column, Object columnValue) { + PreparedStatement pstmt = null; + ResultSet resultSet = null; + try { + pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ?"); + pstmt.setObject(1, columnValue); + resultSet = pstmt.executeQuery(); + while (resultSet.next()) { + return true; + } + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(resultSet, pstmt); + } + return false; + } + + /** + * 获取所有列表名称(不含主键) + * + * @param name 名称 + * @return {@link List} + */ + public List getColumns(String name) { + return getColumns(name, false); + } + + /** + * 获取所有列表名称 + * + * @param name 名称 + * @param primary 是否获取主键 + * @return {@link List} + */ + public List getColumns(String name, boolean primary) { + List list = new ArrayList<>(); + PreparedStatement pstmt = 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(); + while (resultSet.next()) { + list.add(resultSet.getString(1)); + } + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(resultSet, pstmt); + } + // 是否获取主键 + if (!primary) { + list.remove("id"); + } + return list; + } + + /** + * 获取单项数据 + * + * @param name 名称 + * @param column 参考列 + * @param columnValue 参考值 + * @param valueColumn 数据列 + * @return Object + */ + public Object getValue(String name, String column, Object columnValue, String valueColumn) { + PreparedStatement pstmt = null; + ResultSet resultSet = null; + try { + pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? limit 1"); + pstmt.setObject(1, columnValue); + resultSet = pstmt.executeQuery(); + while (resultSet.next()) { + return resultSet.getObject(valueColumn); + } + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(resultSet, pstmt); + } + return null; + } + + /** + * 获取单项数据(根据主键倒叙排列后的最后一项) + * + * @param name 名称 + * @param column 参考列 + * @param columnValue 参考值 + * @param valueColumn 数据列 + * @return Object + */ + public Object getValueLast(String name, String column, Object columnValue, String valueColumn) { + PreparedStatement pstmt = 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(); + while (resultSet.next()) { + return resultSet.getObject(valueColumn); + } + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(resultSet, pstmt); + } + return null; + } + + /** + * 获取多项数据(根据主键倒叙排列后的最后一项) + * + * @param name 名称 + * @param column 参考列 + * @param columnValue 参考值 + * @param valueColumn 数据列 + * @return {@link HashMap} + */ + public HashMap getValueLast(String name, String column, Object columnValue, String... valueColumn) { + HashMap map = new HashMap<>(); + PreparedStatement pstmt = 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(); + while (resultSet.next()) { + for (String _column : valueColumn) { + map.put(_column, resultSet.getObject(_column)); + } + break; + } + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(resultSet, pstmt); + } + return map; + } + + /** + * 获取多项数据(单项多列) + * + * @param name 名称 + * @param column 参考列 + * @param columnValue 参考值 + * @param valueColumn 数据列 + * @return {@link HashMap} + */ + public HashMap getValue(String name, String column, Object columnValue, String... valueColumn) { + HashMap map = new HashMap<>(); + PreparedStatement pstmt = null; + ResultSet resultSet = null; + try { + pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? limit 1"); + pstmt.setObject(1, columnValue); + resultSet = pstmt.executeQuery(); + while (resultSet.next()) { + for (String _column : valueColumn) { + map.put(_column, resultSet.getObject(_column)); + } + break; + } + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(resultSet, pstmt); + } + return map; + } + + /** + * 获取多项数据(单列多列) + * + * @param name 名称 + * @param column 参考列 + * @param size 获取数量(-1 为无限制) + * @return {@link List} + */ + public List getValues(String name, String column, int size) { + return getValues(name, column, size, false); + } + + /** + * 获取多项数据(单列多列) + * + * @param name 名称 + * @param column 参考列 + * @param size 获取数量(-1 位无限制) + * @param desc 是否倒序 + * @return {@link List} + */ + public List getValues(String name, String column, int size, boolean desc) { + List list = new LinkedList<>(); + PreparedStatement pstmt = null; + ResultSet resultSet = null; + try { + if (desc) { + pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + column + "` desc " + (size < 0 ? "" : " limit " + size)); + } else { + pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + column + "` " + (size < 0 ? "" : " limit " + size)); + } + resultSet = pstmt.executeQuery(); + while (resultSet.next()) { + list.add(resultSet.getObject(column)); + } + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(resultSet, pstmt); + } + return list; + } + + /** + * 获取多线数据(多项多列) + * + * @param name 名称 + * @param sortColumn 参考列(该列类型必须为数字) + * @param size 获取数量(-1 为无限制) + * @param valueColumn 获取数据列 + * @return {@link LinkedList} + */ + public LinkedList> getValues(String name, String sortColumn, int size, String... valueColumn) { + return getValues(name, sortColumn, size, false, valueColumn); + } + + /** + * 获取多项数据(多项多列) + * + * @param name 名称 + * @param sortColumn 参考列(该列类型必须为数字) + * @param size 获取数量(-1 为无限制) + * @param desc 是否倒序 + * @param valueColumn 获取数据列 + * @return {@link LinkedList} + */ + public LinkedList> getValues(String name, String sortColumn, int size, boolean desc, String... valueColumn) { + LinkedList> list = new LinkedList<>(); + PreparedStatement pstmt = null; + ResultSet resultSet = null; + try { + if (desc) { + pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + sortColumn + "` desc" + (size < 0 ? "" : " limit " + size)); + } else { + pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + sortColumn + "`" + (size < 0 ? "" : " limit " + size)); + } + resultSet = pstmt.executeQuery(); + while (resultSet.next()) { + HashMap map = new HashMap<>(); + for (String _column : valueColumn) { + map.put(_column, resultSet.getObject(_column)); + } + list.add(map); + } + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + // 重新连接 + if (fallReconnection && e.getMessage().contains("closed")) { + connect(); + } + } finally { + freeResult(resultSet, pstmt); + } + return list; + } + + public boolean execute(String sql) { + PreparedStatement pstmt = null; + try { + pstmt = connection.prepareStatement(sql); + pstmt.execute(); + return true; + } catch (Exception e) { + print("数据库命令执行出错"); + print("错误原因: " + e.getMessage()); + print("错误命令: " + sql); + // 重连 + if (e.getMessage().contains("closed")) { + connect(); + } + return false; + } finally { + try { + if (pstmt != null) { + pstmt.close(); + } + } catch (Exception e) { + // + } + } + } + + public boolean connect() { + try { + print("正在连接数据库"); + print("地址: " + connectionUrl); + long time = System.currentTimeMillis(); + connection = DriverManager.getConnection(connectionUrl, this.user, this.password); + print("数据库连接成功 (" + (System.currentTimeMillis() - time) + "ms)"); + return true; + } catch (SQLException e) { + print("数据库连接失败"); + print("错误原因: " + e.getMessage()); + print("错误代码: " + e.getErrorCode()); + return false; + } + } + + public void print(String message) { + 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 boolean loadDriverMySQL() { + try { + Class.forName("com.mysql.jdbc.Driver"); + return true; + } catch (ClassNotFoundException e) { + return false; + } + } + + public enum ColumnInteger { + + TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT + } + + public enum ColumnFloat { + + FLOAT, DOUBLE + } + + public enum ColumnChar { + + CHAR, VARCHAR + } + + public enum ColumnString { + + TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT + } + + public static class Column { + + private String name; + private Object type; + private int a; + private int b; + + public Column(String name) { + this.name = name; + this.type = ColumnString.TEXT; + } + + public Column(String name, ColumnInteger type) { + this(name); + this.type = type; + this.a = 12; + } + + public Column(String name, ColumnInteger type, int m) { + this(name); + this.type = type; + this.a = m; + } + + public Column(String name, ColumnFloat type, int m, int d) { + this(name); + this.type = type; + this.a = m; + this.b = d; + } + + public Column(String name, ColumnChar type, int n) { + this(name); + this.type = type; + this.a = n; + } + + public Column(String name, ColumnString type) { + this(name); + this.type = type; + } + + @Override + public String toString() { + if (type instanceof ColumnInteger || type instanceof ColumnChar) { + return "`" + name + "` " + type.toString().toLowerCase() + "(" + a + ")"; + } else if (type instanceof ColumnFloat) { + return "`" + name + "` " + type.toString().toLowerCase() + "(" + a + "," + b + ")"; + } else { + return "`" + 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 70c1b2d..7a414c7 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java @@ -24,16 +24,16 @@ import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; -@SuppressWarnings({ "rawtypes", "unchecked" }) +@SuppressWarnings({"rawtypes", "unchecked"}) @Deprecated public class NMSUtil18 { - + protected static boolean failed = false; protected static String versionPrefix = ""; protected final static int NBT_TYPE_COMPOUND = 10; - protected final static int NBT_TYPE_INT_ARRAY= 11; + protected final static int NBT_TYPE_INT_ARRAY = 11; protected final static int NBT_TYPE_DOUBLE = 6; protected final static int NBT_TYPE_FLOAT = 5; protected final static int NBT_TYPE_STRING = 8; @@ -225,8 +225,7 @@ public class NMSUtil18 { protected static Field class_EntityArrow_damageField; protected static Field class_CraftWorld_environmentField; - static - { + static { // Find classes Bukkit hides from us. :-D // Much thanks to @DPOHVAR for sharing the PowerNBT code that powers the reflection approach. String className = Bukkit.getServer().getClass().getName(); @@ -254,7 +253,7 @@ public class NMSUtil18 { class_Packet = fixBukkitClass("net.minecraft.server.Packet"); class_World = fixBukkitClass("net.minecraft.server.World"); class_WorldServer = fixBukkitClass("net.minecraft.server.WorldServer"); - class_EnumSkyBlock = (Class)fixBukkitClass("net.minecraft.server.EnumSkyBlock"); + class_EnumSkyBlock = (Class) fixBukkitClass("net.minecraft.server.EnumSkyBlock"); class_EntityPainting = fixBukkitClass("net.minecraft.server.EntityPainting"); class_EntityCreature = fixBukkitClass("net.minecraft.server.EntityCreature"); class_EntityItemFrame = fixBukkitClass("net.minecraft.server.EntityItemFrame"); @@ -442,7 +441,7 @@ public class NMSUtil18 { class_EntityDamageSource_setThornsMethod = class_EntityDamageSource.getMethod("v"); class_BlockPosition = fixBukkitClass("net.minecraft.server.BlockPosition"); - class_EnumDirection = (Class)fixBukkitClass("net.minecraft.server.EnumDirection"); + class_EnumDirection = (Class) fixBukkitClass("net.minecraft.server.EnumDirection"); class_BlockPositionConstructor = class_BlockPosition.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE); class_EntityPaintingConstructor = class_EntityPainting.getConstructor(class_World, class_BlockPosition, class_EnumDirection); class_EntityItemFrameConstructor = class_EntityItemFrame.getConstructor(class_World, class_BlockPosition, class_EnumDirection); @@ -476,12 +475,10 @@ public class NMSUtil18 { } catch (Throwable ex) { class_EntityArrow_lifeField = null; } - if (class_EntityArrow_lifeField != null) - { + if (class_EntityArrow_lifeField != null) { class_EntityArrow_lifeField.setAccessible(true); } - } - catch (Throwable ex) { + } catch (Throwable ex) { failed = true; ex.printStackTrace(); } @@ -580,7 +577,7 @@ public class NMSUtil18 { Object chunkHandle = getHandle(chunk); boolean done = false; try { - done = (Boolean)class_Chunk_doneField.get(chunkHandle); + done = (Boolean) class_Chunk_doneField.get(chunkHandle); } catch (Throwable ex) { ex.printStackTrace(); } @@ -607,11 +604,11 @@ public class NMSUtil18 { return handle; } - protected static void sendPacket(Server server, Location source, Collection players, Object packet) throws Exception { + protected static void sendPacket(Server server, Location source, Collection players, Object packet) throws Exception { players = ((players != null && players.size() > 0) ? players : server.getOnlinePlayers()); int viewDistance = Bukkit.getServer().getViewDistance() * 16; - int viewDistanceSquared = viewDistance * viewDistance; + int viewDistanceSquared = viewDistance * viewDistance; World sourceWorld = source.getWorld(); for (Player player : players) { Location location = player.getLocation(); @@ -629,37 +626,35 @@ public class NMSUtil18 { Method sendPacketMethod = connection.getClass().getMethod("sendPacket", class_Packet); sendPacketMethod.invoke(connection, packet); } - - public static int getFacing(BlockFace direction) - { + + public static int getFacing(BlockFace direction) { int dir; switch (direction) { - case SOUTH: - default: - dir = 0; - break; - case WEST: - dir = 1; - break; - case NORTH: - dir = 2; - break; - case EAST: - dir = 3; - break; + case SOUTH: + default: + dir = 0; + break; + case WEST: + dir = 1; + break; + case NORTH: + dir = 2; + break; + case EAST: + dir = 3; + break; } - + return dir; } - public static org.bukkit.entity.Entity getBukkitEntity(Object entity) - { + public static org.bukkit.entity.Entity getBukkitEntity(Object entity) { 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; - return (org.bukkit.entity.Entity)bukkitEntity; + return (org.bukkit.entity.Entity) bukkitEntity; } catch (Throwable ex) { ex.printStackTrace(); } @@ -692,7 +687,7 @@ public class NMSUtil18 { try { Object craft = getNMSCopy(stack); - stack = (ItemStack)class_CraftItemStack_mirrorMethod.invoke(null, craft); + stack = (ItemStack) class_CraftItemStack_mirrorMethod.invoke(null, craft); } catch (Throwable ex) { stack = null; } @@ -751,7 +746,7 @@ public class NMSUtil18 { if (nbtBase == null) return false; Boolean result = false; try { - result = (Boolean)class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); + result = (Boolean) class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -808,7 +803,7 @@ public class NMSUtil18 { if (node == null || !class_NBTTagCompound.isInstance(node)) return null; String meta = null; try { - meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag); + meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -819,7 +814,7 @@ public class NMSUtil18 { if (node == null || !class_NBTTagCompound.isInstance(node)) return null; Byte meta = null; try { - meta = (Byte)class_NBTTagCompound_getByteMethod.invoke(node, tag); + meta = (Byte) class_NBTTagCompound_getByteMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -830,7 +825,7 @@ public class NMSUtil18 { if (node == null || !class_NBTTagCompound.isInstance(node)) return null; Integer meta = null; try { - meta = (Integer)class_NBTTagCompound_getIntMethod.invoke(node, tag); + meta = (Integer) class_NBTTagCompound_getIntMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -838,7 +833,7 @@ 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); @@ -851,7 +846,7 @@ 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) { @@ -881,7 +876,7 @@ public class NMSUtil18 { if (craft == null) return null; Object tagObject = getTag(craft); if (tagObject == null) return null; - meta = (String)class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); + meta = (String) class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1000,7 +995,7 @@ public class NMSUtil18 { Object explosion = class_World_explodeMethod.invoke(worldHandle, entityHandle, x, y, z, power, setFire, breakBlocks); Field cancelledField = explosion.getClass().getDeclaredField("wasCanceled"); - result = (Boolean)cancelledField.get(explosion); + result = (Boolean) cancelledField.get(explosion); } catch (Throwable ex) { ex.printStackTrace(); result = false; @@ -1087,7 +1082,7 @@ public class NMSUtil18 { ItemStack item = null; try { Object nmsStack = class_ItemStack_createStackMethod.invoke(null, itemTag); - item = (ItemStack)class_CraftItemStack_mirrorMethod.invoke(null, nmsStack); + item = (ItemStack) class_CraftItemStack_mirrorMethod.invoke(null, nmsStack); } catch (Exception ex) { ex.printStackTrace(); } @@ -1097,7 +1092,7 @@ public class NMSUtil18 { public static ItemStack[] getItems(Object rootTag, String tagName) { try { Object itemList = class_NBTTagCompound_getListMethod.invoke(rootTag, tagName, NBT_TYPE_COMPOUND); - Integer size = (Integer)class_NBTTagList_sizeMethod.invoke(itemList); + Integer size = (Integer) class_NBTTagList_sizeMethod.invoke(itemList); ItemStack[] items = new ItemStack[size]; for (int i = 0; i < size; i++) { try { @@ -1154,7 +1149,7 @@ public class NMSUtil18 { class_TileEntity_saveMethod.invoke(tileEntity, entityData); Object itemList = class_NBTTagCompound_getListMethod.invoke(entityData, "Items", NBT_TYPE_COMPOUND); if (itemList != null) { - List items = (List)class_NBTTagList_list.get(itemList); + List items = (List) class_NBTTagList_list.get(itemList); items.clear(); class_TileEntity_loadMethod.invoke(tileEntity, entityData); class_TileEntity_updateMethod.invoke(tileEntity); @@ -1188,9 +1183,9 @@ public class NMSUtil18 { public static Vector getPosition(Object entityData, String tag) { try { Object posList = class_NBTTagCompound_getListMethod.invoke(entityData, tag, NBT_TYPE_DOUBLE); - Double x = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 0); - Double y = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 1); - Double z = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 2); + Double x = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 0); + Double y = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 1); + Double z = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 2); if (x != null && y != null && z != null) { return new Vector(x, y, z); } @@ -1203,7 +1198,7 @@ public class NMSUtil18 { public static Entity getEntity(World world, UUID uuid) { try { Object worldHandle = getHandle(world); - final Map entityMap = (Map)class_WorldServer_entitiesByUUIDField.get(worldHandle); + final Map entityMap = (Map) class_WorldServer_entitiesByUUIDField.get(worldHandle); if (entityMap != null) { Object nmsEntity = entityMap.get(uuid); if (nmsEntity != null) { diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtils.java b/src/main/java/me/skymc/taboolib/nms/NMSUtils.java index ec28b91..b5656d0 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtils.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtils.java @@ -1,359 +1,361 @@ package me.skymc.taboolib.nms; +import org.bukkit.Bukkit; + import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import org.bukkit.Bukkit; - public class NMSUtils { - - public static String getVersion(){ - String name = Bukkit.getServer().getClass().getPackage().getName(); - return name.substring(name.lastIndexOf('.') + 1) + "."; - } - public static Class getClassWithException(String name) throws Exception{ - return Class.forName(name); - } - - public static Class getClass(String name){ - try{ - return getClassWithException(name); - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - public static Class getClass(String... strings){ - for(String s : strings){ - try{ - return getClassWithException(s); + public static Class c = getOBCClass("block.CraftBlock"); + public static Method m = getMethodSilent(c, "getNMSBlock"); + + public static String getVersion() { + String name = Bukkit.getServer().getClass().getPackage().getName(); + return name.substring(name.lastIndexOf('.') + 1) + "."; + } + + public static Class getClassWithException(String name) throws Exception { + return Class.forName(name); + } + + public static Class getClass(String name) { + try { + return getClassWithException(name); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Class getClass(String... strings) { + for (String s : strings) { + try { + return getClassWithException(s); } catch (Exception ignored) { - } - } - return null; - } - - public static Class getClassSilent(String name){ - try{ - return getClassWithException(name); + } + } + return null; + } + + public static Class getClassSilent(String name) { + try { + return getClassWithException(name); } catch (Exception ignored) { - } - return null; - } - - public static Class getNMSClassWithException(String className) throws Exception{ - return Class.forName("net.minecraft.server." + getVersion() + className); - } - - public static Class getNMSClass(String className){ - try{ - return getNMSClassWithException(className); - }catch(Exception ignored){ - } - return null; - } - - public static Class getNMSClassSilent(String className){ - try{ - return getNMSClassWithException(className); + } + return null; + } + + public static Class getNMSClassWithException(String className) throws Exception { + return Class.forName("net.minecraft.server." + getVersion() + className); + } + + public static Class getNMSClass(String className) { + try { + return getNMSClassWithException(className); } catch (Exception ignored) { - } - return null; - } - - public static Class getNMSClass(String className, String embedded){ - try{ - return getNMSClassWithException(className); - }catch(Exception e){ - return getInnerClassSilent(getNMSClassSilent(embedded), className); - } - } - - public static Class getNMSClassSilent(String className, String embedded){ - try{ - return getNMSClassWithException(className); - }catch(Exception e){ - return getInnerClassSilent(getNMSClassSilent(embedded), className); - } - } - - public static Class getOBCClassWithException(String className) throws Exception{ - return Class.forName("org.bukkit.craftbukkit." + getVersion() + className); - } - - public static Class getOBCClass(String className){ - try{ - return getOBCClassWithException(className); - }catch(Exception ignored){ - } - return null; - } - - public static Class getOBCClassSilent(String className){ - try{ - return getOBCClassWithException(className); + } + return null; + } + + public static Class getNMSClassSilent(String className) { + try { + return getNMSClassWithException(className); } catch (Exception ignored) { - } - return null; - } - - public static Object getHandle(Object obj){ - try{ - return getMethodWithException(obj.getClass(), "getHandle").invoke(obj); - }catch(Exception ignored){ - return null; - } - } - - public static Object getHandleSilent(Object obj){ - try{ - return getMethodWithException(obj.getClass(), "getHandle").invoke(obj); - }catch(Exception e){ - return null; - } - } - - public static Class c = getOBCClass("block.CraftBlock"); - public static Method m = getMethodSilent(c, "getNMSBlock"); - - public static Object getBlockHandleWithException(Object obj) throws Exception{ - return m.invoke(obj); - } - - public static Object getBlockHandle(Object obj){ - try{ - return m.invoke(obj); - }catch(Exception e){ - e.printStackTrace(); - return null; - } - } - - public static Object getBlockHandleSilent(Object obj){ - try{ - return m.invoke(obj); - }catch(Exception e){ - return null; - } - } - - public static Field getFieldWithException(Class clazz, String name) throws Exception{ - for(Field field : clazz.getDeclaredFields()) - if(field.getName().equals(name)){ - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - for(Field field : clazz.getFields()) - if(field.getName().equals(name)){ - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - throw new Exception("Field Not Found"); - } - - public static Field getFieldSilent(Class clazz, String... names){ - for(String name : names){ - try{ - return getFieldWithException(clazz, name); + } + return null; + } + + public static Class getNMSClass(String className, String embedded) { + try { + return getNMSClassWithException(className); + } catch (Exception e) { + return getInnerClassSilent(getNMSClassSilent(embedded), className); + } + } + + public static Class getNMSClassSilent(String className, String embedded) { + try { + return getNMSClassWithException(className); + } catch (Exception e) { + return getInnerClassSilent(getNMSClassSilent(embedded), className); + } + } + + public static Class getOBCClassWithException(String className) throws Exception { + return Class.forName("org.bukkit.craftbukkit." + getVersion() + className); + } + + public static Class getOBCClass(String className) { + try { + return getOBCClassWithException(className); + } catch (Exception ignored) { + } + return null; + } + + public static Class getOBCClassSilent(String className) { + try { + return getOBCClassWithException(className); + } catch (Exception ignored) { + } + return null; + } + + public static Object getHandle(Object obj) { + try { + return getMethodWithException(obj.getClass(), "getHandle").invoke(obj); + } catch (Exception ignored) { + return null; + } + } + + public static Object getHandleSilent(Object obj) { + try { + return getMethodWithException(obj.getClass(), "getHandle").invoke(obj); + } catch (Exception e) { + return null; + } + } + + public static Object getBlockHandleWithException(Object obj) throws Exception { + return m.invoke(obj); + } + + public static Object getBlockHandle(Object obj) { + try { + return m.invoke(obj); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static Object getBlockHandleSilent(Object obj) { + try { + return m.invoke(obj); + } catch (Exception e) { + return null; + } + } + + public static Field getFieldWithException(Class clazz, String name) throws Exception { + for (Field field : clazz.getDeclaredFields()) + if (field.getName().equals(name)) { + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + int modifiers = modifiersField.getInt(field); + modifiers &= ~Modifier.FINAL; + modifiersField.setInt(field, modifiers); + return field; + } + for (Field field : clazz.getFields()) + if (field.getName().equals(name)) { + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + int modifiers = modifiersField.getInt(field); + modifiers &= ~Modifier.FINAL; + modifiersField.setInt(field, modifiers); + return field; + } + throw new Exception("Field Not Found"); + } + + public static Field getFieldSilent(Class clazz, String... names) { + for (String name : names) { + try { + return getFieldWithException(clazz, name); } catch (Exception ignored) { - } - } - return null; - } - - public static Field getFieldSilent(Class clazz, String name){ - try{ - return getFieldWithException(clazz, name); + } + } + return null; + } + + public static Field getFieldSilent(Class clazz, String name) { + try { + return getFieldWithException(clazz, name); } catch (Exception ignored) { - } - return null; - } - - public static Field getField(Class clazz, String... names){ - for(String name : names){ - try{ - return getFieldWithException(clazz, name); + } + return null; + } + + public static Field getField(Class clazz, String... names) { + for (String name : names) { + try { + return getFieldWithException(clazz, name); } catch (Exception ignored) { - } - } - return null; - } - - public static Field getFieldOfTypeWithException(Class clazz, Class type, String name) throws Exception{ - for(Field field : clazz.getDeclaredFields()) - if(field.getName().equals(name) && field.getType().equals(type)){ - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - for(Field field : clazz.getFields()) - if(field.getName().equals(name) && field.getType().equals(type)){ - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - throw new Exception("Field Not Found"); - } - - public static Field getFieldOfType(Class clazz, Class type, String name){ - try{ - return getFieldOfTypeWithException(clazz, type, name); - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - public static Field getFirstFieldOfTypeWithException(Class clazz, Class type) throws Exception{ - for(Field field : clazz.getDeclaredFields()){ - if(field.getType().equals(type)){ - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - } - throw new Exception("Field Not Found"); - } - - public static Field getFirstFieldOfType(Class clazz, Class type){ - try{ - return getFirstFieldOfTypeWithException(clazz, type); - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - public static Field getLastFieldOfTypeWithException(Class clazz, Class type) throws Exception{ - Field field = null; - for(Field f : clazz.getDeclaredFields()) - if(f.getType().equals(type)){ - field = f; - } - if(field == null){ throw new Exception("Field Not Found"); } - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - int modifiers = modifiersField.getInt(field); - modifiers &= ~Modifier.FINAL; - modifiersField.setInt(field, modifiers); - return field; - } - - public static Field getLastFieldOfType(Class clazz, Class type){ - try{ - return getLastFieldOfTypeWithException(clazz, type); - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - public static Method getMethodWithException(Class clazz, String name, Class... args) throws Exception{ - for(Method m : clazz.getDeclaredMethods()) - if(m.getName().equals(name) && (args.length == 0 && m.getParameterTypes().length == 0 || ClassListEqual(args, m.getParameterTypes()))){ - m.setAccessible(true); - return m; - } - for(Method m : clazz.getMethods()) - if(m.getName().equals(name) && (args.length == 0 && m.getParameterTypes().length == 0 || ClassListEqual(args, m.getParameterTypes()))){ - m.setAccessible(true); - return m; - } - throw new Exception("Method Not Found"); - } - - public static Method getMethodSilent(Class clazz, String name, Class... args){ - try{ - return getMethodWithException(clazz, name, args); + } + } + return null; + } + + public static Field getFieldOfTypeWithException(Class clazz, Class type, String name) throws Exception { + for (Field field : clazz.getDeclaredFields()) + if (field.getName().equals(name) && field.getType().equals(type)) { + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + int modifiers = modifiersField.getInt(field); + modifiers &= ~Modifier.FINAL; + modifiersField.setInt(field, modifiers); + return field; + } + for (Field field : clazz.getFields()) + if (field.getName().equals(name) && field.getType().equals(type)) { + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + int modifiers = modifiersField.getInt(field); + modifiers &= ~Modifier.FINAL; + modifiersField.setInt(field, modifiers); + return field; + } + throw new Exception("Field Not Found"); + } + + public static Field getFieldOfType(Class clazz, Class type, String name) { + try { + return getFieldOfTypeWithException(clazz, type, name); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Field getFirstFieldOfTypeWithException(Class clazz, Class type) throws Exception { + for (Field field : clazz.getDeclaredFields()) { + if (field.getType().equals(type)) { + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + int modifiers = modifiersField.getInt(field); + modifiers &= ~Modifier.FINAL; + modifiersField.setInt(field, modifiers); + return field; + } + } + throw new Exception("Field Not Found"); + } + + public static Field getFirstFieldOfType(Class clazz, Class type) { + try { + return getFirstFieldOfTypeWithException(clazz, type); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Field getLastFieldOfTypeWithException(Class clazz, Class type) throws Exception { + Field field = null; + for (Field f : clazz.getDeclaredFields()) + if (f.getType().equals(type)) { + field = f; + } + if (field == null) { + throw new Exception("Field Not Found"); + } + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + int modifiers = modifiersField.getInt(field); + modifiers &= ~Modifier.FINAL; + modifiersField.setInt(field, modifiers); + return field; + } + + public static Field getLastFieldOfType(Class clazz, Class type) { + try { + return getLastFieldOfTypeWithException(clazz, type); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Method getMethodWithException(Class clazz, String name, Class... args) throws Exception { + for (Method m : clazz.getDeclaredMethods()) + if (m.getName().equals(name) && (args.length == 0 && m.getParameterTypes().length == 0 || ClassListEqual(args, m.getParameterTypes()))) { + m.setAccessible(true); + return m; + } + for (Method m : clazz.getMethods()) + if (m.getName().equals(name) && (args.length == 0 && m.getParameterTypes().length == 0 || ClassListEqual(args, m.getParameterTypes()))) { + m.setAccessible(true); + return m; + } + throw new Exception("Method Not Found"); + } + + public static Method getMethodSilent(Class clazz, String name, Class... args) { + try { + return getMethodWithException(clazz, name, args); } catch (Exception ignored) { - } - return null; - } - - public static boolean ClassListEqual(Class[] l1, Class[] l2){ - if(l1.length != l2.length) - return false; - 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)) - return cl; - throw new Exception("Inner Class Not Found"); - } - - public static Class getInnerClass(Class c, String className){ - try{ - return getInnerClassWithException(c, className); - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - public static Class getInnerClassSilent(Class c, String className){ - try{ - return getInnerClassWithException(c, className); + } + return null; + } + + public static boolean ClassListEqual(Class[] l1, Class[] l2) { + if (l1.length != l2.length) + return false; + 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)) + return cl; + throw new Exception("Inner Class Not Found"); + } + + public static Class getInnerClass(Class c, String className) { + try { + return getInnerClassWithException(c, className); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Class getInnerClassSilent(Class c, String className) { + try { + return getInnerClassWithException(c, className); } catch (Exception ignored) { - } - return null; - } - - public static Constructor getConstructor(Class clazz, Class... args) throws Exception{ - for(Constructor c : clazz.getDeclaredConstructors()) - if(args.length == 0 && c.getParameterTypes().length == 0 || ClassListEqual(args, c.getParameterTypes())){ - c.setAccessible(true); - return c; - } - for(Constructor c : clazz.getConstructors()) - if(args.length == 0 && c.getParameterTypes().length == 0 || ClassListEqual(args, c.getParameterTypes())){ - c.setAccessible(true); - return c; - } - throw new Exception("Constructor Not Found"); - } - - public static Constructor getConstructorSilent(Class clazz, Class... args){ - try{ - return getConstructor(clazz, args); + } + return null; + } + + public static Constructor getConstructor(Class clazz, Class... args) throws Exception { + for (Constructor c : clazz.getDeclaredConstructors()) + if (args.length == 0 && c.getParameterTypes().length == 0 || ClassListEqual(args, c.getParameterTypes())) { + c.setAccessible(true); + return c; + } + for (Constructor c : clazz.getConstructors()) + if (args.length == 0 && c.getParameterTypes().length == 0 || ClassListEqual(args, c.getParameterTypes())) { + c.setAccessible(true); + return c; + } + throw new Exception("Constructor Not Found"); + } + + public static Constructor getConstructorSilent(Class clazz, Class... args) { + try { + return getConstructor(clazz, args); } catch (Exception ignored) { - } - return null; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static Enum getEnum(final String value, final Class enumClass){ - return Enum.valueOf(enumClass, value); - } + } + return null; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static Enum getEnum(final String value, final Class enumClass) { + return Enum.valueOf(enumClass, value); + } } diff --git a/src/main/java/me/skymc/taboolib/nms/item/impl/_164ItemUtils.java b/src/main/java/me/skymc/taboolib/nms/item/impl/_164ItemUtils.java index c08b5ba..ce99552 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 @@ -30,8 +30,8 @@ public class _164ItemUtils implements IDabItemUtils{ public boolean getBanner(){ try{ Material m = Material.valueOf("BANNER"); - if(m != null){ return true; } - } catch (Exception ignored) { + return true; + } catch (Exception ignored) { } return false; } 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 e8888e9..11558a1 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 @@ -30,8 +30,8 @@ public class _1710ItemUtils implements IDabItemUtils{ public boolean getBanner(){ try{ Material m = Material.valueOf("BANNER"); - if(m != null){ return true; } - } catch (Exception ignored) { + return true; + } catch (Exception ignored) { } return false; } 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 71df5cf..321c2cf 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 @@ -29,7 +29,7 @@ public class _194ItemUtils implements IDabItemUtils{ public boolean getBanner(){ try{ Material m = Material.valueOf("BANNER"); - if(m != null){ return true; } + return true; } catch (Exception ignored) { } return false; diff --git a/src/main/java/me/skymc/taboolib/nms/nbt/NBTConstants.java b/src/main/java/me/skymc/taboolib/nms/nbt/NBTConstants.java index 4fa611d..c35e593 100644 --- a/src/main/java/me/skymc/taboolib/nms/nbt/NBTConstants.java +++ b/src/main/java/me/skymc/taboolib/nms/nbt/NBTConstants.java @@ -3,23 +3,24 @@ package me.skymc.taboolib.nms.nbt; import java.nio.charset.Charset; @Deprecated -public final class NBTConstants{ - private NBTConstants(){ - throw new AssertionError("Not instantiable"); - } - - public static final Charset CHARSET = Charset.forName("UTF-8"); - - public static final int TYPE_END = 0; - public static final int TYPE_BYTE = 1; - public static final int TYPE_SHORT = 2; - public static final int TYPE_INT = 3; - public static final int TYPE_LONG = 4; - public static final int TYPE_FLOAT = 5; - public static final int TYPE_DOUBLE = 6; - public static final int TYPE_BYTE_ARRAY = 7; - public static final int TYPE_STRING = 8; - public static final int TYPE_LIST = 9; - public static final int TYPE_COMPOUND = 10; - public static final int TYPE_INT_ARRAY = 11; +public final class NBTConstants { + + private NBTConstants() { + throw new AssertionError("Not instantiable"); + } + + public static final Charset CHARSET = Charset.forName("UTF-8"); + + public static final int TYPE_END = 0; + public static final int TYPE_BYTE = 1; + public static final int TYPE_SHORT = 2; + public static final int TYPE_INT = 3; + public static final int TYPE_LONG = 4; + public static final int TYPE_FLOAT = 5; + public static final int TYPE_DOUBLE = 6; + public static final int TYPE_BYTE_ARRAY = 7; + public static final int TYPE_STRING = 8; + public static final int TYPE_LIST = 9; + public static final int TYPE_COMPOUND = 10; + public static final int TYPE_INT_ARRAY = 11; } diff --git a/src/main/java/me/skymc/taboolib/object/WeightCategory.java b/src/main/java/me/skymc/taboolib/object/WeightCategory.java index e02227c..b386767 100644 --- a/src/main/java/me/skymc/taboolib/object/WeightCategory.java +++ b/src/main/java/me/skymc/taboolib/object/WeightCategory.java @@ -1,33 +1,33 @@ package me.skymc.taboolib.object; -public class WeightCategory { - - private String category; - private Integer weight; - - public WeightCategory() { - super(); - } - - public WeightCategory(String category, Integer weight) { - super(); - this.setCategory(category); - this.setWeight(weight); - } - - public Integer getWeight() { - return weight; - } - - public void setWeight(Integer weight) { - this.weight = weight; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } +public class WeightCategory { + + private String category; + private Integer weight; + + public WeightCategory() { + super(); + } + + public WeightCategory(String category, Integer weight) { + super(); + this.setCategory(category); + this.setWeight(weight); + } + + public Integer getWeight() { + return weight; + } + + public void setWeight(Integer weight) { + this.weight = weight; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/other/DateUtils.java b/src/main/java/me/skymc/taboolib/other/DateUtils.java index 4f8d5fa..e4f5cc4 100644 --- a/src/main/java/me/skymc/taboolib/other/DateUtils.java +++ b/src/main/java/me/skymc/taboolib/other/DateUtils.java @@ -4,82 +4,77 @@ import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; -public class DateUtils { - - /** - * 最后一次更新:2018年1月16日21:07:27 - * - * @author sky - */ - +public class DateUtils { + + /** + * 最后一次更新:2018年1月16日21:07:27 + * + * @author sky + */ + public static SimpleDateFormat CH_ALL = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒"); public static SimpleDateFormat EN_ALL = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - + public static SimpleDateFormat YEAR = new SimpleDateFormat("yyyy"); - + public static SimpleDateFormat MONTH = new SimpleDateFormat("MM"); - + public static SimpleDateFormat DAY_OF_MONTH = new SimpleDateFormat("dd"); public static SimpleDateFormat DAY_OF_YEAR = new SimpleDateFormat("DD"); - + public static SimpleDateFormat HOUR_OF_DAY = new SimpleDateFormat("HH"); public static SimpleDateFormat HOUR = new SimpleDateFormat("hh"); - + public static SimpleDateFormat MINUTE = new SimpleDateFormat("mm"); public static SimpleDateFormat SECONDS = new SimpleDateFormat("ss"); - + public static SimpleDateFormat MILLISECOND = new SimpleDateFormat("SSS"); - + public static SimpleDateFormat WEEK = new SimpleDateFormat("E"); - + private static SimpleDateFormat Hour = new SimpleDateFormat("HH:mm"); - + public static Calendar getCalendar() { - return Calendar.getInstance(); + return Calendar.getInstance(); } - + public static Date getTime() { - return Calendar.getInstance().getTime(); + return Calendar.getInstance().getTime(); } - + public static Integer getTime(SimpleDateFormat date) { - return Integer.valueOf(date.format(getTime())); + return Integer.valueOf(date.format(getTime())); + } + + public static boolean timeInDifference(String m1, String m2) { + try { + Date now = Hour.parse(Hour.format(System.currentTimeMillis())); + Date min = Hour.parse(m1); + Date max = Hour.parse(m2); + return (now.after(min) && now.before(max)) || now.equals(min) || now.equals(max); + } catch (Exception e) { + return false; + } + } + + public static long formatDate(String time) { + long date = 0; + try { + for (String value : time.toLowerCase().split(";")) { + Integer num = Integer.valueOf(value.substring(0, value.length() - 1)); + if (value.endsWith("d")) { + date += num * 1000L * 60 * 60 * 24; + } else if (value.endsWith("h")) { + date += num * 1000L * 60 * 60; + } else if (value.endsWith("m")) { + date += num * 1000L * 60; + } else if (value.endsWith("s")) { + date += num * 1000L; + } + } + } catch (Exception e) { + // TODO: handle exception + } + return date; } - - public static boolean timeInDifference(String m1, String m2) { - try { - Date now = Hour.parse(Hour.format(System.currentTimeMillis())); - Date min = Hour.parse(m1); - Date max = Hour.parse(m2); - return (now.after(min) && now.before(max)) || now.equals(min) || now.equals(max); - } - catch (Exception e) { - return false; - } - } - - public static long formatDate(String time) { - long date = 0; - try { - for (String value : time.toLowerCase().split(";")) { - Integer num = Integer.valueOf(value.substring(0, value.length() - 1)); - if (value.endsWith("d")) { - date += num * 1000L * 60 * 60 * 24; - } - else if (value.endsWith("h")) { - date += num * 1000L * 60 * 60; - } - else if (value.endsWith("m")) { - date += num * 1000L * 60; - } - else if (value.endsWith("s")) { - date += num * 1000L; - } - } - } - catch (Exception e) { - // TODO: handle exception - } - return date; - } } diff --git a/src/main/java/me/skymc/taboolib/other/MathUtils.java b/src/main/java/me/skymc/taboolib/other/MathUtils.java index 662165b..fbc751a 100644 --- a/src/main/java/me/skymc/taboolib/other/MathUtils.java +++ b/src/main/java/me/skymc/taboolib/other/MathUtils.java @@ -1,64 +1,55 @@ package me.skymc.taboolib.other; +import me.skymc.taboolib.particle.EffLib; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import me.skymc.taboolib.particle.EffLib; - public class MathUtils { - - public static double tronc(double paramDouble, int paramInt) - { - double d = Math.pow(10.0D, paramInt); - return Math.floor(paramDouble * d) / d; - } - - public static void drawVec(Vector paramVector, Location paramLocation, Color paramColor) - { - for (double d = 0.0D; d < 1.0D; d += 0.1D) { - EffLib.REDSTONE.display(new EffLib.OrdinaryColor(paramColor), paramLocation.clone().add(paramVector.clone().multiply(d)), 100.0D); - } - } - - public static void sendCoords(Player paramPlayer, Vector paramVector, String paramString) - { - paramPlayer.sendMessage(paramString + tronc(paramVector.getX(), 2) + " " + tronc(paramVector.getY(), 2) + " " + tronc(paramVector.getZ(), 2)); - } - - public static void sendCoords(Player paramPlayer, Location paramLocation, String paramString) - { - paramPlayer.sendMessage(paramString + tronc(paramLocation.getX(), 2) + " " + tronc(paramLocation.getY(), 2) + " " + tronc(paramLocation.getZ(), 2)); - } - - public static Vector rotAxisX(Vector paramVector, double paramDouble) - { - double d1 = paramVector.getY() * Math.cos(paramDouble) - paramVector.getZ() * Math.sin(paramDouble); - double d2 = paramVector.getY() * Math.sin(paramDouble) + paramVector.getZ() * Math.cos(paramDouble); - return paramVector.setY(d1).setZ(d2); - } - - public static Vector rotAxisY(Vector paramVector, double paramDouble) - { - double d1 = paramVector.getX() * Math.cos(paramDouble) + paramVector.getZ() * Math.sin(paramDouble); - double d2 = paramVector.getX() * -Math.sin(paramDouble) + paramVector.getZ() * Math.cos(paramDouble); - return paramVector.setX(d1).setZ(d2); - } - - public static Vector rotAxisZ(Vector paramVector, double paramDouble) - { - double d1 = paramVector.getX() * Math.cos(paramDouble) - paramVector.getY() * Math.sin(paramDouble); - double d2 = paramVector.getX() * Math.sin(paramDouble) + paramVector.getY() * Math.cos(paramDouble); - return paramVector.setX(d1).setY(d2); - } - - public static Vector rotateFunc(Vector paramVector, Location paramLocation) - { - double d1 = paramLocation.getYaw() / 180.0F * 3.141592653589793D; - double d2 = paramLocation.getPitch() / 180.0F * 3.141592653589793D; - paramVector = rotAxisX(paramVector, d2); - paramVector = rotAxisY(paramVector, -d1); - return paramVector; - } + + public static double tronc(double paramDouble, int paramInt) { + double d = Math.pow(10.0D, paramInt); + return Math.floor(paramDouble * d) / d; + } + + public static void drawVec(Vector paramVector, Location paramLocation, Color paramColor) { + for (double d = 0.0D; d < 1.0D; d += 0.1D) { + EffLib.REDSTONE.display(new EffLib.OrdinaryColor(paramColor), paramLocation.clone().add(paramVector.clone().multiply(d)), 100.0D); + } + } + + public static void sendCoords(Player paramPlayer, Vector paramVector, String paramString) { + paramPlayer.sendMessage(paramString + tronc(paramVector.getX(), 2) + " " + tronc(paramVector.getY(), 2) + " " + tronc(paramVector.getZ(), 2)); + } + + public static void sendCoords(Player paramPlayer, Location paramLocation, String paramString) { + paramPlayer.sendMessage(paramString + tronc(paramLocation.getX(), 2) + " " + tronc(paramLocation.getY(), 2) + " " + tronc(paramLocation.getZ(), 2)); + } + + public static Vector rotAxisX(Vector paramVector, double paramDouble) { + double d1 = paramVector.getY() * Math.cos(paramDouble) - paramVector.getZ() * Math.sin(paramDouble); + double d2 = paramVector.getY() * Math.sin(paramDouble) + paramVector.getZ() * Math.cos(paramDouble); + return paramVector.setY(d1).setZ(d2); + } + + public static Vector rotAxisY(Vector paramVector, double paramDouble) { + double d1 = paramVector.getX() * Math.cos(paramDouble) + paramVector.getZ() * Math.sin(paramDouble); + double d2 = paramVector.getX() * -Math.sin(paramDouble) + paramVector.getZ() * Math.cos(paramDouble); + return paramVector.setX(d1).setZ(d2); + } + + public static Vector rotAxisZ(Vector paramVector, double paramDouble) { + double d1 = paramVector.getX() * Math.cos(paramDouble) - paramVector.getY() * Math.sin(paramDouble); + double d2 = paramVector.getX() * Math.sin(paramDouble) + paramVector.getY() * Math.cos(paramDouble); + return paramVector.setX(d1).setY(d2); + } + + public static Vector rotateFunc(Vector paramVector, Location paramLocation) { + double d1 = paramLocation.getYaw() / 180.0F * 3.141592653589793D; + double d2 = paramLocation.getPitch() / 180.0F * 3.141592653589793D; + paramVector = rotAxisX(paramVector, d2); + paramVector = rotAxisY(paramVector, -d1); + return paramVector; + } } diff --git a/src/main/java/me/skymc/taboolib/other/NumberUtils.java b/src/main/java/me/skymc/taboolib/other/NumberUtils.java index 695cada..a469276 100644 --- a/src/main/java/me/skymc/taboolib/other/NumberUtils.java +++ b/src/main/java/me/skymc/taboolib/other/NumberUtils.java @@ -4,65 +4,62 @@ import java.text.DecimalFormat; import java.util.Random; public class NumberUtils { - - private static Random rand = new Random(); - private static DecimalFormat doubleFormat = new DecimalFormat("#.##"); - - public static Random getRand() { - return rand; - } - - public static Double format(Double num) { - return Double.valueOf(doubleFormat.format(num)); - } - - @Deprecated + + private static Random rand = new Random(); + private static DecimalFormat doubleFormat = new DecimalFormat("#.##"); + + public static Random getRand() { + return rand; + } + + public static Double format(Double num) { + return Double.valueOf(doubleFormat.format(num)); + } + + @Deprecated public static int getRandom() { return rand.nextInt(100); } - - @Deprecated + + @Deprecated public static boolean getChance(int a) { return getRandom() <= a; } - + public static int getRandomInteger(Number l, Number u) { - Integer ll = Math.min(l.intValue(), u.intValue()); - Integer uu = Math.max(l.intValue(), u.intValue()); - return rand.nextInt(uu) % (uu - ll + 1) + ll; + Integer ll = Math.min(l.intValue(), u.intValue()); + Integer uu = Math.max(l.intValue(), u.intValue()); + return rand.nextInt(uu) % (uu - ll + 1) + ll; } - + public static double getRandomDouble(Number l, Number u) { - double ll = Math.min(l.doubleValue(), u.doubleValue()); - double uu = Math.max(l.doubleValue(), u.doubleValue()); - double d = ll + rand.nextDouble() * (uu - ll); - return Double.valueOf(doubleFormat.format(d)); + double ll = Math.min(l.doubleValue(), u.doubleValue()); + double uu = Math.max(l.doubleValue(), u.doubleValue()); + double d = ll + rand.nextDouble() * (uu - ll); + return Double.valueOf(doubleFormat.format(d)); } - + public static int getInteger(String s) { - try { - return Integer.valueOf(s); - } - catch (Exception e) { - return 0; - } + try { + return Integer.valueOf(s); + } catch (Exception e) { + return 0; + } } - + public static double getDouble(String s) { - try { - return Double.valueOf(s); - } - catch (Exception e) { - return 0; - } + try { + return Double.valueOf(s); + } catch (Exception e) { + return 0; + } } - + public static Boolean getBoolean(String s) { - try { - return Boolean.valueOf(s); - } - catch (Exception e) { - return false; - } + try { + return Boolean.valueOf(s); + } catch (Exception e) { + return false; + } } } diff --git a/src/main/java/me/skymc/taboolib/other/WeightUtils.java b/src/main/java/me/skymc/taboolib/other/WeightUtils.java index 0a9bb7e..78bcd9b 100644 --- a/src/main/java/me/skymc/taboolib/other/WeightUtils.java +++ b/src/main/java/me/skymc/taboolib/other/WeightUtils.java @@ -1,32 +1,32 @@ package me.skymc.taboolib.other; -import java.util.List; - import me.skymc.taboolib.object.WeightCategory; -public class WeightUtils { - +import java.util.List; + +public class WeightUtils { + public static String getStringByWeight(List categorys) { - - int weightSum = 0; - for (WeightCategory wc : categorys) { - weightSum += wc.getWeight(); - } - - if (weightSum <= 0) { - return null; - } - + + int weightSum = 0; + for (WeightCategory wc : categorys) { + weightSum += wc.getWeight(); + } + + if (weightSum <= 0) { + return null; + } + Integer n = NumberUtils.getRand().nextInt(weightSum); - Integer m = 0; - - for (WeightCategory wc : categorys) { - if (m <= n && n < m + wc.getWeight()) { - return wc.getCategory(); - } - m += wc.getWeight(); - } + Integer m = 0; + + for (WeightCategory wc : categorys) { + if (m <= n && n < m + wc.getWeight()) { + return wc.getCategory(); + } + m += wc.getWeight(); + } return null; } - + } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/packet/PacketUtils.java b/src/main/java/me/skymc/taboolib/packet/PacketUtils.java index ddfdebb..63ed053 100644 --- a/src/main/java/me/skymc/taboolib/packet/PacketUtils.java +++ b/src/main/java/me/skymc/taboolib/packet/PacketUtils.java @@ -1,25 +1,23 @@ package me.skymc.taboolib.packet; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; public class PacketUtils { - - public enum EntityStatus { - - FIRE, CROUCHED, UNUSED1, UNUSED2, SPRINTING, INVISIBLE, GLOWING, ELYTRA - } - - public static void sendPacketEntityStatus(Entity entity, EntityStatus status, Player... players) { - PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); - packet.getIntegers().write(0, entity.getEntityId()); - WrappedDataWatcher watcher = new WrappedDataWatcher(); - WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(Byte.class); + + public enum EntityStatus { + FIRE, CROUCHED, UNUSED1, UNUSED2, SPRINTING, INVISIBLE, GLOWING, ELYTRA + } + + public static void sendPacketEntityStatus(Entity entity, EntityStatus status, Player... players) { + PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); + packet.getIntegers().write(0, entity.getEntityId()); + WrappedDataWatcher watcher = new WrappedDataWatcher(); + WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(Byte.class); switch (status) { case FIRE: watcher.setObject(0, serializer, (byte) 0x01); @@ -49,29 +47,29 @@ public class PacketUtils { watcher.setObject(0, serializer, (byte) 0x00); break; } - packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); - try { - for (Player player : players) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void sendPacketEntityCustomName(Entity entity, String value, Player... players) { - PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); - packet.getIntegers().write(0, entity.getEntityId()); - WrappedDataWatcher watcher = new WrappedDataWatcher(); - WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(String.class); - watcher.setObject(2, serializer, value == null ? "" : value); - packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); - try { - for (Player player : players) { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } + packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); + try { + for (Player player : players) { + ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void sendPacketEntityCustomName(Entity entity, String value, Player... players) { + PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA); + packet.getIntegers().write(0, entity.getEntityId()); + WrappedDataWatcher watcher = new WrappedDataWatcher(); + WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(String.class); + watcher.setObject(2, serializer, value == null ? "" : value); + packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); + try { + for (Player player : players) { + ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + } + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/me/skymc/taboolib/player/TargetUtils.java b/src/main/java/me/skymc/taboolib/player/TargetUtils.java index 617dd9e..fa993a9 100644 --- a/src/main/java/me/skymc/taboolib/player/TargetUtils.java +++ b/src/main/java/me/skymc/taboolib/player/TargetUtils.java @@ -1,27 +1,25 @@ package me.skymc.taboolib.player; -import java.util.LinkedList; - import org.bukkit.block.Block; import org.bukkit.entity.LivingEntity; import org.bukkit.util.BlockIterator; +import java.util.LinkedList; + @Deprecated public class TargetUtils { - - public static LinkedList getTarget(LivingEntity p, int max) { - BlockIterator itor = new BlockIterator(p); - LinkedList block = new LinkedList<>(); - while(itor.hasNext()) - { - max++; - block.add(itor.next()); - if (max >= 100) - { - break; - } - } - return block; - } + + public static LinkedList getTarget(LivingEntity p, int max) { + BlockIterator itor = new BlockIterator(p); + LinkedList block = new LinkedList<>(); + while (itor.hasNext()) { + max++; + block.add(itor.next()); + if (max >= 100) { + break; + } + } + return block; + } } diff --git a/src/main/java/me/skymc/taboolib/playerdata/DataUtils.java b/src/main/java/me/skymc/taboolib/playerdata/DataUtils.java index 774e380..1ac4ea2 100644 --- a/src/main/java/me/skymc/taboolib/playerdata/DataUtils.java +++ b/src/main/java/me/skymc/taboolib/playerdata/DataUtils.java @@ -1,10 +1,10 @@ package me.skymc.taboolib.playerdata; -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.concurrent.ConcurrentHashMap; - +import me.skymc.taboolib.Main; +import me.skymc.taboolib.database.PlayerDataManager; +import me.skymc.taboolib.exception.PlayerOfflineException; +import me.skymc.taboolib.fileutils.FileUtils; +import me.skymc.taboolib.message.MsgUtils; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.configuration.file.FileConfiguration; @@ -14,141 +14,139 @@ import org.bukkit.event.Listener; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.plugin.Plugin; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.database.PlayerDataManager; -import me.skymc.taboolib.exception.PlayerOfflineException; -import me.skymc.taboolib.fileutils.FileUtils; -import me.skymc.taboolib.message.MsgUtils; +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; public class DataUtils implements Listener { - - public static final ConcurrentHashMap> CACHE_DATA_PLUGIN = new ConcurrentHashMap<>(); - - public static void saveAllCahces(Plugin plugin) { - saveAllCaches(plugin, false); - } - - public static void saveAllCaches(Plugin plugin, boolean remove) { - if (plugin == null || !CACHE_DATA_PLUGIN.containsKey(plugin.getName())) { - return; - } - for (String fileName : CACHE_DATA_PLUGIN.get(plugin.getName()).keySet()) { - saveConfiguration(CACHE_DATA_PLUGIN.get(plugin.getName()).get(fileName), FileUtils.file(getDataSaveFolder(plugin), fileName)); - } - if (remove) { - CACHE_DATA_PLUGIN.remove(plugin.getName()); - } - } - - public static void saveAllCaches() { - saveAllCaches(false); - } - - public static void saveAllCaches(boolean remove) { - long time = System.currentTimeMillis(); - for (String plugin : CACHE_DATA_PLUGIN.keySet()) { - saveAllCaches(getFixedPlugin(plugin), remove); - } - if (!Main.getInst().getConfig().getBoolean("HIDE-NOTIFY")) { - MsgUtils.send("保存 &f" + DataUtils.CACHE_DATA_PLUGIN.size() + " &7条插件数据, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)"); - } - } - - public static void saveConfiguration(FileConfiguration conf, File file) { - try { - conf.save(file); - } catch (IOException e) { - MsgUtils.warn("文件 &4" + file.getName() + "&c 保存失败, 原因: &4" + e.getMessage()); - } - } - - public static String getFixedFileName(String name) { - return name.contains(".") ? name : name + ".yml"; - } - - public static Plugin getFixedPlugin(String pluginName) { - return Bukkit.getPluginManager().getPlugin(pluginName) == null ? Main.getInst() : Bukkit.getPluginManager().getPlugin(pluginName); - } - - public static File getDataSaveFolder(Plugin plugin) { - return plugin == null || plugin.equals(Main.getInst()) ? Main.getServerDataFolder() : plugin.getDataFolder(); - } - - public static String getDataSaveKey(Plugin plugin) { - return plugin == null || plugin.equals(Main.getInst()) ? Main.getInst().getName() : plugin.getName(); - } - - public static FileConfiguration addPluginData(String name, Plugin plugin) { - return setPluginData(getFixedFileName(name), plugin, YamlConfiguration.loadConfiguration(FileUtils.file(getDataSaveFolder(plugin), getFixedFileName(name)))); - } - - public static FileConfiguration getPluginData(String name, Plugin plugin) { - return !CACHE_DATA_PLUGIN.containsKey(getDataSaveKey(plugin)) ? null : CACHE_DATA_PLUGIN.get(getDataSaveKey(plugin)).get(getFixedFileName(name)); - } - - public static FileConfiguration setPluginData(String name, Plugin plugin, FileConfiguration conf) { - if (!CACHE_DATA_PLUGIN.containsKey(getDataSaveKey(plugin))) { - CACHE_DATA_PLUGIN.put(getDataSaveKey(plugin), new HashMap<>()); - } - CACHE_DATA_PLUGIN.get(getDataSaveKey(plugin)).put(getFixedFileName(name), conf); - return conf; - } - - @EventHandler - public void disable(PluginDisableEvent e) { - if (e.getPlugin().equals(Main.getInst())) { - return; - } - if (CACHE_DATA_PLUGIN.containsKey(e.getPlugin().getName())) { - saveAllCaches(e.getPlugin(), true); - } - } - - @Deprecated - public static FileConfiguration getPlayerData(String name) { - try { - return PlayerDataManager.getPlayerData(name, true); - } - catch (PlayerOfflineException e) { - return new YamlConfiguration(); - } - } - - @Deprecated - public static FileConfiguration addPlayerData(String name) { - return PlayerDataManager.loadPlayerData(name); - } - - @Deprecated - public static void savePlayerData(String name, boolean remove) { - PlayerDataManager.savePlayerData(name, remove); - } - - @Deprecated - public static FileConfiguration registerServerData(String name) { - return addPluginData(name, null); - } - - @Deprecated - public static FileConfiguration getPlayerData(OfflinePlayer p) { - return getPlayerData(p.getName()); - } - - @Deprecated - public static void setPlayerData(OfflinePlayer p, String s, Object o) { - getPlayerData(p.getName()).set(s, o); - } - - @Deprecated - public static void saveData(OfflinePlayer p) { - saveOnline(p.getName()); - } - - public static Long getOnline(OfflinePlayer p) { - return getPlayerData(p).getLong("TabooLib.Offline"); - } - - public static void saveOnline(String p) { - getPlayerData(p).set("TabooLib.Offline", System.currentTimeMillis()); - } + + public static final ConcurrentHashMap> CACHE_DATA_PLUGIN = new ConcurrentHashMap<>(); + + public static void saveAllCaches(Plugin plugin) { + saveAllCaches(plugin, false); + } + + public static void saveAllCaches(Plugin plugin, boolean remove) { + if (plugin == null || !CACHE_DATA_PLUGIN.containsKey(plugin.getName())) { + return; + } + for (String fileName : CACHE_DATA_PLUGIN.get(plugin.getName()).keySet()) { + saveConfiguration(CACHE_DATA_PLUGIN.get(plugin.getName()).get(fileName), FileUtils.file(getDataSaveFolder(plugin), fileName)); + } + if (remove) { + CACHE_DATA_PLUGIN.remove(plugin.getName()); + } + } + + public static void saveAllCaches() { + saveAllCaches(false); + } + + public static void saveAllCaches(boolean remove) { + long time = System.currentTimeMillis(); + for (String plugin : CACHE_DATA_PLUGIN.keySet()) { + saveAllCaches(getFixedPlugin(plugin), remove); + } + if (!Main.getInst().getConfig().getBoolean("HIDE-NOTIFY")) { + MsgUtils.send("保存 &f" + DataUtils.CACHE_DATA_PLUGIN.size() + " &7条插件数据, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)"); + } + } + + public static void saveConfiguration(FileConfiguration conf, File file) { + try { + conf.save(file); + } catch (IOException e) { + MsgUtils.warn("文件 &4" + file.getName() + "&c 保存失败, 原因: &4" + e.getMessage()); + } + } + + public static String getFixedFileName(String name) { + return name.contains(".") ? name : name + ".yml"; + } + + public static Plugin getFixedPlugin(String pluginName) { + return Bukkit.getPluginManager().getPlugin(pluginName) == null ? Main.getInst() : Bukkit.getPluginManager().getPlugin(pluginName); + } + + public static File getDataSaveFolder(Plugin plugin) { + return plugin == null || plugin.equals(Main.getInst()) ? Main.getServerDataFolder() : plugin.getDataFolder(); + } + + public static String getDataSaveKey(Plugin plugin) { + return plugin == null || plugin.equals(Main.getInst()) ? Main.getInst().getName() : plugin.getName(); + } + + public static FileConfiguration addPluginData(String name, Plugin plugin) { + return setPluginData(getFixedFileName(name), plugin, YamlConfiguration.loadConfiguration(FileUtils.file(getDataSaveFolder(plugin), getFixedFileName(name)))); + } + + public static FileConfiguration getPluginData(String name, Plugin plugin) { + return !CACHE_DATA_PLUGIN.containsKey(getDataSaveKey(plugin)) ? new YamlConfiguration() : CACHE_DATA_PLUGIN.get(getDataSaveKey(plugin)).get(getFixedFileName(name)); + } + + public static FileConfiguration setPluginData(String name, Plugin plugin, FileConfiguration conf) { + if (!CACHE_DATA_PLUGIN.containsKey(getDataSaveKey(plugin))) { + CACHE_DATA_PLUGIN.put(getDataSaveKey(plugin), new HashMap<>()); + } + CACHE_DATA_PLUGIN.get(getDataSaveKey(plugin)).put(getFixedFileName(name), conf); + return conf; + } + + @EventHandler + public void disable(PluginDisableEvent e) { + if (e.getPlugin().equals(Main.getInst())) { + return; + } + if (CACHE_DATA_PLUGIN.containsKey(e.getPlugin().getName())) { + saveAllCaches(e.getPlugin(), true); + } + } + + @Deprecated + public static FileConfiguration getPlayerData(String name) { + try { + return PlayerDataManager.getPlayerData(name, true); + } catch (PlayerOfflineException e) { + return new YamlConfiguration(); + } + } + + @Deprecated + public static FileConfiguration addPlayerData(String name) { + return PlayerDataManager.loadPlayerData(name); + } + + @Deprecated + public static void savePlayerData(String name, boolean remove) { + PlayerDataManager.savePlayerData(name, remove); + } + + @Deprecated + public static FileConfiguration registerServerData(String name) { + return addPluginData(name, null); + } + + @Deprecated + public static FileConfiguration getPlayerData(OfflinePlayer p) { + return getPlayerData(p.getName()); + } + + @Deprecated + public static void setPlayerData(OfflinePlayer p, String s, Object o) { + getPlayerData(p.getName()).set(s, o); + } + + @Deprecated + public static void saveData(OfflinePlayer p) { + saveOnline(p.getName()); + } + + public static Long getOnline(OfflinePlayer p) { + return getPlayerData(p).getLong("TabooLib.Offline"); + } + + public static void saveOnline(String p) { + getPlayerData(p).set("TabooLib.Offline", System.currentTimeMillis()); + } } diff --git a/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java b/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java index 5794f6c..ae6f0d2 100644 --- a/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java +++ b/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java @@ -1,38 +1,27 @@ package me.skymc.taboolib.plugin; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Field; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.SortedSet; -import java.util.logging.Level; -import java.util.logging.Logger; - +import com.google.common.base.Joiner; +import me.skymc.taboolib.Main; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.PluginCommand; import org.bukkit.command.SimpleCommandMap; import org.bukkit.event.Event; -import org.bukkit.plugin.InvalidDescriptionException; -import org.bukkit.plugin.InvalidPluginException; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.RegisteredListener; +import org.bukkit.plugin.*; -import com.google.common.base.Joiner; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.URLClassLoader; +import java.util.*; +import java.util.Map.Entry; +import java.util.logging.Level; +import java.util.logging.Logger; -import me.skymc.taboolib.Main; +public class PluginUtils { -public class PluginUtils -{ - public static String consolidateStrings(final String[] args, final int start) { + public static String consolidateStrings(final String[] args, final int start) { StringBuilder ret = new StringBuilder(args[start]); if (args.length > start + 1) { for (int i = start + 1; i < args.length; ++i) { @@ -41,13 +30,13 @@ public class PluginUtils } return ret.toString(); } - + public static void enable(final Plugin plugin) { if (plugin != null && !plugin.isEnabled()) { Bukkit.getPluginManager().enablePlugin(plugin); } } - + public static void enableAll() { for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (!isIgnored(plugin)) { @@ -55,13 +44,13 @@ public class PluginUtils } } } - + public static void disable(final Plugin plugin) { if (plugin != null && plugin.isEnabled()) { Bukkit.getPluginManager().disablePlugin(plugin); } } - + public static void disableAll() { for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (!isIgnored(plugin)) { @@ -69,11 +58,11 @@ public class PluginUtils } } } - + public static String getFormattedName(final Plugin plugin) { return getFormattedName(plugin, false); } - + public static String getFormattedName(final Plugin plugin, final boolean includeVersions) { final ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED; String pluginName = color + plugin.getName(); @@ -82,11 +71,11 @@ public class PluginUtils } return pluginName; } - + public static Plugin getPluginByName(final String[] args, final int start) { return getPluginByName(consolidateStrings(args, start)); } - + public static Plugin getPluginByName(final String name) { for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (name.equalsIgnoreCase(plugin.getName())) { @@ -95,7 +84,7 @@ public class PluginUtils } return null; } - + public static List getPluginNames(final boolean fullName) { final List plugins = new ArrayList<>(); for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { @@ -103,7 +92,7 @@ public class PluginUtils } return plugins; } - + public static String getPluginVersion(final String name) { final Plugin plugin = getPluginByName(name); if (plugin != null && plugin.getDescription() != null) { @@ -111,7 +100,7 @@ public class PluginUtils } return null; } - + public static String getUsages(final Plugin plugin) { final List parsedCommands = new ArrayList<>(); final Map> commands = plugin.getDescription().getCommands(); @@ -127,9 +116,9 @@ public class PluginUtils } return Joiner.on(", ").join(parsedCommands); } - + @SuppressWarnings("unchecked") - public static List findByCommand(final String command) { + public static List findByCommand(final String command) { final List plugins = new ArrayList<>(); for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { final Map> commands = plugin.getDescription().getCommands(); @@ -137,18 +126,16 @@ public class PluginUtils for (final Map.Entry> commandNext : commands.entrySet()) { if (commandNext.getKey().equalsIgnoreCase(command)) { plugins.add(plugin.getName()); - } - else { + } else { for (final Map.Entry attributeNext : commandNext.getValue().entrySet()) { if (attributeNext.getKey().equals("aliases")) { final Object aliases = attributeNext.getValue(); if (aliases instanceof String) { - if (!((String)aliases).equalsIgnoreCase(command)) { + if (!((String) aliases).equalsIgnoreCase(command)) { continue; } plugins.add(plugin.getName()); - } - else { + } else { final List array = (List) aliases; for (final String str : array) { if (str.equalsIgnoreCase(command)) { @@ -164,21 +151,21 @@ public class PluginUtils } return plugins; } - + public static boolean isIgnored(final Plugin plugin) { return isIgnored(plugin.getName()); } - + public static boolean isIgnored(final String plugin) { return plugin.equalsIgnoreCase(Main.getInst().getName()); } - + private static String load(final Plugin plugin) { return load(plugin.getName()); } - + public static String load(final String name) { - Plugin target = null; + Plugin target; final File pluginDir = new File("plugins"); if (!pluginDir.isDirectory()) { return "load.plugin-directory"; @@ -193,8 +180,7 @@ public class PluginUtils pluginFile = f; break; } - } - catch (InvalidDescriptionException e3) { + } catch (InvalidDescriptionException e3) { return "load.cannot-find"; } } @@ -202,25 +188,23 @@ public class PluginUtils } try { target = Bukkit.getPluginManager().loadPlugin(pluginFile); - } - catch (InvalidDescriptionException e) { + } catch (InvalidDescriptionException e) { return "load.invalid-description"; - } - catch (InvalidPluginException e2) { + } catch (InvalidPluginException e2) { return "load.invalid-plugin"; } target.onLoad(); Bukkit.getPluginManager().enablePlugin(target); return "load.loaded"; } - + public static void reload(final Plugin plugin) { if (plugin != null) { unload(plugin); load(plugin); } } - + public static void reloadAll() { for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (!isIgnored(plugin)) { @@ -228,9 +212,9 @@ public class PluginUtils } } } - + @SuppressWarnings("unchecked") - public static String unload(final Plugin plugin) { + public static String unload(final Plugin plugin) { final String name = plugin.getName(); final PluginManager pluginManager = Bukkit.getPluginManager(); SimpleCommandMap commandMap = null; @@ -244,24 +228,23 @@ public class PluginUtils try { final Field pluginsField = Bukkit.getPluginManager().getClass().getDeclaredField("plugins"); pluginsField.setAccessible(true); - plugins = (List)pluginsField.get(pluginManager); + plugins = (List) pluginsField.get(pluginManager); final Field lookupNamesField = Bukkit.getPluginManager().getClass().getDeclaredField("lookupNames"); lookupNamesField.setAccessible(true); - names = (Map)lookupNamesField.get(pluginManager); + names = (Map) lookupNamesField.get(pluginManager); try { final Field listenersField = Bukkit.getPluginManager().getClass().getDeclaredField("listeners"); listenersField.setAccessible(true); - listeners = (Map>)listenersField.get(pluginManager); - } - catch (Exception e3) { + listeners = (Map>) listenersField.get(pluginManager); + } catch (Exception e3) { reloadlisteners = false; } final Field commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("commandMap"); commandMapField.setAccessible(true); - commandMap = (SimpleCommandMap)commandMapField.get(pluginManager); + commandMap = (SimpleCommandMap) commandMapField.get(pluginManager); final Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands"); knownCommandsField.setAccessible(true); - commands = (Map)knownCommandsField.get(commandMap); + commands = (Map) knownCommandsField.get(commandMap); } catch (NoSuchFieldException | IllegalAccessException e) { return "failed"; } @@ -283,7 +266,7 @@ public class PluginUtils while (it2.hasNext()) { final Map.Entry entry = it2.next(); if (entry.getValue() instanceof PluginCommand) { - final PluginCommand c = (PluginCommand)entry.getValue(); + final PluginCommand c = (PluginCommand) entry.getValue(); if (c.getPlugin() != plugin) { continue; } @@ -295,9 +278,8 @@ public class PluginUtils final ClassLoader cl = plugin.getClass().getClassLoader(); if (cl instanceof URLClassLoader) { try { - ((URLClassLoader)cl).close(); - } - catch (IOException ex) { + ((URLClassLoader) cl).close(); + } catch (IOException ex) { Logger.getLogger(PluginUtils.class.getName()).log(Level.SEVERE, null, ex); } } diff --git a/src/main/java/me/skymc/taboolib/scoreboard/ScoreboardUtil.java b/src/main/java/me/skymc/taboolib/scoreboard/ScoreboardUtil.java index 2d96946..4dd03d0 100644 --- a/src/main/java/me/skymc/taboolib/scoreboard/ScoreboardUtil.java +++ b/src/main/java/me/skymc/taboolib/scoreboard/ScoreboardUtil.java @@ -1,295 +1,297 @@ package me.skymc.taboolib.scoreboard; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; - import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Scoreboard; -public class ScoreboardUtil -{ - private ScoreboardUtil() { } +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; - public static String[] cutUnranked(String[] content) - { - String[] elements = Arrays.copyOf(content, 16); +public class ScoreboardUtil { - if(elements[0] == null) - elements[0] = "Unamed board"; + private ScoreboardUtil() { + } - if(elements[0].length() > 32) - elements[0] = elements[0].substring(0, 32); + public static String[] cutUnranked(String[] content) { + String[] elements = Arrays.copyOf(content, 16); - for(int i = 1; i < elements.length; i++) - if(elements[i] != null) - if(elements[i].length() > 40) - elements[i] = elements[i].substring(0, 40); + if (elements[0] == null) { + elements[0] = "Unamed board"; + } - return elements; - } + if (elements[0].length() > 32) { + elements[0] = elements[0].substring(0, 32); + } - public static String cutRankedTitle(String title) - { - if(title == null) - return "Unamed board"; + for (int i = 1; i < elements.length; i++) { + if (elements[i] != null) { + if (elements[i].length() > 40) { + elements[i] = elements[i].substring(0, 40); + } + } + } - if(title.length() > 32) - return title.substring(0, 32); + return elements; + } - return title; - } + public static String cutRankedTitle(String title) { + if (title == null) { + return "Unamed board"; + } - public static HashMap cutRanked(HashMap content) - { - HashMap elements = new HashMap<>(content); + if (title.length() > 32) { + return title.substring(0, 32); + } - while(elements.size() > 15) - { - String minimumKey = (String) elements.keySet().toArray()[0]; - int minimum = elements.get(minimumKey); + return title; + } - for(String string : elements.keySet()) - if(elements.get(string) < minimum || (elements.get(string) == minimum && string.compareTo(minimumKey) < 0)) - { - minimumKey = string; - minimum = elements.get(string); - } + public static HashMap cutRanked(HashMap content) { + HashMap elements = new HashMap<>(content); - elements.remove(minimumKey); - } + while (elements.size() > 15) { + String minimumKey = (String) elements.keySet().toArray()[0]; + int minimum = elements.get(minimumKey); - for(String string : new ArrayList<>(elements.keySet())) - if(string != null) - if(string.length() > 40) - { - int value = elements.get(string); - elements.remove(string); - elements.put(string.substring(0, 40), value); - } + for (String string : elements.keySet()) { + if (elements.get(string) < minimum || (elements.get(string) == minimum && string.compareTo(minimumKey) < 0)) { + minimumKey = string; + minimum = elements.get(string); + } + } - return elements; + elements.remove(minimumKey); + } - } + for (String string : new ArrayList<>(elements.keySet())) { + if (string != null) { + if (string.length() <= 40) { + } else { + int value = elements.get(string); + elements.remove(string); + elements.put(string.substring(0, 40), value); + } + } + } - public static Scoreboard unrankedSidebarDisplay(Player p, String... elements) - { - elements = cutUnranked(elements); + return elements; - try - { - if(p.getScoreboard() == null || p.getScoreboard() == Bukkit.getScoreboardManager().getMainScoreboard() || p.getScoreboard().getObjectives().size() != 1) - { - p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - } + } - if(p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)) == null) - { - p.getScoreboard().registerNewObjective(p.getUniqueId().toString().substring(0, 16), "dummy"); - p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)).setDisplaySlot(DisplaySlot.SIDEBAR); - } + public static Scoreboard unrankedSidebarDisplay(Player p, String... elements) { + elements = cutUnranked(elements); + + try { + if (p.getScoreboard() == null || p.getScoreboard() == Bukkit.getScoreboardManager().getMainScoreboard() || p.getScoreboard().getObjectives().size() != 1) { + p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } + + if (p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)) == null) { + p.getScoreboard().registerNewObjective(p.getUniqueId().toString().substring(0, 16), "dummy"); + p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)).setDisplaySlot(DisplaySlot.SIDEBAR); + } + p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).setDisplayName(elements[0]); - p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).setDisplayName(elements[0]); + for (int i = 1; i < elements.length; i++) { + if (elements[i] != null) { + if (p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(elements[i]).getScore() != 16 - i) { + p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(elements[i]).setScore(16 - i); + for (String string : p.getScoreboard().getEntries()) { + if (p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)).getScore(string).getScore() == 16 - i) { + if (!string.equals(elements[i])) { + p.getScoreboard().resetScores(string); + } + } + } - for(int i = 1; i < elements.length; i++) - if(elements[i] != null) - if(p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(elements[i]).getScore() != 16 - i) - { - p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(elements[i]).setScore(16 - i); - for(String string : p.getScoreboard().getEntries()) - if(p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)).getScore(string).getScore() == 16 - i) - if(!string.equals(elements[i])) - p.getScoreboard().resetScores(string); + } + } + } - } + for (String entry : p.getScoreboard().getEntries()) { + boolean toErase = true; + for (String element : elements) { + if (element != null && element.equals(entry) && p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)).getScore(entry).getScore() == 16 - Arrays.asList(elements).indexOf(element)) { + toErase = false; + break; + } + } - for(String entry : p.getScoreboard().getEntries()) - { - boolean toErase = true; - for(String element : elements) - { - if(element != null && element.equals(entry) && p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)).getScore(entry).getScore() == 16 - Arrays.asList(elements).indexOf(element)) - { - toErase = false; - break; - } - } + if (toErase) { + p.getScoreboard().resetScores(entry); + } - if(toErase) - p.getScoreboard().resetScores(entry); + } - } + return p.getScoreboard(); + } catch (Exception e) { + return null; + } + } - return p.getScoreboard(); - } - catch(Exception e) - { - return null; - } - } + public static boolean unrankedSidebarDisplay(Collection players, String[] elements) { + for (Player player : players) { + if (unrankedSidebarDisplay(player, elements) == null) { + return false; + } + } - public static boolean unrankedSidebarDisplay(Collection players, String[] elements) - { - for(Player player : players) - if(unrankedSidebarDisplay(player, elements) == null) - return false; + return true; + } - return true; - } + public static boolean unrankedSidebarDisplay(Collection players, Scoreboard board, String... elements) { + try { + String objName = "COLLAB-SB-WINTER"; - public static boolean unrankedSidebarDisplay(Collection players, Scoreboard board, String... elements) - { - try - { - String objName = "COLLAB-SB-WINTER"; + if (board == null) { + board = Bukkit.getScoreboardManager().getNewScoreboard(); + } - if(board == null) - board = Bukkit.getScoreboardManager().getNewScoreboard(); + elements = cutUnranked(elements); - elements = cutUnranked(elements); + for (Player player : players) { + if (player.getScoreboard() != board) { + player.setScoreboard(board); + } + } - for(Player player : players) - if(player.getScoreboard() != board) - player.setScoreboard(board); - - if(board.getObjective(objName) == null) - { - board.registerNewObjective(objName, "dummy"); - board.getObjective(objName).setDisplaySlot(DisplaySlot.SIDEBAR); - } + if (board.getObjective(objName) == null) { + board.registerNewObjective(objName, "dummy"); + board.getObjective(objName).setDisplaySlot(DisplaySlot.SIDEBAR); + } - board.getObjective(DisplaySlot.SIDEBAR).setDisplayName(elements[0]); + board.getObjective(DisplaySlot.SIDEBAR).setDisplayName(elements[0]); - for(int i = 1; i < elements.length; i++) - if(elements[i] != null && board.getObjective(DisplaySlot.SIDEBAR).getScore(elements[i]).getScore() != 16 - i) - { - board.getObjective(DisplaySlot.SIDEBAR).getScore(elements[i]).setScore(16 - i); - for(String string : board.getEntries()) - if(board.getObjective(objName).getScore(string).getScore() == 16 - i) - if(!string.equals(elements[i])) - board.resetScores(string); + for (int i = 1; i < elements.length; i++) { + if (elements[i] != null && board.getObjective(DisplaySlot.SIDEBAR).getScore(elements[i]).getScore() != 16 - i) { + board.getObjective(DisplaySlot.SIDEBAR).getScore(elements[i]).setScore(16 - i); + for (String string : board.getEntries()) { + if (board.getObjective(objName).getScore(string).getScore() == 16 - i) { + if (!string.equals(elements[i])) { + board.resetScores(string); + } + } + } - } + } + } - for(String entry : board.getEntries()) - { - boolean toErase = true; - for(String element : elements) - { - if(element != null && element.equals(entry) && board.getObjective(objName).getScore(entry).getScore() == 16 - Arrays.asList(elements).indexOf(element)) - { - toErase = false; - break; - } - } + for (String entry : board.getEntries()) { + boolean toErase = true; + for (String element : elements) { + if (element != null && element.equals(entry) && board.getObjective(objName).getScore(entry).getScore() == 16 - Arrays.asList(elements).indexOf(element)) { + toErase = false; + break; + } + } - if(toErase) - board.resetScores(entry); + if (toErase) { + board.resetScores(entry); + } - } + } - return true; - } - catch(Exception e) - { - e.printStackTrace(); - return false; - } - } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } - public static boolean rankedSidebarDisplay(Player p, String title, HashMap elements) - { - try - { - title = cutRankedTitle(title); - elements = cutRanked(elements); + public static boolean rankedSidebarDisplay(Player p, String title, HashMap elements) { + try { + title = cutRankedTitle(title); + elements = cutRanked(elements); - if(p.getScoreboard() == null || p.getScoreboard() == Bukkit.getScoreboardManager().getMainScoreboard() || p.getScoreboard().getObjectives().size() != 1) - { - p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - } + if (p.getScoreboard() == null || p.getScoreboard() == Bukkit.getScoreboardManager().getMainScoreboard() || p.getScoreboard().getObjectives().size() != 1) { + p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } - if(p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)) == null) - { - p.getScoreboard().registerNewObjective(p.getUniqueId().toString().substring(0, 16), "dummy"); - p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)).setDisplaySlot(DisplaySlot.SIDEBAR); - } - p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).setDisplayName(title); + if (p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)) == null) { + p.getScoreboard().registerNewObjective(p.getUniqueId().toString().substring(0, 16), "dummy"); + p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)).setDisplaySlot(DisplaySlot.SIDEBAR); + } + p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).setDisplayName(title); - for(String string : elements.keySet()) - if(p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(string).getScore() != elements.get(string)) - p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(string).setScore(elements.get(string)); + for (String string : elements.keySet()) { + if (p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(string).getScore() != elements.get(string)) { + p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(string).setScore(elements.get(string)); + } + } - for(String string : new ArrayList<>(p.getScoreboard().getEntries())) - if(!elements.keySet().contains(string)) - p.getScoreboard().resetScores(string); + for (String string : new ArrayList<>(p.getScoreboard().getEntries())) { + if (!elements.keySet().contains(string)) { + p.getScoreboard().resetScores(string); + } + } - return true; - } - catch(Exception e) - { - e.printStackTrace(); - return false; - } - } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } - public static boolean rankedSidebarDisplay(Collection players, String title, HashMap elements) - { - for(Player player : players) - if(!rankedSidebarDisplay(player, title, elements)) - return false; + public static boolean rankedSidebarDisplay(Collection players, String title, HashMap elements) { + for (Player player : players) { + if (!rankedSidebarDisplay(player, title, elements)) { + return false; + } + } - return true; - } + return true; + } - public static boolean rankedSidebarDisplay(Collection players, String title, HashMap elements, Scoreboard board) - { - try - { - title = cutRankedTitle(title); - elements = cutRanked(elements); + public static boolean rankedSidebarDisplay(Collection players, String title, HashMap elements, Scoreboard board) { + try { + title = cutRankedTitle(title); + elements = cutRanked(elements); - String objName = "COLLAB-SB-WINTER"; + String objName = "COLLAB-SB-WINTER"; - if(board == null) - board = Bukkit.getScoreboardManager().getNewScoreboard(); + if (board == null) { + board = Bukkit.getScoreboardManager().getNewScoreboard(); + } - for(Player player : players) - if(player.getScoreboard() != board) - player.setScoreboard(board); + for (Player player : players) { + if (player.getScoreboard() != board) { + player.setScoreboard(board); + } + } - if(board.getObjective(objName) == null) - { - board.registerNewObjective(objName, "dummy"); - board.getObjective(objName).setDisplaySlot(DisplaySlot.SIDEBAR); - } + if (board.getObjective(objName) == null) { + board.registerNewObjective(objName, "dummy"); + board.getObjective(objName).setDisplaySlot(DisplaySlot.SIDEBAR); + } - board.getObjective(DisplaySlot.SIDEBAR).setDisplayName(title); + board.getObjective(DisplaySlot.SIDEBAR).setDisplayName(title); - for(String string : elements.keySet()) - if(board.getObjective(DisplaySlot.SIDEBAR).getScore(string).getScore() != elements.get(string)) - board.getObjective(DisplaySlot.SIDEBAR).getScore(string).setScore(elements.get(string)); + for (String string : elements.keySet()) { + if (board.getObjective(DisplaySlot.SIDEBAR).getScore(string).getScore() != elements.get(string)) { + board.getObjective(DisplaySlot.SIDEBAR).getScore(string).setScore(elements.get(string)); + } + } - for(String string : new ArrayList<>(board.getEntries())) - if(!elements.keySet().contains(string)) - board.resetScores(string); + for (String string : new ArrayList<>(board.getEntries())) { + if (!elements.keySet().contains(string)) { + board.resetScores(string); + } + } - return true; - } - catch(Exception e) - { - e.printStackTrace(); - return false; - } - } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/sound/SoundPack.java b/src/main/java/me/skymc/taboolib/sound/SoundPack.java index 52cdacf..af616d6 100644 --- a/src/main/java/me/skymc/taboolib/sound/SoundPack.java +++ b/src/main/java/me/skymc/taboolib/sound/SoundPack.java @@ -4,62 +4,64 @@ import org.bukkit.Sound; import org.bukkit.entity.Player; public class SoundPack { - - private Sound sound; - private Float a; - private Float b; - - public SoundPack() { - this.sound = Sound.valueOf(SoundUtils.getModifiedSound("ENTITY_VILLAGER_NO")); - this.a = 1f; - this.b = 1f; - } - - public SoundPack(Sound sound, Float a, Float b) { - this.sound = sound; - this.a = a; - this.b = b; - } - - public SoundPack(String s) { - try { - sound = Sound.valueOf(SoundUtils.getModifiedSound(s.split("-")[0])); - a = Float.valueOf(s.split("-")[1]); - b = Float.valueOf(s.split("-")[2]); - } - catch (Exception e) { - this.sound = Sound.valueOf(SoundUtils.getModifiedSound("ENTITY_VILLAGER_NO")); - this.a = 1f; - this.b = 1f; - } - } - - public Sound getSound() { - return sound; - } - - public Float getA() { - return a; - } - - public Float getB() { - return b; - } - - public void play(Player p) { - p.playSound(p.getLocation(), sound, a, b); - } - - public void parse(String s) { - try { - sound = Sound.valueOf(SoundUtils.getModifiedSound(s.split("-")[0])); - a = Float.valueOf(s.split("-")[1]); - b = Float.valueOf(s.split("-")[2]); - } - catch (Exception e) { - this.sound = Sound.valueOf(SoundUtils.getModifiedSound("ENTITY_VILLAGER_NO")); - this.a = 1f; - this.b = 1f; - } - } + + private Sound sound; + private Float a; + private Float b; + + public SoundPack() { + this.sound = Sound.valueOf(SoundUtils.getModifiedSound("ENTITY_VILLAGER_NO")); + this.a = 1f; + this.b = 1f; + } + + public SoundPack(Sound sound, Float a, Float b) { + this.sound = sound; + this.a = a; + this.b = b; + } + + public SoundPack(String s) { + try { + sound = Sound.valueOf(SoundUtils.getModifiedSound(s.split("-")[0])); + a = Float.valueOf(s.split("-")[1]); + b = Float.valueOf(s.split("-")[2]); + } catch (Exception e) { + this.sound = Sound.valueOf(SoundUtils.getModifiedSound("ENTITY_VILLAGER_NO")); + this.a = 1f; + this.b = 1f; + } + } + + public Sound getSound() { + return sound; + } + + public Float getA() { + return a; + } + + public Float getB() { + return b; + } + + public void play(Player p) { + p.playSound(p.getLocation(), sound, a, b); + } + + public void parse(String s) { + try { + sound = Sound.valueOf(SoundUtils.getModifiedSound(s.split("-")[0])); + a = Float.valueOf(s.split("-")[1]); + b = Float.valueOf(s.split("-")[2]); + } catch (Exception e) { + this.sound = Sound.valueOf(SoundUtils.getModifiedSound("ENTITY_VILLAGER_NO")); + this.a = 1f; + this.b = 1f; + } + } + + public String toString() { + return sound.name() + "-" + a + "-" + b; + } } diff --git a/src/main/java/me/skymc/taboolib/sound/SoundUtils.java b/src/main/java/me/skymc/taboolib/sound/SoundUtils.java index f0a9239..de67dc8 100644 --- a/src/main/java/me/skymc/taboolib/sound/SoundUtils.java +++ b/src/main/java/me/skymc/taboolib/sound/SoundUtils.java @@ -1,52 +1,43 @@ package me.skymc.taboolib.sound; -import org.bukkit.Location; -import org.bukkit.Sound; - import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.message.MsgUtils; +import org.bukkit.Location; +import org.bukkit.Sound; public class SoundUtils { - - public static void sound(Location paramLocation, String paramString, float paramFloat1, float paramFloat2) { - String str = getModifiedSound(paramString); - try { - paramLocation.getWorld().playSound(paramLocation, Sound.valueOf(str), paramFloat1, paramFloat2); - } - catch (Exception localException) { - MsgUtils.send("§4Bug with " + paramString + ". No such sound found. Please report it to the plugin creator :)"); - } - } - - static String getModifiedSound(String str) { - if (TabooLib.getVerint() < 10900) { - str = str.replace("BLOCK_FIRE_EXTINGUISH", "FIZZ"); - str = str.replace("BLOCK_NOTE_HAT", "NOTE_STICKS"); - str = str.replace("ENTITY_SHEEP_DEATH", "SHEEP_IDLE"); - str = str.replace("ENTITY_LLAMA_ANGRY", "HORSE_HIT"); - str = str.replace("BLOCK_BREWING_STAND_BREW", "CREEPER_HISS"); - str = str.replace("ENTITY_SHULKER_TELEPORT", "ENDERMAN_TELEPORT"); - str = str.replace("ENTITY_ZOMBIE_ATTACK_IRON_DOOR", "ZOMBIE_METAL"); - str = str.replace("BLOCK_GRAVEL_BREAK", "DIG_GRAVEL"); - str = str.replace("BLOCK_SNOW_BREAK", "DIG_SNOW"); - str = str.replace("BLOCK_GRAVEL_BREAK", "DIG_GRAVEL"); - str = str.replace("ENTITY_PLAYER_LEVELUP", "LEVEL_UP"); - str = str.replace("ENTITY_SNOWBALL_THROW", "SHOOT_ARROW"); - - str = str.replace("ENTITY_", ""); - str = str.replace("GENERIC_", ""); - str = str.replace("BLOCK_", ""); - str = str.replace("_AMBIENT", ""); - str = str.replace("_BREAK", ""); - str = str.replace("PLAYER_ATTACK_CRIT", "ITEM_BREAK"); - str = str.replace("ENDERMEN", "ENDERMAN"); - str = str.replace("ARROW_SHOOT", "SHOOT_ARROW"); - str = str.replace("UI_BUTTON_", ""); - str = str.replace("ENDERMAN_HURT", "ENDERMAN_HIT"); - str = str.replace("BLAZE_HURT", "BLAZE_HIT"); - str = str.replace("_FLAP", "_WINGS"); - str = str.replace("EXPERIENCE_", ""); - } - return str; - } + + public static void sound(Location paramLocation, String paramString, float paramFloat1, float paramFloat2) { + String str = getModifiedSound(paramString); + try { + paramLocation.getWorld().playSound(paramLocation, Sound.valueOf(str), paramFloat1, paramFloat2); + } catch (Exception localException) { + MsgUtils.send("§4Bug with " + paramString + ". No such sound found. Please report it to the plugin creator :)"); + } + } + + static String getModifiedSound(String str) { + if (TabooLib.getVerint() < 10900) { + str = str.replace("BLOCK_FIRE_EXTINGUISH", "FIZZ"); + str = str.replace("BLOCK_NOTE_HAT", "NOTE_STICKS"); + str = str.replace("ENTITY_SHEEP_DEATH", "SHEEP_IDLE"); + str = str.replace("ENTITY_LLAMA_ANGRY", "HORSE_HIT"); + str = str.replace("BLOCK_BREWING_STAND_BREW", "CREEPER_HISS"); + str = str.replace("ENTITY_SHULKER_TELEPORT", "ENDERMAN_TELEPORT"); + str = str.replace("ENTITY_ZOMBIE_ATTACK_IRON_DOOR", "ZOMBIE_METAL"); + str = str.replace("BLOCK_GRAVEL_BREAK", "DIG_GRAVEL"); + str = str.replace("BLOCK_SNOW_BREAK", "DIG_SNOW"); + str = str.replace("BLOCK_GRAVEL_BREAK", "DIG_GRAVEL"); + str = str.replace("ENTITY_PLAYER_LEVELUP", "LEVEL_UP"); + str = str.replace("ENTITY_SNOWBALL_THROW", "SHOOT_ARROW"); + str = str.replace("PLAYER_ATTACK_CRIT", "ITEM_BREAK"); + str = str.replace("ENDERMEN", "ENDERMAN"); + str = str.replace("ARROW_SHOOT", "SHOOT_ARROW"); + str = str.replace("ENDERMAN_HURT", "ENDERMAN_HIT"); + str = str.replace("BLAZE_HURT", "BLAZE_HIT"); + str = str.replace("_FLAP", "_WINGS"); + str = str.replaceAll("ENTITY_|GENERIC_|BLOCK_|_AMBIENT|_BREAK|UI_BUTTON_|EXPERIENCE_", ""); + } + return str; + } } diff --git a/src/main/java/me/skymc/taboolib/string/language2/Language2.java b/src/main/java/me/skymc/taboolib/string/language2/Language2.java index ca3047c..09af73a 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/Language2.java +++ b/src/main/java/me/skymc/taboolib/string/language2/Language2.java @@ -1,92 +1,105 @@ package me.skymc.taboolib.string.language2; -import java.io.File; -import java.io.FileNotFoundException; - +import me.clip.placeholderapi.PlaceholderAPI; +import me.skymc.taboolib.fileutils.ConfigUtils; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -import lombok.Getter; -import me.clip.placeholderapi.PlaceholderAPI; -import me.skymc.taboolib.fileutils.ConfigUtils; +import java.io.File; +import java.io.FileNotFoundException; /** * @author sky * @since 2018年2月13日 下午2:37:07 */ public class Language2 { - - @Getter - private FileConfiguration configuration; - @Getter - private File languageFile; - @Getter - private File languageFolder; - @Getter - private Plugin plugin; - @Getter - private String languageName; - - public Language2(Plugin plugin) { - this("zh_CN", plugin); - } - - public Language2(String languageName, Plugin plugin) { - this.languageName = languageName; - this.plugin = plugin; - reload(languageName); - } - - public Language2Value get(String key) { - return new Language2Value(this, key); - } - - public Language2Value get(String key, String... placeholder) { - Language2Value value = new Language2Value(this, key); - for (int i = 0 ; i < placeholder.length ; i++) { - value.addPlaceholder("$" + i, placeholder[i]); - } - return value; - } - - public void reload() { - reload(this.languageName); - } - - public void reload(String languageName) { - createFolder(plugin); - languageName = formatName(languageName); - languageFile = new File(languageFolder, languageName); - if (!languageFile.exists()) { - if (plugin.getResource("Language2/" + languageName) == null) { - try { - throw new FileNotFoundException("语言文件 " + languageName + " 不存在"); - } catch (Exception ignored) { - } - } else { - plugin.saveResource("Language2/" + languageName, true); - } - } - configuration = ConfigUtils.load(plugin, languageFile); - } - - public String setPlaceholderAPI(Player player, String string) { - if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null && player != null) { - return PlaceholderAPI.setPlaceholders(player, string); - } - return string; - } - - private String formatName(String name) { - return name.contains(".yml") ? name : name + ".yml"; - } - - private void createFolder(Plugin plugin) { - languageFolder = new File(plugin.getDataFolder(), "Language2"); - if (!languageFolder.exists()) { - languageFolder.mkdir(); - } - } + + private FileConfiguration configuration; + private File languageFile; + private File languageFolder; + private Plugin plugin; + private String languageName; + + public FileConfiguration getConfiguration() { + return configuration; + } + + public File getLanguageFile() { + return languageFile; + } + + public File getLanguageFolder() { + return languageFolder; + } + + public Plugin getPlugin() { + return plugin; + } + + public String getLanguageName() { + return languageName; + } + + public Language2(Plugin plugin) { + this("zh_CN", plugin); + } + + public Language2(String languageName, Plugin plugin) { + this.languageName = languageName; + this.plugin = plugin; + reload(languageName); + } + + public Language2Value get(String key) { + return new Language2Value(this, key); + } + + public Language2Value get(String key, String... placeholder) { + Language2Value value = new Language2Value(this, key); + for (int i = 0; i < placeholder.length; i++) { + value.addPlaceholder("$" + i, placeholder[i]); + } + return value; + } + + public void reload() { + reload(this.languageName); + } + + public void reload(String languageName) { + createFolder(plugin); + languageName = formatName(languageName); + languageFile = new File(languageFolder, languageName); + if (!languageFile.exists()) { + if (plugin.getResource("Language2/" + languageName) == null) { + try { + throw new FileNotFoundException("语言文件 " + languageName + " 不存在"); + } catch (Exception ignored) { + } + } else { + plugin.saveResource("Language2/" + languageName, true); + } + } + configuration = ConfigUtils.load(plugin, languageFile); + } + + public String setPlaceholderAPI(Player player, String string) { + if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null && player != null) { + return PlaceholderAPI.setPlaceholders(player, string); + } + return string; + } + + private String formatName(String name) { + return name.contains(".yml") ? name : name + ".yml"; + } + + private void createFolder(Plugin plugin) { + languageFolder = new File(plugin.getDataFolder(), "Language2"); + if (!languageFolder.exists()) { + languageFolder.mkdir(); + } + } } diff --git a/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java b/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java index b2ecc8b..87d13ee 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java +++ b/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java @@ -1,116 +1,112 @@ package me.skymc.taboolib.string.language2; +import me.skymc.taboolib.string.language2.value.*; +import org.bukkit.entity.Player; + import java.util.ArrayList; import java.util.LinkedList; import java.util.List; -import org.bukkit.entity.Player; - -import lombok.Getter; -import me.skymc.taboolib.string.language2.value.Language2Action; -import me.skymc.taboolib.string.language2.value.Language2Book; -import me.skymc.taboolib.string.language2.value.Language2Json; -import me.skymc.taboolib.string.language2.value.Language2Json2; -import me.skymc.taboolib.string.language2.value.Language2Sound; -import me.skymc.taboolib.string.language2.value.Language2Text; -import me.skymc.taboolib.string.language2.value.Language2Title; - /** * @author sky * @since 2018-03-08 22:45:56 */ public class Language2Format implements Language2Line { - - @Getter - private Language2Value language2Value = null; - - @Getter - private List language2Lines = new ArrayList<>(); - - public Language2Format(Player player, Language2Value value) { - language2Value = value; - // 语言类型 - Language2Type type = Language2Type.TEXT; - // 递交数据 - List values = new LinkedList<>(); - - // 遍历内容 - for (String line : value.getLanguageValue()) { - // 文本类型 - if (line.contains("[text]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.TEXT; - } - // 大标题 - else if (line.contains("[title]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.TITLE; - } - // 小标题 - else if (line.contains("[action]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.ACTION; - } - // JSON - else if (line.contains("[json]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.JSON; - } - // JSON2 - else if (line.contains("[json2]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.JSON2; - } - // 音效 - else if (line.contains("[sound]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.SOUND; - } - // 书本 - else if (line.contains("[book]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.BOOK; - } - else if (line.contains("[return]")) { - // 递交数据 - parseValue(player, values, type); - } - // 默认 - else { - // 追加内容 - values.add(line); - } - } - } - - /** - * 识别内容 - * - * @param player 玩家 - * @param list 数据 - * @param type 类型 - */ - private void parseValue(Player player, List list, Language2Type type) { - if (list.size() == 0) { - return; - } - // 变量转换 - List listPlaceholder = language2Value.setPlaceholder(list, player); - // 大标题 + + private Language2Value language2Value; + private List language2Lines = new ArrayList<>(); + + public Language2Value getLanguage2Value() { + return language2Value; + } + + public List getLanguage2Lines() { + return language2Lines; + } + + public Language2Format(Player player, Language2Value value) { + language2Value = value; + // 语言类型 + Language2Type type = Language2Type.TEXT; + // 递交数据 + List values = new LinkedList<>(); + + // 遍历内容 + for (String line : value.getLanguageValue()) { + // 文本类型 + if (line.contains("[text]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.TEXT; + } + // 大标题 + else if (line.contains("[title]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.TITLE; + } + // 小标题 + else if (line.contains("[action]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.ACTION; + } + // JSON + else if (line.contains("[json]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.JSON; + } + // JSON2 + else if (line.contains("[json2]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.JSON2; + } + // 音效 + else if (line.contains("[sound]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.SOUND; + } + // 书本 + else if (line.contains("[book]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.BOOK; + } else if (line.contains("[return]")) { + // 递交数据 + parseValue(player, values, type); + } + // 默认 + else { + // 追加内容 + values.add(line); + } + } + } + + /** + * 识别内容 + * + * @param player 玩家 + * @param list 数据 + * @param type 类型 + */ + private void parseValue(Player player, List list, Language2Type type) { + if (list.size() == 0) { + return; + } + // 变量转换 + List listPlaceholder = language2Value.setPlaceholder(list, player); + // 大标题 switch (type) { case TITLE: language2Lines.add(new Language2Title(this, listPlaceholder)); @@ -138,23 +134,23 @@ public class Language2Format implements Language2Line { default: language2Lines.add(new Language2Text(this, listPlaceholder)); break; - } - // 清理数据 - list.clear(); - listPlaceholder.clear(); - } + } + // 清理数据 + list.clear(); + listPlaceholder.clear(); + } - @Override - public void send(Player player) { - for (Language2Line line : language2Lines) { - line.send(player); - } - } + @Override + public void send(Player player) { + for (Language2Line line : language2Lines) { + line.send(player); + } + } - @Override - public void console() { - for (Language2Line line : language2Lines) { - line.console(); - } - } + @Override + public void console() { + for (Language2Line line : language2Lines) { + line.console(); + } + } } diff --git a/src/main/java/me/skymc/taboolib/string/language2/Language2Value.java b/src/main/java/me/skymc/taboolib/string/language2/Language2Value.java index 9f2abd5..ab47ae5 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/Language2Value.java +++ b/src/main/java/me/skymc/taboolib/string/language2/Language2Value.java @@ -1,214 +1,219 @@ package me.skymc.taboolib.string.language2; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map.Entry; - +import me.skymc.taboolib.string.language2.value.Language2Text; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import lombok.Getter; -import me.skymc.taboolib.string.language2.value.Language2Text; +import java.util.*; +import java.util.Map.Entry; /** * @author sky * @since 2018年2月13日 下午3:05:15 */ public class Language2Value { - - @Getter - private Language2 language; - - @Getter - private String languageKey; - - @Getter - private List languageValue; - - @Getter - private LinkedHashMap placeholder = new LinkedHashMap<>(); - - @Getter - private boolean enablePlaceholderAPI = false; - - /** - * 构造方法 - */ - public Language2Value(Language2 language, String languageKey) { - // 如果语言文件不存在 - if (language == null || languageKey == null) { - languageValue = Arrays.asList(ChatColor.DARK_RED + "[]", "[return]"); - return; - } - - // 如果语言文本不存在 - if (!language.getConfiguration().contains(languageKey)) { - languageValue = Arrays.asList(ChatColor.DARK_RED + "[]", "[return]"); - return; - } - - // 如果不是集合类型 - if (language.getConfiguration().get(languageKey) instanceof List) { - // 设置文本 - languageValue = asColored(language.getConfiguration().getStringList(languageKey)); - // 追加结尾 - languageValue.add("[return]"); - // 是否启用PAPI - if (languageValue.get(0).contains("[papi]")) { - enablePlaceholderAPI = true; - } - } - else { - // 设置文本 - languageValue = Arrays.asList(ChatColor.translateAlternateColorCodes('&', language.getConfiguration().getString(languageKey)), "[return]"); - } - - // 初始化变量 - this.language = language; - this.languageKey = languageKey; - } - - /** - * 向玩家发送信息 - * - * @param player - */ - public void send(Player player) { - new Language2Format(player, this).send(player); - } - - /** - * 向玩家发送信息 - * - * @param players 玩家 - */ - public void send(List players) { - for (Player player : players) { - send(player); - } - } - - /** - * 向指令发送者发送信息 - * - * @param sender - */ - public void send(CommandSender sender) { - if (sender instanceof Player) { - send((Player) sender); - } - else { - console(); - } - } - - /** - * 全服公告 - */ - public void broadcast() { - send(new ArrayList<>(Bukkit.getOnlinePlayers())); - } - - /** - * 发送到后台 - */ - public void console() { - new Language2Format(null, this).console(); - } - - /** - * 获取文本 - * - * @return - */ - public String asString() { - Language2Format format = new Language2Format(null, this); - if (format.getLanguage2Lines().get(0) instanceof Language2Text) { - Language2Text text = (Language2Text) format.getLanguage2Lines().get(0); - return setPlaceholder(text.getText().get(0), null); - } - else { - return languageValue.size() == 0 ? ChatColor.DARK_RED + "[]" : setPlaceholder(languageValue.get(0), null); - } - } - - /** - * 获取文本集合 - * - * @return - */ - public List asStringList() { - Language2Format format = new Language2Format(null, this); - if (format.getLanguage2Lines().get(0) instanceof Language2Text) { - Language2Text text = (Language2Text) format.getLanguage2Lines().get(0); - return setPlaceholder(text.getText(), null); - } - else { - return Collections.singletonList(languageValue.size() == 0 ? ChatColor.DARK_RED + "[]" : setPlaceholder(languageValue.get(0), null)); - } - } - - /** - * 变量替换 - * - * @param value 替换文本 - * @param player 检测玩家 - * @return String - */ - public String setPlaceholder(String value, Player player) { - for (Entry entry : placeholder.entrySet()) { - value = value.replace(entry.getKey(), entry.getValue()); - } - return isEnablePlaceholderAPI() ? this.language.setPlaceholderAPI(player, value) : value; - } - - /** - * 变量替换 - * - * @param list 替换集合 - * @param player 检测玩家 - * @return {@link List} - */ - public List setPlaceholder(List list, Player player) { - List _list = new ArrayList<>(list); - for (int i = 0 ; i < _list.size() ; i++) { - _list.set(i, setPlaceholder(_list.get(i), player)); - } - return _list; - } - - /** - * 变量替换构造 - * - * @param key 键 - * @param value 值 - * @return {@link Language2Value} - */ - public Language2Value addPlaceholder(String key, String value) { - this.placeholder.put(key, value); - return this; - } - - /** - * 替换颜色 - * - * @param list - * @return - */ - public List asColored(List list) { - for (int i = 0 ; i < list.size() ; i++) { - list.set(i, ChatColor.translateAlternateColorCodes('&', list.get(i))); - } - return list; - } - - @Override - public String toString() { - return asString(); - } + + private Language2 language; + + private String languageKey; + + private List languageValue; + + private LinkedHashMap placeholder = new LinkedHashMap<>(); + + private boolean enablePlaceholderAPI = false; + + public Language2 getLanguage() { + return language; + } + + public String getLanguageKey() { + return languageKey; + } + + public List getLanguageValue() { + return languageValue; + } + + public LinkedHashMap getPlaceholder() { + return placeholder; + } + + public boolean isEnablePlaceholderAPI() { + return enablePlaceholderAPI; + } + + /** + * 构造方法 + */ + public Language2Value(Language2 language, String languageKey) { + // 如果语言文件不存在 + if (language == null || languageKey == null) { + languageValue = Arrays.asList(ChatColor.DARK_RED + "[]", "[return]"); + return; + } + + // 如果语言文本不存在 + if (!language.getConfiguration().contains(languageKey)) { + languageValue = Arrays.asList(ChatColor.DARK_RED + "[]", "[return]"); + return; + } + + // 如果不是集合类型 + if (language.getConfiguration().get(languageKey) instanceof List) { + // 设置文本 + languageValue = asColored(language.getConfiguration().getStringList(languageKey)); + // 追加结尾 + languageValue.add("[return]"); + // 是否启用PAPI + if (languageValue.get(0).contains("[papi]")) { + enablePlaceholderAPI = true; + } + } else { + // 设置文本 + languageValue = Arrays.asList(ChatColor.translateAlternateColorCodes('&', language.getConfiguration().getString(languageKey)), "[return]"); + } + + // 初始化变量 + this.language = language; + this.languageKey = languageKey; + } + + /** + * 向玩家发送信息 + * + * @param player + */ + public void send(Player player) { + new Language2Format(player, this).send(player); + } + + /** + * 向玩家发送信息 + * + * @param players 玩家 + */ + public void send(List players) { + for (Player player : players) { + send(player); + } + } + + /** + * 向指令发送者发送信息 + * + * @param sender + */ + public void send(CommandSender sender) { + if (sender instanceof Player) { + send((Player) sender); + } else { + console(); + } + } + + /** + * 全服公告 + */ + public void broadcast() { + send(new ArrayList<>(Bukkit.getOnlinePlayers())); + } + + /** + * 发送到后台 + */ + public void console() { + new Language2Format(null, this).console(); + } + + /** + * 获取文本 + * + * @return + */ + public String asString() { + Language2Format format = new Language2Format(null, this); + if (format.getLanguage2Lines().get(0) instanceof Language2Text) { + Language2Text text = (Language2Text) format.getLanguage2Lines().get(0); + return setPlaceholder(text.getText().get(0), null); + } else { + return languageValue.size() == 0 ? ChatColor.DARK_RED + "[]" : setPlaceholder(languageValue.get(0), null); + } + } + + /** + * 获取文本集合 + * + * @return + */ + public List asStringList() { + Language2Format format = new Language2Format(null, this); + if (format.getLanguage2Lines().get(0) instanceof Language2Text) { + Language2Text text = (Language2Text) format.getLanguage2Lines().get(0); + return setPlaceholder(text.getText(), null); + } else { + return Collections.singletonList(languageValue.size() == 0 ? ChatColor.DARK_RED + "[]" : setPlaceholder(languageValue.get(0), null)); + } + } + + /** + * 变量替换 + * + * @param value 替换文本 + * @param player 检测玩家 + * @return String + */ + public String setPlaceholder(String value, Player player) { + for (Entry entry : placeholder.entrySet()) { + value = value.replace(entry.getKey(), entry.getValue()); + } + return isEnablePlaceholderAPI() ? this.language.setPlaceholderAPI(player, value) : value; + } + + /** + * 变量替换 + * + * @param list 替换集合 + * @param player 检测玩家 + * @return {@link List} + */ + public List setPlaceholder(List list, Player player) { + List _list = new ArrayList<>(list); + for (int i = 0; i < _list.size(); i++) { + _list.set(i, setPlaceholder(_list.get(i), player)); + } + return _list; + } + + /** + * 变量替换构造 + * + * @param key 键 + * @param value 值 + * @return {@link Language2Value} + */ + public Language2Value addPlaceholder(String key, String value) { + this.placeholder.put(key, value); + return this; + } + + /** + * 替换颜色 + * + * @param list + * @return + */ + public List asColored(List list) { + for (int i = 0; i < list.size(); i++) { + list.set(i, ChatColor.translateAlternateColorCodes('&', list.get(i))); + } + return list; + } + + @Override + public String toString() { + return asString(); + } } diff --git a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Action.java b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Action.java index 2b07307..9e278bc 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Action.java +++ b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Action.java @@ -1,13 +1,5 @@ package me.skymc.taboolib.string.language2.value; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; - -import lombok.Getter; import me.skymc.taboolib.Main; import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.display.ActionUtils; @@ -15,81 +7,94 @@ import me.skymc.taboolib.other.NumberUtils; import me.skymc.taboolib.string.language2.Language2Format; import me.skymc.taboolib.string.language2.Language2Line; import me.skymc.taboolib.string.language2.Language2Value; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.List; /** * @author sky * @since 2018年2月13日 下午3:58:07 */ public class Language2Action implements Language2Line { - - private static final String KEY_TEXT = " text: "; - private static final String KEY_STAY = " repeat: "; - - @Getter - private String text = ""; - - @Getter - private int repeat = 1; - - @Getter - private Language2Value value; - - public Language2Action(Language2Format format, List list) { - // 变量初始化 - this.value = format.getLanguage2Value(); - // 遍历文本 - for (String message : list) { - try { - // 动作栏提示 - if (message.startsWith(KEY_TEXT)) { - text = message.substring(KEY_TEXT.length()); - } - // 持续时间 - if (message.startsWith(KEY_STAY)) { - repeat = NumberUtils.getInteger(message.substring(KEY_STAY.length())); - } - } - catch (Exception e) { - // 识别异常 - text = ChatColor.DARK_RED + "[]"; - } - } - - // 检查重复次数 - if (repeat < 0) { - repeat = 1; - text = ChatColor.DARK_RED + "[]"; - } - } - - /** - * 发送给玩家 - * - * @param player 玩家 - */ - @Override - public void send(Player player) { - // 检查版本 - if (TabooLib.getVerint() < 10800) { - player.sendMessage(ChatColor.DARK_RED + "[]"); - } - else { - new BukkitRunnable() { - int times = 0; - - @Override - public void run() { - ActionUtils.send(player, text); - if ((times += 1) >= repeat) { - cancel(); - } - } - }.runTaskTimer(Main.getInst(), 0, 20); - } - } - @Override - public void console() { - Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); - } + private static final String KEY_TEXT = " text: "; + private static final String KEY_STAY = " repeat: "; + + private String text = ""; + + private int repeat = 1; + + private Language2Value value; + + public String getText() { + return text; + } + + public int getRepeat() { + return repeat; + } + + public Language2Value getValue() { + return value; + } + + public Language2Action(Language2Format format, List list) { + // 变量初始化 + this.value = format.getLanguage2Value(); + // 遍历文本 + for (String message : list) { + try { + // 动作栏提示 + if (message.startsWith(KEY_TEXT)) { + text = message.substring(KEY_TEXT.length()); + } + // 持续时间 + if (message.startsWith(KEY_STAY)) { + repeat = NumberUtils.getInteger(message.substring(KEY_STAY.length())); + } + } catch (Exception e) { + // 识别异常 + text = ChatColor.DARK_RED + "[]"; + } + } + + // 检查重复次数 + if (repeat < 0) { + repeat = 1; + text = ChatColor.DARK_RED + "[]"; + } + } + + /** + * 发送给玩家 + * + * @param player 玩家 + */ + @Override + public void send(Player player) { + // 检查版本 + if (TabooLib.getVerint() < 10800) { + player.sendMessage(ChatColor.DARK_RED + "[]"); + } else { + new BukkitRunnable() { + int times = 0; + + @Override + public void run() { + ActionUtils.send(player, text); + if ((times += 1) >= repeat) { + cancel(); + } + } + }.runTaskTimer(Main.getInst(), 0, 20); + } + } + + @Override + public void console() { + Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); + } } 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 7a0957e..5a8c2ff 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 @@ -1,19 +1,5 @@ package me.skymc.taboolib.string.language2.value; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import lombok.Getter; import me.skymc.taboolib.bookformatter.BookFormatter; import me.skymc.taboolib.bookformatter.action.ClickAction; import me.skymc.taboolib.bookformatter.action.HoverAction; @@ -25,190 +11,207 @@ import me.skymc.taboolib.other.NumberUtils; import me.skymc.taboolib.string.language2.Language2Format; import me.skymc.taboolib.string.language2.Language2Line; import me.skymc.taboolib.string.language2.Language2Value; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * @author sky * @since 2018-03-10 15:55:28 */ public class Language2Book implements Language2Line { - - private static final String KEY_TEXT = " text: "; - private static final String KEY_COMMAND = " command: "; - private static final String KEY_SUGGEST = " suggest: "; - private static final String KEY_URL = " url: "; - private static final String KEY_PAGE = " page: "; - private static final String KEY_SHOWTEXT = " showtext: "; - private static final String KEY_SHOWITEM = " showitem: "; - private static final String KEY_OPTION = "@option:"; - private static final Pattern pattern = Pattern.compile("<@(\\S+)>"); - - @Getter - private Player player; - - @Getter - private Language2Value value; - - @Getter - private HashMap options = new HashMap<>(); - - @Getter - private BookBuilder book; - - public Language2Book(Language2Format format, List list, Player player) { - // 变量 - this.player = player; - this.value = format.getLanguage2Value(); - - // 获取书本设置 - formatOptions(list); - // 书本 - book = BookFormatter.writtenBook(); - // 内容 - PageBuilder page = new PageBuilder(); - // 遍历内容 - for (String line : list) { - // 翻页 - if (line.equals("[page]")) { - book.addPages(page.build()); - page = new PageBuilder(); - } - // 设置 - else if (line.startsWith("@option")) { - break; - } - else { - Matcher matcher = pattern.matcher(line); - boolean find = false; - while (matcher.find()) { - find = true; - String optionName = matcher.group(1); - String optionFullName = "<@" + matcher.group(1) + ">"; - // 判断设置是否存在 - if (!options.containsKey(optionName)) { - page.add("§4[]"); - } - else { - String[] line_split = line.split(optionFullName); - try { - // 单独一行 - if (line_split.length == 0) { - page.add(options.get(optionName).build()).endLine(); - } else { - // 前段 - page.add(line_split[0]); - // 变量 - page.add(options.get(optionName).build()); - // 后段 - if (line_split.length >= 2) { - // 获取文本 - StringBuilder sb = new StringBuilder(); - for (int i = 1 ; i < line_split.length ; i++) { + + private static final String KEY_TEXT = " text: "; + private static final String KEY_COMMAND = " command: "; + private static final String KEY_SUGGEST = " suggest: "; + private static final String KEY_URL = " url: "; + private static final String KEY_PAGE = " page: "; + private static final String KEY_SHOWTEXT = " showtext: "; + private static final String KEY_SHOWITEM = " showitem: "; + private static final String KEY_OPTION = "@option:"; + private static final Pattern pattern = Pattern.compile("<@(\\S+)>"); + + private Player player; + + private Language2Value value; + + private HashMap options = new HashMap<>(); + + private BookBuilder book; + + public static Pattern getPattern() { + return pattern; + } + + public Player getPlayer() { + return player; + } + + public Language2Value getValue() { + return value; + } + + public HashMap getOptions() { + return options; + } + + public BookBuilder getBook() { + return book; + } + + public Language2Book(Language2Format format, List list, Player player) { + // 变量 + this.player = player; + this.value = format.getLanguage2Value(); + + // 获取书本设置 + formatOptions(list); + // 书本 + book = BookFormatter.writtenBook(); + // 内容 + PageBuilder page = new PageBuilder(); + // 遍历内容 + for (String line : list) { + // 翻页 + if (line.equals("[page]")) { + book.addPages(page.build()); + page = new PageBuilder(); + } + // 设置 + else if (line.startsWith("@option")) { + break; + } else { + Matcher matcher = pattern.matcher(line); + boolean find = false; + while (matcher.find()) { + find = true; + String optionName = matcher.group(1); + String optionFullName = "<@" + matcher.group(1) + ">"; + // 判断设置是否存在 + if (!options.containsKey(optionName)) { + page.add("§4[]"); + } else { + String[] line_split = line.split(optionFullName); + try { + // 单独一行 + if (line_split.length == 0) { + page.add(options.get(optionName).build()).endLine(); + } else { + // 前段 + page.add(line_split[0]); + // 变量 + page.add(options.get(optionName).build()); + // 后段 + if (line_split.length >= 2) { + // 获取文本 + StringBuilder sb = new StringBuilder(); + for (int i = 1; i < line_split.length; i++) { sb.append(line_split[i]).append(optionFullName); - } - // 更改文本 - line = sb.substring(0, sb.length() - optionFullName.length()); - // 如果后段还有变量 - if (!pattern.matcher(line).find()) { - page.add(line_split[1]).endLine(); - } - } else { - page.endLine(); - } - } - } - catch (Exception e) { - page.add("§4[]"); - } - } - } - if (!find) { - page.add(line).endLine(); - } - } - } - // 结尾 - book.addPages(page.build()); - } - - private void formatOptions(List list) { - // 获取书本设置 - HashMap> _options = getOptions(list); - for (Entry> entry : _options.entrySet()) { - TextBuilder builder = new TextBuilder(); - // 遍历内容 - for (String _option : entry.getValue()) { - if (_option.startsWith(KEY_TEXT)) { - builder.text(_option.substring(KEY_TEXT.length())); - } - else if (_option.startsWith(KEY_COMMAND)) { - builder.onClick(ClickAction.runCommand(_option.substring(KEY_COMMAND.length()))); - } - else if (_option.startsWith(KEY_SUGGEST)) { - builder.onClick(ClickAction.suggestCommand(_option.substring(KEY_SUGGEST.length()))); - } - else if (_option.startsWith(KEY_URL)) { - try { - builder.onClick(ClickAction.openUrl(_option.substring(KEY_URL.length()))); - } - catch (Exception e) { - builder.text("§4[]"); - } - } - else if (_option.startsWith(KEY_PAGE)) { - builder.onClick(ClickAction.changePage(NumberUtils.getInteger(_option.substring(KEY_PAGE.length())))); - } - else if (_option.startsWith(KEY_SHOWTEXT)) { - builder.onHover(HoverAction.showText(_option.substring(KEY_SHOWTEXT.length()))); - } - else if (_option.startsWith(KEY_SHOWITEM)) { - ItemStack item = ItemUtils.getCacheItem(_option.substring(KEY_SHOWITEM.length())); - if (item == null) { - item = new ItemStack(Material.STONE); - } - builder.onHover(HoverAction.showItem(item)); - } - } - options.put(entry.getKey(), builder); - } - } - - private HashMap> getOptions(List list) { - HashMap> options_source = new HashMap<>(); - List option = new ArrayList<>(); - // 遍历 - String optionName = null; - boolean start = false; - // 遍历所有代码 - for (String line : list) { - if (line.startsWith(KEY_OPTION)) { - // 如果已经开始检测 - if (start) { - // 返回源码 - options_source.put(optionName, new ArrayList<>(option)); - // 清除源码 - option.clear(); - } - // 标签 - start = true; - // 当前设置名称 - optionName = line.substring(KEY_OPTION.length()); - } - else if (start) { - option.add(line); - } - } - // 返回最后设置 - options_source.put(optionName, option); - return options_source; - } + } + // 更改文本 + line = sb.substring(0, sb.length() - optionFullName.length()); + // 如果后段还有变量 + if (!pattern.matcher(line).find()) { + page.add(line_split[1]).endLine(); + } + } else { + page.endLine(); + } + } + } catch (Exception e) { + page.add("§4[]"); + } + } + } + if (!find) { + page.add(line).endLine(); + } + } + } + // 结尾 + book.addPages(page.build()); + } - @Override - public void send(Player player) { - BookFormatter.forceOpen(player, book.build()); - } + private void formatOptions(List list) { + // 获取书本设置 + HashMap> _options = getOptions(list); + for (Entry> entry : _options.entrySet()) { + TextBuilder builder = new TextBuilder(); + // 遍历内容 + for (String _option : entry.getValue()) { + if (_option.startsWith(KEY_TEXT)) { + builder.text(_option.substring(KEY_TEXT.length())); + } else if (_option.startsWith(KEY_COMMAND)) { + builder.onClick(ClickAction.runCommand(_option.substring(KEY_COMMAND.length()))); + } else if (_option.startsWith(KEY_SUGGEST)) { + builder.onClick(ClickAction.suggestCommand(_option.substring(KEY_SUGGEST.length()))); + } else if (_option.startsWith(KEY_URL)) { + try { + builder.onClick(ClickAction.openUrl(_option.substring(KEY_URL.length()))); + } catch (Exception e) { + builder.text("§4[]"); + } + } else if (_option.startsWith(KEY_PAGE)) { + builder.onClick(ClickAction.changePage(NumberUtils.getInteger(_option.substring(KEY_PAGE.length())))); + } else if (_option.startsWith(KEY_SHOWTEXT)) { + builder.onHover(HoverAction.showText(_option.substring(KEY_SHOWTEXT.length()))); + } else if (_option.startsWith(KEY_SHOWITEM)) { + ItemStack item = ItemUtils.getCacheItem(_option.substring(KEY_SHOWITEM.length())); + if (item == null) { + item = new ItemStack(Material.STONE); + } + builder.onHover(HoverAction.showItem(item)); + } + } + options.put(entry.getKey(), builder); + } + } - @Override - public void console() { - Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); - } + private HashMap> getOptions(List list) { + HashMap> options_source = new HashMap<>(); + List option = new ArrayList<>(); + // 遍历 + String optionName = null; + boolean start = false; + // 遍历所有代码 + for (String line : list) { + if (line.startsWith(KEY_OPTION)) { + // 如果已经开始检测 + if (start) { + // 返回源码 + options_source.put(optionName, new ArrayList<>(option)); + // 清除源码 + option.clear(); + } + // 标签 + start = true; + // 当前设置名称 + optionName = line.substring(KEY_OPTION.length()); + } else if (start) { + option.add(line); + } + } + // 返回最后设置 + options_source.put(optionName, option); + return options_source; + } + + @Override + public void send(Player player) { + BookFormatter.forceOpen(player, book.build()); + } + + @Override + public void console() { + Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); + } } 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 eae95e5..7ba9745 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 @@ -1,14 +1,5 @@ package me.skymc.taboolib.string.language2.value; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import lombok.Getter; import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.jsonformatter.JSONFormatter; import me.skymc.taboolib.jsonformatter.click.ClickEvent; @@ -21,145 +12,163 @@ import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent; import me.skymc.taboolib.string.language2.Language2Format; import me.skymc.taboolib.string.language2.Language2Line; import me.skymc.taboolib.string.language2.Language2Value; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; /** * @author sky * @since 2018年2月13日 下午4:11:33 */ public class Language2Json implements Language2Line { - - private static final String KEY_TEXT = " text: "; - private static final String KEY_COMMAND = " command: "; - private static final String KEY_SUGGEST = " suggest: "; - private static final String KEY_URL = " url: "; - private static final String KEY_ITEM = " item: "; - - @Getter - private Player player; - - @Getter - private Language2Value value; - - @Getter - private JSONFormatter json = new JSONFormatter(); - - @Getter - private StringBuffer text = new StringBuffer(); - - public Language2Json(Language2Format format, List list, Player player) { - // 首次检测 - boolean isFirst = true; - boolean isBreak = false; - - // 变量初始化 - this.value = format.getLanguage2Value(); - this.player = player; - - // 动作初始化 - ClickEvent clickEvent = null; - HoverEvent hoverEvent = null; - - // 文本初始化 - String current = ChatColor.DARK_RED + "[]"; - - // 遍历文本 - for (String message : list) { - try { - // 如果是显示文本 - if (message.startsWith(KEY_TEXT)) { - hoverEvent = new ShowTextEvent(message.replace("||", "\n").substring(KEY_TEXT.length())); - } - // 显示物品 - else if (message.startsWith(KEY_ITEM)) { - ItemStack item = ItemUtils.getCacheItem(message.substring(KEY_ITEM.length())); - if (item == null) { - item = new ItemStack(Material.STONE); - } - hoverEvent = new ShowItemEvent(item); - } - // 执行指令 - else if (message.startsWith(KEY_COMMAND)) { - clickEvent = new RunCommandEvent(message.substring(KEY_COMMAND.length())); - } - // 打印指令 - else if (message.startsWith(KEY_SUGGEST)) { - clickEvent = new SuggestCommandEvent(message.substring(KEY_SUGGEST.length())); - } - // 打开连接 - else if (message.startsWith(KEY_URL)) { - clickEvent = new OpenUrlEvent(message.substring(KEY_URL.length())); - } - // 换行 - else if (message.equals("[break]")) { - append(current, clickEvent, hoverEvent); - // 删除动作 - clickEvent = null; - hoverEvent = null; - // 换行 - json.newLine(); - // 标记 - isBreak = true; - } - // 新内容 - else { - if (!isFirst && !isBreak) { - append(current, clickEvent, hoverEvent); - // 删除动作 - clickEvent = null; - hoverEvent = null; - } - // 更新 - current = message; - // 标记 - isFirst = false; - isBreak = false; - } - } - catch (Exception e) { - // 识别异常 - json.append(ChatColor.DARK_RED + "[]"); - } - } - // 追加 - append(current, clickEvent, hoverEvent); - } - - /** - * 发送给玩家 - * - * @param player 玩家 - */ - @Override - public void send(Player player) { - json.send(player); - } - - @Override - public void console() { - Bukkit.getConsoleSender().sendMessage(text.toString()); - } - /** - * 追加 JSON 内容 - * - * @param current 文本 - * @param hoverEvent 显示动作 - */ - private void append(String current, ClickEvent clickEvent, HoverEvent hoverEvent) { - if (clickEvent == null && hoverEvent == null) { - // 纯文本 - json.append(current); - } else if (clickEvent != null && hoverEvent == null) { - // 纯点击 - json.appendClick(current, clickEvent); - } else if (clickEvent == null && hoverEvent != null) { - // 纯显示 - json.appendHover(current, hoverEvent); - } else { - // 全部 - json.appendHoverClick(current, hoverEvent, clickEvent); - } - // 追加显示文本 - text.append(current); - } + private static final String KEY_TEXT = " text: "; + private static final String KEY_COMMAND = " command: "; + private static final String KEY_SUGGEST = " suggest: "; + private static final String KEY_URL = " url: "; + private static final String KEY_ITEM = " item: "; + + private Player player; + + private Language2Value value; + + private JSONFormatter json = new JSONFormatter(); + + private StringBuffer text = new StringBuffer(); + + public Player getPlayer() { + return player; + } + + public Language2Value getValue() { + return value; + } + + public JSONFormatter getJson() { + return json; + } + + public StringBuffer getText() { + return text; + } + + public Language2Json(Language2Format format, List list, Player player) { + // 首次检测 + boolean isFirst = true; + boolean isBreak = false; + + // 变量初始化 + this.value = format.getLanguage2Value(); + this.player = player; + + // 动作初始化 + ClickEvent clickEvent = null; + HoverEvent hoverEvent = null; + + // 文本初始化 + String current = ChatColor.DARK_RED + "[]"; + + // 遍历文本 + for (String message : list) { + try { + // 如果是显示文本 + if (message.startsWith(KEY_TEXT)) { + hoverEvent = new ShowTextEvent(message.replace("||", "\n").substring(KEY_TEXT.length())); + } + // 显示物品 + else if (message.startsWith(KEY_ITEM)) { + ItemStack item = ItemUtils.getCacheItem(message.substring(KEY_ITEM.length())); + if (item == null) { + item = new ItemStack(Material.STONE); + } + hoverEvent = new ShowItemEvent(item); + } + // 执行指令 + else if (message.startsWith(KEY_COMMAND)) { + clickEvent = new RunCommandEvent(message.substring(KEY_COMMAND.length())); + } + // 打印指令 + else if (message.startsWith(KEY_SUGGEST)) { + clickEvent = new SuggestCommandEvent(message.substring(KEY_SUGGEST.length())); + } + // 打开连接 + else if (message.startsWith(KEY_URL)) { + clickEvent = new OpenUrlEvent(message.substring(KEY_URL.length())); + } + // 换行 + else if (message.equals("[break]")) { + append(current, clickEvent, hoverEvent); + // 删除动作 + clickEvent = null; + hoverEvent = null; + // 换行 + json.newLine(); + // 标记 + isBreak = true; + } + // 新内容 + else { + if (!isFirst && !isBreak) { + append(current, clickEvent, hoverEvent); + // 删除动作 + clickEvent = null; + hoverEvent = null; + } + // 更新 + current = message; + // 标记 + isFirst = false; + isBreak = false; + } + } catch (Exception e) { + // 识别异常 + json.append(ChatColor.DARK_RED + "[]"); + } + } + // 追加 + append(current, clickEvent, hoverEvent); + } + + /** + * 发送给玩家 + * + * @param player 玩家 + */ + @Override + public void send(Player player) { + json.send(player); + } + + @Override + public void console() { + Bukkit.getConsoleSender().sendMessage(text.toString()); + } + + /** + * 追加 JSON 内容 + * + * @param current 文本 + * @param hoverEvent 显示动作 + */ + private void append(String current, ClickEvent clickEvent, HoverEvent hoverEvent) { + if (clickEvent == null && hoverEvent == null) { + // 纯文本 + json.append(current); + } else if (clickEvent != null && hoverEvent == null) { + // 纯点击 + json.appendClick(current, clickEvent); + } else if (clickEvent == null && hoverEvent != null) { + // 纯显示 + json.appendHover(current, hoverEvent); + } else { + // 全部 + json.appendHoverClick(current, hoverEvent, clickEvent); + } + // 追加显示文本 + text.append(current); + } } diff --git a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Json2.java b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Json2.java index 843cb87..0e3a257 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Json2.java +++ b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Json2.java @@ -1,19 +1,5 @@ package me.skymc.taboolib.string.language2.value; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import lombok.Getter; import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.jsonformatter.JSONFormatter; import me.skymc.taboolib.jsonformatter.click.ClickEvent; @@ -26,185 +12,203 @@ import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent; import me.skymc.taboolib.string.language2.Language2Format; import me.skymc.taboolib.string.language2.Language2Line; import me.skymc.taboolib.string.language2.Language2Value; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * @author sky * @since 2018-03-10 15:55:28 */ public class Language2Json2 implements Language2Line { - - private static final String KEY_TEXT = " text: "; - private static final String KEY_COMMAND = " command: "; - private static final String KEY_SUGGEST = " suggest: "; - private static final String KEY_URL = " url: "; - private static final String KEY_SHOWTEXT = " showtext: "; - private static final String KEY_SHOWITEM = " showitem: "; - private static final String KEY_OPTION = "@option:"; - private static final Pattern pattern = Pattern.compile("<@(\\S+)>"); - - @Getter - private Player player; - - @Getter - private Language2Value value; - - @Getter - private HashMap options = new HashMap<>(); - - @Getter - private JSONFormatter json = new JSONFormatter(); - - public Language2Json2(Language2Format format, List list, Player player) { - // 变量 - this.player = player; - this.value = format.getLanguage2Value(); - - // 获取书本设置 - formatOptions(list); - // 遍历内容 - int lineNumber = 0; - int lineNumberEnd = getLineNumberEnd(list); - for (String line : list) { - if (line.startsWith("@option")) { - break; - } else { - Matcher matcher = pattern.matcher(line); - boolean find = false; - while (matcher.find()) { - find = true; - String optionName = matcher.group(1); - String optionFullName = "<@" + matcher.group(1) + ">"; - // 判断设置是否存在 - if (!options.containsKey(optionName)) { - json.append("§4[]"); - } else { - String[] line_split = line.split(optionFullName); - try { - // 单独一行 - if (line_split.length == 0) { - json.append(options.get(optionName)); - } else { - // 前段 - json.append(line_split[0]); - // 变量 - json.append(options.get(optionName)); - // 后段 - if (line_split.length >= 2) { - // 获取文本 - StringBuilder sb = new StringBuilder(); - for (int i = 1 ; i < line_split.length ; i++) { + + private static final String KEY_TEXT = " text: "; + private static final String KEY_COMMAND = " command: "; + private static final String KEY_SUGGEST = " suggest: "; + private static final String KEY_URL = " url: "; + private static final String KEY_SHOWTEXT = " showtext: "; + private static final String KEY_SHOWITEM = " showitem: "; + private static final String KEY_OPTION = "@option:"; + private static final Pattern pattern = Pattern.compile("<@(\\S+)>"); + + private Player player; + + private Language2Value value; + + private HashMap options = new HashMap<>(); + + private JSONFormatter json = new JSONFormatter(); + + public Player getPlayer() { + return player; + } + + public Language2Value getValue() { + return value; + } + + public HashMap getOptions() { + return options; + } + + public JSONFormatter getJson() { + return json; + } + + public Language2Json2(Language2Format format, List list, Player player) { + // 变量 + this.player = player; + this.value = format.getLanguage2Value(); + + // 获取书本设置 + formatOptions(list); + // 遍历内容 + int lineNumber = 0; + int lineNumberEnd = getLineNumberEnd(list); + for (String line : list) { + if (line.startsWith("@option")) { + break; + } else { + Matcher matcher = pattern.matcher(line); + boolean find = false; + while (matcher.find()) { + find = true; + String optionName = matcher.group(1); + String optionFullName = "<@" + matcher.group(1) + ">"; + // 判断设置是否存在 + if (!options.containsKey(optionName)) { + json.append("§4[]"); + } else { + String[] line_split = line.split(optionFullName); + try { + // 单独一行 + if (line_split.length == 0) { + json.append(options.get(optionName)); + } else { + // 前段 + json.append(line_split[0]); + // 变量 + json.append(options.get(optionName)); + // 后段 + if (line_split.length >= 2) { + // 获取文本 + StringBuilder sb = new StringBuilder(); + for (int i = 1; i < line_split.length; i++) { sb.append(line_split[i]).append(optionFullName); - } - // 更改文本 - line = sb.substring(0, sb.length() - optionFullName.length()); - // 如果后段还有变量 - if (!pattern.matcher(line).find()) { - json.append(line_split[1]); - } - } - } - } catch (Exception e) { - json.append("§4[]"); - } - } - } - if (!find) { - json.append(line); - } - if (++lineNumber < lineNumberEnd) { - json.newLine(); - } - } - } - } - - private int getLineNumberEnd(List list) { - int line = list.size(); - for (int i = 0 ; i < list.size(); i++) { - if (list.get(i).startsWith("@option")) { - return i; - } - } - return line; - } - - private void formatOptions(List list) { - HashMap> _options = getOptions(list); - for (Entry> entry : _options.entrySet()) { - JSONFormatter jsonFormatter = new JSONFormatter(); - String current = ChatColor.DARK_RED + "[]"; - ClickEvent clickEvent = null; - HoverEvent hoverEvent = null; - for (String _option : entry.getValue()) { - if (_option.startsWith(KEY_TEXT)) { - current = _option.substring(KEY_TEXT.length()); - } - else if (_option.startsWith(KEY_COMMAND)) { - clickEvent = new RunCommandEvent(_option.substring(KEY_COMMAND.length())); - } - else if (_option.startsWith(KEY_SUGGEST)) { - clickEvent = new SuggestCommandEvent(_option.substring(KEY_SUGGEST.length())); - } - else if (_option.startsWith(KEY_URL)) { - clickEvent = new OpenUrlEvent(_option.substring(KEY_URL.length())); - } - else if (_option.startsWith(KEY_SHOWTEXT)) { - hoverEvent = new ShowTextEvent(_option.replace("||", "\n").substring(KEY_SHOWTEXT.length())); - } - else if (_option.startsWith(KEY_SHOWITEM)) { - ItemStack item = ItemUtils.getCacheItem(_option.substring(KEY_SHOWITEM.length())); - if (item == null) { - item = new ItemStack(Material.STONE); - } - hoverEvent = new ShowItemEvent(item); - } - } - append(jsonFormatter, current, clickEvent, hoverEvent); - options.put(entry.getKey(), jsonFormatter); - } - } - - private void append(JSONFormatter json, String current, ClickEvent clickEvent, HoverEvent hoverEvent) { - if (clickEvent == null && hoverEvent == null) { - json.append(current); - } else if (clickEvent != null && hoverEvent == null) { - json.appendClick(current, clickEvent); - } else if (clickEvent == null && hoverEvent != null) { - json.appendHover(current, hoverEvent); - } else { - json.appendHoverClick(current, hoverEvent, clickEvent); - } - } - - private HashMap> getOptions(List list) { - HashMap> options_source = new HashMap<>(); - List option = new ArrayList<>(); - String optionName = null; - boolean start = false; - for (String line : list) { - if (line.startsWith(KEY_OPTION)) { - if (start) { - options_source.put(optionName, new ArrayList<>(option)); - option.clear(); - } - start = true; - optionName = line.substring(KEY_OPTION.length()); - } - else if (start) { - option.add(line); - } - } - options_source.put(optionName, option); - return options_source; - } + } + // 更改文本 + line = sb.substring(0, sb.length() - optionFullName.length()); + // 如果后段还有变量 + if (!pattern.matcher(line).find()) { + json.append(line_split[1]); + } + } + } + } catch (Exception e) { + json.append("§4[]"); + } + } + } + if (!find) { + json.append(line); + } + if (++lineNumber < lineNumberEnd) { + json.newLine(); + } + } + } + } - @Override - public void send(Player player) { - json.send(player); - } + private int getLineNumberEnd(List list) { + int line = list.size(); + for (int i = 0; i < list.size(); i++) { + if (list.get(i).startsWith("@option")) { + return i; + } + } + return line; + } - @Override - public void console() { - Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); - } + private void formatOptions(List list) { + HashMap> _options = getOptions(list); + for (Entry> entry : _options.entrySet()) { + JSONFormatter jsonFormatter = new JSONFormatter(); + String current = ChatColor.DARK_RED + "[]"; + ClickEvent clickEvent = null; + HoverEvent hoverEvent = null; + for (String _option : entry.getValue()) { + if (_option.startsWith(KEY_TEXT)) { + current = _option.substring(KEY_TEXT.length()); + } else if (_option.startsWith(KEY_COMMAND)) { + clickEvent = new RunCommandEvent(_option.substring(KEY_COMMAND.length())); + } else if (_option.startsWith(KEY_SUGGEST)) { + clickEvent = new SuggestCommandEvent(_option.substring(KEY_SUGGEST.length())); + } else if (_option.startsWith(KEY_URL)) { + clickEvent = new OpenUrlEvent(_option.substring(KEY_URL.length())); + } else if (_option.startsWith(KEY_SHOWTEXT)) { + hoverEvent = new ShowTextEvent(_option.replace("||", "\n").substring(KEY_SHOWTEXT.length())); + } else if (_option.startsWith(KEY_SHOWITEM)) { + ItemStack item = ItemUtils.getCacheItem(_option.substring(KEY_SHOWITEM.length())); + if (item == null) { + item = new ItemStack(Material.STONE); + } + hoverEvent = new ShowItemEvent(item); + } + } + append(jsonFormatter, current, clickEvent, hoverEvent); + options.put(entry.getKey(), jsonFormatter); + } + } + + private void append(JSONFormatter json, String current, ClickEvent clickEvent, HoverEvent hoverEvent) { + if (clickEvent == null && hoverEvent == null) { + json.append(current); + } else if (clickEvent != null && hoverEvent == null) { + json.appendClick(current, clickEvent); + } else if (clickEvent == null) { + json.appendHover(current, hoverEvent); + } else { + json.appendHoverClick(current, hoverEvent, clickEvent); + } + } + + private HashMap> getOptions(List list) { + HashMap> options_source = new HashMap<>(); + List option = new ArrayList<>(); + String optionName = null; + boolean start = false; + for (String line : list) { + if (line.startsWith(KEY_OPTION)) { + if (start) { + options_source.put(optionName, new ArrayList<>(option)); + option.clear(); + } + start = true; + optionName = line.substring(KEY_OPTION.length()); + } else if (start) { + option.add(line); + } + } + options_source.put(optionName, option); + return options_source; + } + + @Override + public void send(Player player) { + json.send(player); + } + + @Override + public void console() { + Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); + } } diff --git a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Sound.java b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Sound.java index d5c9592..f2e219a 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Sound.java +++ b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Sound.java @@ -1,47 +1,51 @@ package me.skymc.taboolib.string.language2.value; -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import lombok.Getter; import me.skymc.taboolib.sound.SoundPack; import me.skymc.taboolib.string.language2.Language2Format; import me.skymc.taboolib.string.language2.Language2Line; import me.skymc.taboolib.string.language2.Language2Value; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; /** * @author sky * @since 2018-03-08 22:43:27 */ public class Language2Sound implements Language2Line { - - @Getter - private List sounds = new ArrayList<>(); - - @Getter - private Language2Value value; - - public Language2Sound(Language2Format format, List list) { - this.value = format.getLanguage2Value(); - // 遍历文本 - for (String line : list) { - sounds.add(new SoundPack(line)); - } - } - @Override - public void send(Player player) { - for (SoundPack sound : sounds) { - sound.play(player); - } - } + private List sounds = new ArrayList<>(); - @Override - public void console() { - Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); - } + private Language2Value value; + + public List getSounds() { + return sounds; + } + + public Language2Value getValue() { + return value; + } + + public Language2Sound(Language2Format format, List list) { + this.value = format.getLanguage2Value(); + // 遍历文本 + for (String line : list) { + sounds.add(new SoundPack(line)); + } + } + + @Override + public void send(Player player) { + for (SoundPack sound : sounds) { + sound.play(player); + } + } + + @Override + public void console() { + Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); + } } diff --git a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Text.java b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Text.java index 270cd05..00a67d4 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Text.java +++ b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Text.java @@ -1,45 +1,49 @@ package me.skymc.taboolib.string.language2.value; -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import lombok.Getter; import me.skymc.taboolib.string.language2.Language2Format; import me.skymc.taboolib.string.language2.Language2Line; import me.skymc.taboolib.string.language2.Language2Value; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; /** * @author sky * @since 2018-03-08 22:43:27 */ public class Language2Text implements Language2Line { - - @Getter - private List text = new ArrayList<>(); - - @Getter - private Language2Value value; - - public Language2Text(Language2Format format, List list) { - this.value = format.getLanguage2Value(); - // 遍历文本 + + private List text = new ArrayList<>(); + + private Language2Value value; + + public List getText() { + return text; + } + + public Language2Value getValue() { + return value; + } + + public Language2Text(Language2Format format, List list) { + this.value = format.getLanguage2Value(); + // 遍历文本 text.addAll(list); - } + } - @Override - public void send(Player player) { - for (String line : text) { - player.sendMessage(line); - } - } + @Override + public void send(Player player) { + for (String line : text) { + player.sendMessage(line); + } + } - @Override - public void console() { - for (String line : text) { - Bukkit.getConsoleSender().sendMessage(line); - } - } + @Override + public void console() { + for (String line : text) { + Bukkit.getConsoleSender().sendMessage(line); + } + } } diff --git a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Title.java b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Title.java index aa6894a..829aba2 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Title.java +++ b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Title.java @@ -1,89 +1,103 @@ package me.skymc.taboolib.string.language2.value; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import lombok.Getter; import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.display.TitleUtils; import me.skymc.taboolib.string.language2.Language2Format; import me.skymc.taboolib.string.language2.Language2Line; import me.skymc.taboolib.string.language2.Language2Value; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import java.util.List; /** * @author sky * @since 2018年2月13日 下午3:58:07 */ public class Language2Title implements Language2Line { - - private static final String KEY_TITLE = " title: "; - private static final String KEY_SUBTITLE = " subtitle: "; - private static final String KEY_STAYRULE = " stay: "; - - @Getter - private String title = ""; - - @Getter - private String subtitle = ""; - - @Getter - private int fade1 = 0; - - @Getter - private int fade2 = 0; - - @Getter - private int stay = 20; - - @Getter - private Language2Value value; - - public Language2Title(Language2Format format, List list) { - // 变量初始化 - this.value = format.getLanguage2Value(); - // 遍历文本 - for (String message : list) { - try { - // 大标题 - if (message.startsWith(KEY_TITLE)) { - title = message.substring(KEY_TITLE.length()); - } - // 小标题 - else if (message.startsWith(KEY_SUBTITLE)) { - subtitle = message.substring(KEY_SUBTITLE.length()); - } - // 持续时间 - else if (message.startsWith(KEY_STAYRULE)) { - String rule = message.substring(KEY_STAYRULE.length()); - fade1 = Integer.valueOf(rule.split("\\|")[0]); - stay = Integer.valueOf(rule.split("\\|")[1]); - fade2 = Integer.valueOf(rule.split("\\|")[2]); - } - } - catch (Exception e) { - // 识别异常 - title = ChatColor.DARK_RED + "[]"; - subtitle = ChatColor.DARK_RED + "[]"; - } - } - } - - @Override - public void send(Player player) { - // 检查版本 - if (TabooLib.getVerint() < 10800) { - player.sendMessage(ChatColor.DARK_RED + "[]"); - } - else { - TitleUtils.sendTitle(player, title, subtitle, fade1, stay, fade2); - } - } - @Override - public void console() { - Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); - } + private static final String KEY_TITLE = " title: "; + private static final String KEY_SUBTITLE = " subtitle: "; + private static final String KEY_STAYRULE = " stay: "; + + private String title = ""; + + private String subtitle = ""; + + private int fade1 = 0; + + private int fade2 = 0; + + private int stay = 20; + + private Language2Value value; + + public String getTitle() { + return title; + } + + public String getSubtitle() { + return subtitle; + } + + public int getFade1() { + return fade1; + } + + public int getFade2() { + return fade2; + } + + public int getStay() { + return stay; + } + + public Language2Value getValue() { + return value; + } + + public Language2Title(Language2Format format, List list) { + // 变量初始化 + this.value = format.getLanguage2Value(); + // 遍历文本 + for (String message : list) { + try { + // 大标题 + if (message.startsWith(KEY_TITLE)) { + title = message.substring(KEY_TITLE.length()); + } + // 小标题 + else if (message.startsWith(KEY_SUBTITLE)) { + subtitle = message.substring(KEY_SUBTITLE.length()); + } + // 持续时间 + else if (message.startsWith(KEY_STAYRULE)) { + String rule = message.substring(KEY_STAYRULE.length()); + fade1 = Integer.valueOf(rule.split("\\|")[0]); + stay = Integer.valueOf(rule.split("\\|")[1]); + fade2 = Integer.valueOf(rule.split("\\|")[2]); + } + } catch (Exception e) { + // 识别异常 + title = ChatColor.DARK_RED + "[]"; + subtitle = ChatColor.DARK_RED + "[]"; + } + } + } + + @Override + public void send(Player player) { + // 检查版本 + if (TabooLib.getVerint() < 10800) { + player.sendMessage(ChatColor.DARK_RED + "[]"); + } else { + TitleUtils.sendTitle(player, title, subtitle, fade1, stay, fade2); + } + } + + @Override + public void console() { + Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); + } } diff --git a/src/main/java/me/skymc/taboolib/support/SupportPlaceholder.java b/src/main/java/me/skymc/taboolib/support/SupportPlaceholder.java index 34e13b9..1d20713 100644 --- a/src/main/java/me/skymc/taboolib/support/SupportPlaceholder.java +++ b/src/main/java/me/skymc/taboolib/support/SupportPlaceholder.java @@ -1,67 +1,66 @@ package me.skymc.taboolib.support; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - import me.clip.placeholderapi.external.EZPlaceholderHook; import me.skymc.taboolib.database.GlobalDataManager; import me.skymc.tlm.TLM; import me.skymc.tlm.module.TabooLibraryModule; import me.skymc.tlm.module.sub.ModuleKits; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; public class SupportPlaceholder extends EZPlaceholderHook { - - public SupportPlaceholder(Plugin plugin, String identifier) { - super(plugin, identifier); - } - @Override - public String onPlaceholderRequest(Player player, String args) { - if (args.startsWith("variable_")) { - String[] value = args.split("_"); - StringBuilder sb = new StringBuilder(); - for (int i = 1; i < value.length ; i++) { + public SupportPlaceholder(Plugin plugin, String identifier) { + super(plugin, identifier); + } + + @Override + public String onPlaceholderRequest(Player player, String args) { + if (args.startsWith("variable_")) { + String[] value = args.split("_"); + StringBuilder sb = new StringBuilder(); + for (int i = 1; i < value.length; i++) { sb.append(value[i]).append("_"); - } - return GlobalDataManager.getVariableAsynchronous(sb.substring(0, sb.length() - 1), ""); - } - if (args.startsWith("tlm_kit_")) { - // 是否启用 - if (TabooLibraryModule.getInst().valueOf("Kits") == null) { - return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.0").asString(); - } - - // 获取模块 - ModuleKits moduleKits = (ModuleKits) TabooLibraryModule.getInst().valueOf("Kits"); - String kit = args.split("_")[2]; - - // 礼包不存在 - if (!moduleKits.contains(kit)) { - return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.1").asString(); - } - - // 是否领取 - if (moduleKits.isPlayerRewared(player, kit)) { - // 是否只能领取一次 - if (moduleKits.isDisposable(kit)) { - return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.2").asString(); - } - // 是否冷却中 - if (moduleKits.isPlayerCooldown(player, kit)) { - return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.4").asString(); - } - } - - // 是否有权限领取 - String permission = moduleKits.getPermission(kit); - if (permission != null && !player.hasPermission(permission)) { - return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.5").asString(); - } - - // 可领取 - return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.3").asString(); - } - return null; - } + } + return GlobalDataManager.getVariableAsynchronous(sb.substring(0, sb.length() - 1), ""); + } + if (args.startsWith("tlm_kit_")) { + // 是否启用 + if (TabooLibraryModule.getInst().valueOf("Kits") == null) { + return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.0").asString(); + } + + // 获取模块 + ModuleKits moduleKits = (ModuleKits) TabooLibraryModule.getInst().valueOf("Kits"); + String kit = args.split("_")[2]; + + // 礼包不存在 + if (!moduleKits.contains(kit)) { + return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.1").asString(); + } + + // 是否领取 + if (moduleKits.isPlayerRewared(player, kit)) { + // 是否只能领取一次 + if (moduleKits.isDisposable(kit)) { + return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.2").asString(); + } + // 是否冷却中 + if (moduleKits.isPlayerCooldown(player, kit)) { + return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.4").asString(); + } + } + + // 是否有权限领取 + String permission = moduleKits.getPermission(kit); + if (permission != null && !player.hasPermission(permission)) { + return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.5").asString(); + } + + // 可领取 + return TLM.getInst().getLanguage().get("KIT-PLACEHOLDER.3").asString(); + } + return null; + } } diff --git a/src/main/java/me/skymc/taboolib/support/SupportWorldGuard.java b/src/main/java/me/skymc/taboolib/support/SupportWorldGuard.java index e326e33..241bba6 100644 --- a/src/main/java/me/skymc/taboolib/support/SupportWorldGuard.java +++ b/src/main/java/me/skymc/taboolib/support/SupportWorldGuard.java @@ -1,51 +1,50 @@ package me.skymc.taboolib.support; -import java.util.Collection; - +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import com.sk89q.worldguard.protection.managers.RegionManager; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -import com.sk89q.worldguard.bukkit.WorldGuardPlugin; -import com.sk89q.worldguard.protection.managers.RegionManager; -import com.sk89q.worldguard.protection.regions.ProtectedRegion; +import java.util.Collection; -public class SupportWorldGuard -{ - String Source_code_from_AgarthaLib; +public class SupportWorldGuard { + + String Source_code_from_AgarthaLib; private WorldGuardPlugin worldGuard; - + public SupportWorldGuard() { final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("WorldGuard"); if (plugin != null) { - this.worldGuard = (WorldGuardPlugin)plugin; + this.worldGuard = (WorldGuardPlugin) plugin; } } - + public final WorldGuardPlugin getWorldGuard() { return this.worldGuard; } - + public final RegionManager getRegionManager(final World world) { return this.worldGuard.getRegionManager(world); } - + public final boolean isRegionManagerExists(final World world) { return this.getRegionManager(world) != null; } - + public final Collection getRegionIDs(final World world) { final RegionManager regionManager = this.getRegionManager(world); return regionManager.getRegions().keySet(); } - + public final Collection getRegions(final World world) { final RegionManager regionManager = this.getRegionManager(world); return regionManager.getRegions().values(); } - + public final ProtectedRegion getRegion(final World world, final String id) { final RegionManager regionManager = this.getRegionManager(world); if (regionManager != null) { @@ -57,11 +56,11 @@ public class SupportWorldGuard } return null; } - + public final boolean isRegionExists(final World world, final String id) { return this.getRegion(world, id) != null; } - + public final boolean isPlayerInsideRegion(final ProtectedRegion region, final Player player) { final Location location = player.getLocation(); return region.contains(location.getBlockX(), location.getBlockY(), location.getBlockZ()); diff --git a/src/main/java/me/skymc/taboolib/team/TagManager.java b/src/main/java/me/skymc/taboolib/team/TagManager.java index 997a487..0732989 100644 --- a/src/main/java/me/skymc/taboolib/team/TagManager.java +++ b/src/main/java/me/skymc/taboolib/team/TagManager.java @@ -1,7 +1,6 @@ package me.skymc.taboolib.team; -import java.util.HashMap; - +import me.skymc.taboolib.Main; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -11,190 +10,204 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; -import lombok.Getter; -import lombok.Setter; -import me.skymc.taboolib.Main; +import java.util.HashMap; /** * @author sky * @since 2018-03-17 21:43:49 */ public class TagManager implements Listener { - - private static TagManager inst; - - @Getter - private HashMap playerdata = new HashMap<>(); - - private TagManager() { - Bukkit.getPluginManager().registerEvents(this, Main.getInst()); - } - - public static TagManager getInst() { - synchronized (TagManager.class) { - if (inst == null) { - inst = new TagManager(); - } - } - return inst; - } - - /** - * 设置玩家前缀 - * - * @param player 名称 - * @param prefix 前缀 - */ - public void setPrefix(Player player, String prefix) { - getPlayerData(player).setPrefix(prefix); - uploadData(player); - } - - /** - * 设置玩家后缀 - * - * @param player 玩家 - * @param suffix 后缀 - */ - public void setSuffix(Player player, String suffix) { - getPlayerData(player).setSuffix(suffix); - uploadData(player); - } - - /** - * 获取玩家前缀 - * - * @param player 玩家 - * @return String - */ - public String getPrefix(Player player) { - return getPlayerData(player).getPrefix(); - } - - /** - * 获取玩家后缀 - * - * @param player 玩家 - * @return String - */ - public String getSuffix(Player player) { - return getPlayerData(player).getSuffix(); - } - - /** - * 获取玩家数据 - * - * @param player 玩家 - * @return {@link PlayerData} - */ - private PlayerData getPlayerData(Player player) { - return playerdata.computeIfAbsent(player.getName(), k -> new PlayerData(player.getName())); - } - /** - * 删除该玩家的称号数据 - * - * @param player - */ - public void removeData(Player player) { - playerdata.remove(player.getName()); - for (Player _player : Bukkit.getOnlinePlayers()) { - Scoreboard scoreboard = _player.getScoreboard(); - if (scoreboard != null) { - Team team = scoreboard.getTeam(player.getName()); - if (team != null) { - team.unregister(); - } - } - } - } - - /** - * 将该玩家的数据向服务器所有玩家更新 - * - * @param player 玩家 - */ - public void uploadData(Player player) { - PlayerData data = getPlayerData(player); - String prefix = data.getPrefix().length() > 16 ? data.getPrefix().substring(0, 16) : data.getPrefix(); - String suffix = data.getSuffix().length() > 16 ? data.getSuffix().substring(0, 16) : data.getSuffix(); - // 如果没有称号数据 - if (prefix.isEmpty() && suffix.isEmpty()) { - return; - } - - for (Player _player : Bukkit.getOnlinePlayers()) { - Scoreboard scoreboard = _player.getScoreboard(); - if (scoreboard == null) { - _player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - } - Team team = scoreboard.getTeam(player.getName()); - if (team == null) { - team = scoreboard.registerNewTeam(player.getName()); - team.addEntry(player.getName()); - } - team.setPrefix(prefix); - team.setSuffix(suffix); - } - } - - /** - * 下载服务器内的称号数据到该玩家 - * - * @param player 玩家 - */ - public void downloadData(Player player) { - Scoreboard scoreboard = player.getScoreboard(); - if (scoreboard == null) { - player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - } - - for (Player _player : Bukkit.getOnlinePlayers()) { - PlayerData data = getPlayerData(_player); - String prefix = data.getPrefix().length() > 16 ? data.getPrefix().substring(0, 16) : data.getPrefix(); - String suffix = data.getSuffix().length() > 16 ? data.getSuffix().substring(0, 16) : data.getSuffix(); - // 如果没有称号数据 - if (prefix.isEmpty() && suffix.isEmpty()) { - continue; - } - - Team team = scoreboard.getTeam(_player.getName()); - if (team == null) { - team = scoreboard.registerNewTeam(_player.getName()); - team.addEntry(_player.getName()); - } - team.setPrefix(prefix); - team.setSuffix(suffix); - } - } - - @EventHandler - public void onJoin(PlayerJoinEvent e) { - downloadData(e.getPlayer()); - } - - @EventHandler - public void onQuit(PlayerQuitEvent e) { - removeData(e.getPlayer()); - } - - static class PlayerData { - - @Getter - private String name; - - @Getter - @Setter - private String prefix; - - @Getter - @Setter - private String suffix; - - public PlayerData(String name) { - this.name = name; - this.prefix = ""; - this.suffix = ""; - } - } + private static TagManager inst; + + private HashMap playerdata = new HashMap<>(); + + public HashMap getPlayerdata() { + return playerdata; + } + + private TagManager() { + Bukkit.getPluginManager().registerEvents(this, Main.getInst()); + } + + public static TagManager getInst() { + synchronized (TagManager.class) { + if (inst == null) { + inst = new TagManager(); + } + } + return inst; + } + + /** + * 设置玩家前缀 + * + * @param player 名称 + * @param prefix 前缀 + */ + public void setPrefix(Player player, String prefix) { + getPlayerData(player).setPrefix(prefix); + uploadData(player); + } + + /** + * 设置玩家后缀 + * + * @param player 玩家 + * @param suffix 后缀 + */ + public void setSuffix(Player player, String suffix) { + getPlayerData(player).setSuffix(suffix); + uploadData(player); + } + + /** + * 获取玩家前缀 + * + * @param player 玩家 + * @return String + */ + public String getPrefix(Player player) { + return getPlayerData(player).getPrefix(); + } + + /** + * 获取玩家后缀 + * + * @param player 玩家 + * @return String + */ + public String getSuffix(Player player) { + return getPlayerData(player).getSuffix(); + } + + /** + * 获取玩家数据 + * + * @param player 玩家 + * @return {@link PlayerData} + */ + private PlayerData getPlayerData(Player player) { + return playerdata.computeIfAbsent(player.getName(), k -> new PlayerData(player.getName())); + } + + /** + * 删除该玩家的称号数据 + * + * @param player + */ + public void removeData(Player player) { + playerdata.remove(player.getName()); + for (Player _player : Bukkit.getOnlinePlayers()) { + Scoreboard scoreboard = _player.getScoreboard(); + if (scoreboard != null) { + Team team = scoreboard.getTeam(player.getName()); + if (team != null) { + team.unregister(); + } + } + } + } + + /** + * 将该玩家的数据向服务器所有玩家更新 + * + * @param player 玩家 + */ + public void uploadData(Player player) { + PlayerData data = getPlayerData(player); + String prefix = data.getPrefix().length() > 16 ? data.getPrefix().substring(0, 16) : data.getPrefix(); + String suffix = data.getSuffix().length() > 16 ? data.getSuffix().substring(0, 16) : data.getSuffix(); + // 如果没有称号数据 + if (prefix.isEmpty() && suffix.isEmpty()) { + return; + } + + for (Player _player : Bukkit.getOnlinePlayers()) { + Scoreboard scoreboard = _player.getScoreboard(); + if (scoreboard == null) { + _player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } + Team team = scoreboard.getTeam(player.getName()); + if (team == null) { + team = scoreboard.registerNewTeam(player.getName()); + team.addEntry(player.getName()); + } + team.setPrefix(prefix); + team.setSuffix(suffix); + } + } + + /** + * 下载服务器内的称号数据到该玩家 + * + * @param player 玩家 + */ + public void downloadData(Player player) { + Scoreboard scoreboard = player.getScoreboard(); + if (scoreboard == null) { + player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } + + for (Player _player : Bukkit.getOnlinePlayers()) { + PlayerData data = getPlayerData(_player); + String prefix = data.getPrefix().length() > 16 ? data.getPrefix().substring(0, 16) : data.getPrefix(); + String suffix = data.getSuffix().length() > 16 ? data.getSuffix().substring(0, 16) : data.getSuffix(); + // 如果没有称号数据 + if (prefix.isEmpty() && suffix.isEmpty()) { + continue; + } + + Team team = scoreboard.getTeam(_player.getName()); + if (team == null) { + team = scoreboard.registerNewTeam(_player.getName()); + team.addEntry(_player.getName()); + } + team.setPrefix(prefix); + team.setSuffix(suffix); + } + } + + @EventHandler + public void onJoin(PlayerJoinEvent e) { + downloadData(e.getPlayer()); + } + + @EventHandler + public void onQuit(PlayerQuitEvent e) { + removeData(e.getPlayer()); + } + + static class PlayerData { + + private String name; + private String prefix; + private String suffix; + + public String getName() { + return name; + } + + public String getPrefix() { + return prefix; + } + + public String getSuffix() { + return suffix; + } + + public void setPrefix(String prefix) { + this.prefix = prefix; + } + + public void setSuffix(String suffix) { + this.suffix = suffix; + } + + public PlayerData(String name) { + this.name = name; + this.prefix = ""; + this.suffix = ""; + } + } } diff --git a/src/main/java/me/skymc/taboolib/team/TagUtils.java b/src/main/java/me/skymc/taboolib/team/TagUtils.java index b3a6680..1ebca72 100644 --- a/src/main/java/me/skymc/taboolib/team/TagUtils.java +++ b/src/main/java/me/skymc/taboolib/team/TagUtils.java @@ -10,122 +10,122 @@ import org.bukkit.scoreboard.Team; * @since 2018-03-17 21:36:52 */ public class TagUtils { - - /** - * 设置玩家前后缀 - * - * @param p 玩家 - * @param prefix 前缀 - * @param suffix 后缀 - */ - public static void setTag(Player p, String prefix, String suffix) { - // 判断长度 - if (prefix.length() > 16) { - prefix = prefix.substring(0, 16); - } - if (suffix.length() > 16) { - suffix = suffix.substring(0, 16); - } - - // 获取计分板 - Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); - Team t = board.getTeam(p.getName()); - if (t == null) { - t = board.registerNewTeam(p.getName()); - } - - // 更新称号 - t.setPrefix(prefix); - t.setSuffix(suffix); - t.addEntry(p.getName()); - - // 更新玩家 - for (Player o : Bukkit.getOnlinePlayers()) { - if (!board.equals(o.getScoreboard())) { - o.setScoreboard(board); - } - } - } - - /** - * 注销玩家前后缀 - * - * @param p 玩家 - */ - public static void unregisterTag(Player p) { - Team team = Bukkit.getScoreboardManager().getMainScoreboard().getTeam(p.getName()); - if (team != null) { - team.unregister(); - } - } - - /** - * 注销所有在线玩家前后缀 - */ - public static void unregisterAll() { - for (Player o : Bukkit.getOnlinePlayers()) { - unregisterTag(o); - } - } - - /** - * 删除所有前后缀 - */ - public static void delete() { - for (Team t : Bukkit.getScoreboardManager().getMainScoreboard().getTeams()) { - t.unregister(); - } - } - - /** - * 设置全服玩家前后缀 - * - * @param prefix 前缀 - * @param suffix 后缀 - */ - public static void registerAll(String prefix, String suffix) { - for (Player o : Bukkit.getOnlinePlayers()) { - setTag(o, prefix, suffix); - } - } - - /** - * 刷新计分板数据 - */ - public static void refresh() { - Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); - for (Player o : Bukkit.getOnlinePlayers()) { - o.setScoreboard(board); - } - } - - /** - * 获取玩家前缀 - * - * @param p 玩家 - * @return String - */ - public static String getPrefix(Player p) { - Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); - Team t = board.getTeam(p.getName()); - if (t != null) { - return t.getPrefix(); - } - return null; - } - - /** - * 获取玩玩家后缀 - * - * @param p 玩家 - * @return String - */ - public static String getSuffix(Player p) { - Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); - Team t = board.getTeam(p.getName()); - if (t != null) { - return t.getSuffix(); - } - return null; - } + + /** + * 设置玩家前后缀 + * + * @param p 玩家 + * @param prefix 前缀 + * @param suffix 后缀 + */ + public static void setTag(Player p, String prefix, String suffix) { + // 判断长度 + if (prefix.length() > 16) { + prefix = prefix.substring(0, 16); + } + if (suffix.length() > 16) { + suffix = suffix.substring(0, 16); + } + + // 获取计分板 + Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); + Team t = board.getTeam(p.getName()); + if (t == null) { + t = board.registerNewTeam(p.getName()); + } + + // 更新称号 + t.setPrefix(prefix); + t.setSuffix(suffix); + t.addEntry(p.getName()); + + // 更新玩家 + for (Player o : Bukkit.getOnlinePlayers()) { + if (!board.equals(o.getScoreboard())) { + o.setScoreboard(board); + } + } + } + + /** + * 注销玩家前后缀 + * + * @param p 玩家 + */ + public static void unregisterTag(Player p) { + Team team = Bukkit.getScoreboardManager().getMainScoreboard().getTeam(p.getName()); + if (team != null) { + team.unregister(); + } + } + + /** + * 注销所有在线玩家前后缀 + */ + public static void unregisterAll() { + for (Player o : Bukkit.getOnlinePlayers()) { + unregisterTag(o); + } + } + + /** + * 删除所有前后缀 + */ + public static void delete() { + for (Team t : Bukkit.getScoreboardManager().getMainScoreboard().getTeams()) { + t.unregister(); + } + } + + /** + * 设置全服玩家前后缀 + * + * @param prefix 前缀 + * @param suffix 后缀 + */ + public static void registerAll(String prefix, String suffix) { + for (Player o : Bukkit.getOnlinePlayers()) { + setTag(o, prefix, suffix); + } + } + + /** + * 刷新计分板数据 + */ + public static void refresh() { + Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); + for (Player o : Bukkit.getOnlinePlayers()) { + o.setScoreboard(board); + } + } + + /** + * 获取玩家前缀 + * + * @param p 玩家 + * @return String + */ + public static String getPrefix(Player p) { + Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); + Team t = board.getTeam(p.getName()); + if (t != null) { + return t.getPrefix(); + } + return null; + } + + /** + * 获取玩玩家后缀 + * + * @param p 玩家 + * @return String + */ + public static String getSuffix(Player p) { + Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); + Team t = board.getTeam(p.getName()); + if (t != null) { + return t.getSuffix(); + } + return null; + } } diff --git a/src/main/java/me/skymc/taboolib/thread/ThreadUtils.java b/src/main/java/me/skymc/taboolib/thread/ThreadUtils.java index a1e67fe..91af79d 100644 --- a/src/main/java/me/skymc/taboolib/thread/ThreadUtils.java +++ b/src/main/java/me/skymc/taboolib/thread/ThreadUtils.java @@ -3,82 +3,80 @@ package me.skymc.taboolib.thread; import java.util.LinkedList; public class ThreadUtils { - - private static PoolWorker[] threads; - private static final LinkedList queue = new LinkedList<>(); - /** - * 构造方法 - * - * @param number 线程数量 - */ - public ThreadUtils(int number) { - threads = new PoolWorker[number]; + private static PoolWorker[] threads; + private static final LinkedList queue = new LinkedList<>(); - for (int i = 0; i < number; i++) { - threads[i] = new PoolWorker(); - threads[i].setName("TabooLib WorkThread - " + i); - threads[i].start(); - } - } - - /** - * 停止工作 - * - */ - public void stop() { - for (PoolWorker p : threads) { - p.stop(); - } - } + /** + * 构造方法 + * + * @param number 线程数量 + */ + public ThreadUtils(int number) { + threads = new PoolWorker[number]; - /** - * 添加任务 - * - * @param r - */ - public void execute(Runnable r) { - // 线程锁 - synchronized (queue) { - // 添加任务 - queue.addLast(r); - // 开始任务 - queue.notify(); - } - } + for (int i = 0; i < number; i++) { + threads[i] = new PoolWorker(); + threads[i].setName("TabooLib WorkThread - " + i); + threads[i].start(); + } + } - private class PoolWorker extends Thread { - - @Override - public void run() { - Runnable runnable; - - while (true) { - - // 线程锁 - synchronized (queue) { - - // 如果任务为空 - while (queue.isEmpty()) { - // 等待任务 - try { - queue.wait(); - } catch (InterruptedException ignored) { - - } - } - // 获取任务 - runnable = queue.removeFirst(); - } - - // 运行任务 - try { - runnable.run(); - } - catch (Exception e) { - e.printStackTrace(); - } - } - } - } + /** + * 停止工作 + */ + public void stop() { + for (PoolWorker p : threads) { + p.stop(); + } + } + + /** + * 添加任务 + * + * @param r + */ + public void execute(Runnable r) { + // 线程锁 + synchronized (queue) { + // 添加任务 + queue.addLast(r); + // 开始任务 + queue.notify(); + } + } + + private class PoolWorker extends Thread { + + @Override + public void run() { + Runnable runnable; + + while (true) { + + // 线程锁 + synchronized (queue) { + + // 如果任务为空 + while (queue.isEmpty()) { + // 等待任务 + try { + queue.wait(); + } catch (InterruptedException ignored) { + + } + } + // 获取任务 + runnable = queue.removeFirst(); + } + + // 运行任务 + try { + runnable.run(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/timecycle/TimeCycle.java b/src/main/java/me/skymc/taboolib/timecycle/TimeCycle.java index 1697fb3..b2105b8 100644 --- a/src/main/java/me/skymc/taboolib/timecycle/TimeCycle.java +++ b/src/main/java/me/skymc/taboolib/timecycle/TimeCycle.java @@ -1,36 +1,35 @@ package me.skymc.taboolib.timecycle; +import me.skymc.taboolib.other.DateUtils; import org.bukkit.plugin.Plugin; -import me.skymc.taboolib.other.DateUtils; - public class TimeCycle { + + private String name; + private Plugin plugin; + + private long cycle; + + public TimeCycle(String name, long cycle, Plugin plugin) { + this.name = name; + this.cycle = cycle; + this.plugin = plugin; + + long millisHour = DateUtils.getTime(DateUtils.HOUR_OF_DAY) * 60L * 60L * 1000L; + long millisMinute = DateUtils.getTime(DateUtils.MINUTE) * 60L * 1000L; + + long time = System.currentTimeMillis() - millisHour - millisMinute; + } - private String name; - private Plugin plugin; - - private long cycle; - - public TimeCycle(String name, long cycle, Plugin plugin) { - this.name = name; - this.cycle = cycle; - this.plugin = plugin; - - long millisHour = DateUtils.getTime(DateUtils.HOUR_OF_DAY) * 60L * 60L * 1000L; - long millisMinute = DateUtils.getTime(DateUtils.MINUTE) * 60L * 1000L; - - long time = System.currentTimeMillis() - millisHour - millisMinute; - } - - public Plugin getPlugin() { - return plugin; - } - - public String getName() { - return name; - } - - public long getCycle() { - return cycle; - } + public Plugin getPlugin() { + return plugin; + } + + public String getName() { + return name; + } + + public long getCycle() { + return cycle; + } } diff --git a/src/main/java/me/skymc/taboolib/timeutil/TimeFormatter.java b/src/main/java/me/skymc/taboolib/timeutil/TimeFormatter.java index b3fdb4a..d3e6d9d 100644 --- a/src/main/java/me/skymc/taboolib/timeutil/TimeFormatter.java +++ b/src/main/java/me/skymc/taboolib/timeutil/TimeFormatter.java @@ -2,30 +2,67 @@ package me.skymc.taboolib.timeutil; import java.util.concurrent.TimeUnit; -import lombok.Data; - /** * @author sky * @since 2018-04-10 22:11:04 */ -@Data public class TimeFormatter { - - private long days; - private long hours; - private long minutes; - private long seconds; - private long milliseconds; - - public TimeFormatter(long millisecond) { - days = TimeUnit.MILLISECONDS.toDays(millisecond); - hours = TimeUnit.MILLISECONDS.toHours(millisecond) - days * 24L; - minutes = TimeUnit.MILLISECONDS.toMinutes(millisecond) - TimeUnit.MILLISECONDS.toHours(millisecond) * 60L; - seconds = TimeUnit.MILLISECONDS.toSeconds(millisecond) - TimeUnit.MILLISECONDS.toMinutes(millisecond) * 60L; - milliseconds = TimeUnit.MILLISECONDS.toMillis(millisecond) - TimeUnit.MILLISECONDS.toSeconds(millisecond) * 1000L; - } - - public long toMilliseconds() { - return milliseconds + (seconds * 1000L) + (minutes * 1000L * 60L) + (hours * 1000L * 60L * 60L) + (days * 1000L * 60L * 60L * 24L); - } + + private long days; + private long hours; + private long minutes; + private long seconds; + private long milliseconds; + + public long getDays() { + return days; + } + + public void setDays(long days) { + this.days = days; + } + + public long getHours() { + return hours; + } + + public void setHours(long hours) { + this.hours = hours; + } + + public long getMinutes() { + return minutes; + } + + public void setMinutes(long minutes) { + this.minutes = minutes; + } + + public long getSeconds() { + return seconds; + } + + public void setSeconds(long seconds) { + this.seconds = seconds; + } + + public long getMilliseconds() { + return milliseconds; + } + + public void setMilliseconds(long milliseconds) { + this.milliseconds = milliseconds; + } + + public TimeFormatter(long millisecond) { + days = TimeUnit.MILLISECONDS.toDays(millisecond); + hours = TimeUnit.MILLISECONDS.toHours(millisecond) - days * 24L; + minutes = TimeUnit.MILLISECONDS.toMinutes(millisecond) - TimeUnit.MILLISECONDS.toHours(millisecond) * 60L; + seconds = TimeUnit.MILLISECONDS.toSeconds(millisecond) - TimeUnit.MILLISECONDS.toMinutes(millisecond) * 60L; + milliseconds = TimeUnit.MILLISECONDS.toMillis(millisecond) - TimeUnit.MILLISECONDS.toSeconds(millisecond) * 1000L; + } + + public long toMilliseconds() { + return milliseconds + (seconds * 1000L) + (minutes * 1000L * 60L) + (hours * 1000L * 60L * 60L) + (days * 1000L * 60L * 60L * 24L); + } } diff --git a/src/main/java/me/skymc/tlm/TLM.java b/src/main/java/me/skymc/tlm/TLM.java index cff3dce..71f83dd 100644 --- a/src/main/java/me/skymc/tlm/TLM.java +++ b/src/main/java/me/skymc/tlm/TLM.java @@ -1,8 +1,5 @@ package me.skymc.tlm; -import org.bukkit.configuration.file.FileConfiguration; - -import lombok.Getter; import me.skymc.taboolib.Main; import me.skymc.taboolib.fileutils.ConfigUtils; import me.skymc.taboolib.message.MsgUtils; @@ -12,85 +9,92 @@ import me.skymc.tlm.module.sub.ModuleCommandChanger; import me.skymc.tlm.module.sub.ModuleInventorySave; import me.skymc.tlm.module.sub.ModuleKits; import me.skymc.tlm.module.sub.ModuleTimeCycle; +import org.bukkit.configuration.file.FileConfiguration; /** * @author sky * @since 2018年2月17日 下午10:28:05 */ public class TLM { - - private static TLM inst = null; - - @Getter - private FileConfiguration config; - - @Getter - private Language2 language; - - /** - * 构造方法 - */ - private TLM() { - // 重载配置文件 - reloadConfig(); - - // 载入模块 - if (isEnableModule("TimeCycle")) { - TabooLibraryModule.getInst().register(new ModuleTimeCycle()); - } - if (isEnableModule("Kits")) { - TabooLibraryModule.getInst().register(new ModuleKits()); - } - if (isEnableModule("CommandChanger")) { - TabooLibraryModule.getInst().register(new ModuleCommandChanger()); - } - if (isEnableModule("InventorySave")) { - TabooLibraryModule.getInst().register(new ModuleInventorySave()); - } - - // 载入模块 - TabooLibraryModule.getInst().loadModules(); - - // 提示 - MsgUtils.send("载入 &f" + TabooLibraryModule.getInst().getSize() + " &7个 &fTLM &7模块"); - } - - /** - * 获取 TLM 对象 - * - * @return TLM - */ - public static TLM getInst() { - if (inst == null) { - synchronized (TLM.class) { - if (inst == null) { - inst = new TLM(); - } - } - } - return inst; - } - - /** - * 载入配置文件 - */ - public void reloadConfig() { - config = ConfigUtils.saveDefaultConfig(Main.getInst(), "module.yml"); - // 载入语言文件 - try { - language = new Language2(config.getString("Language"), Main.getInst()); - } catch (Exception e) { - MsgUtils.warn("语言文件不存在: &4" + config.getString("Language")); + + private static TLM inst = null; + + private FileConfiguration config; + + private Language2 language; + + public FileConfiguration getConfig() { + return config; + } + + public Language2 getLanguage() { + return language; + } + + /** + * 构造方法 + */ + private TLM() { + // 重载配置文件 + reloadConfig(); + + // 载入模块 + if (isEnableModule("TimeCycle")) { + TabooLibraryModule.getInst().register(new ModuleTimeCycle()); } - } - - /** - * 模块是否启用 - * - * @param name 名称 - * @return boolean - */ - public boolean isEnableModule(String name) { - return config.getStringList("EnableModule").contains(name); - } + if (isEnableModule("Kits")) { + TabooLibraryModule.getInst().register(new ModuleKits()); + } + if (isEnableModule("CommandChanger")) { + TabooLibraryModule.getInst().register(new ModuleCommandChanger()); + } + if (isEnableModule("InventorySave")) { + TabooLibraryModule.getInst().register(new ModuleInventorySave()); + } + + // 载入模块 + TabooLibraryModule.getInst().loadModules(); + + // 提示 + MsgUtils.send("载入 &f" + TabooLibraryModule.getInst().getSize() + " &7个 &fTLM &7模块"); + } + + /** + * 获取 TLM 对象 + * + * @return TLM + */ + public static TLM getInst() { + if (inst == null) { + synchronized (TLM.class) { + if (inst == null) { + inst = new TLM(); + } + } + } + return inst; + } + + /** + * 载入配置文件 + */ + public void reloadConfig() { + config = ConfigUtils.saveDefaultConfig(Main.getInst(), "module.yml"); + // 载入语言文件 + try { + language = new Language2(config.getString("Language"), Main.getInst()); + } catch (Exception e) { + MsgUtils.warn("语言文件不存在: &4" + config.getString("Language")); + } + } + + /** + * 模块是否启用 + * + * @param name 名称 + * @return boolean + */ + public boolean isEnableModule(String name) { + return config.getStringList("EnableModule").contains(name); + } } diff --git a/src/main/java/me/skymc/tlm/annotation/DisableConfig.java b/src/main/java/me/skymc/tlm/annotation/DisableConfig.java index 83b8a2a..90a3b18 100644 --- a/src/main/java/me/skymc/tlm/annotation/DisableConfig.java +++ b/src/main/java/me/skymc/tlm/annotation/DisableConfig.java @@ -1,13 +1,13 @@ package me.skymc.tlm.annotation; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target(TYPE) public @interface DisableConfig { - + } diff --git a/src/main/java/me/skymc/tlm/command/TLMCommands.java b/src/main/java/me/skymc/tlm/command/TLMCommands.java index 38185bc..ebab347 100644 --- a/src/main/java/me/skymc/tlm/command/TLMCommands.java +++ b/src/main/java/me/skymc/tlm/command/TLMCommands.java @@ -1,14 +1,13 @@ package me.skymc.tlm.command; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; - import me.skymc.tlm.TLM; import me.skymc.tlm.command.sub.TLMInvCommand; import me.skymc.tlm.command.sub.TLMKitCommand; import me.skymc.tlm.command.sub.TLMListCommand; import me.skymc.tlm.command.sub.TLMReloadCommand; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; /** * @author sky @@ -16,51 +15,49 @@ import me.skymc.tlm.command.sub.TLMReloadCommand; */ 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 (sender.hasPermission("taboolib.admin")) { - TLM.getInst().getLanguage().get("COMMAND-HELP").send(sender); - } else { - TLM.getInst().getLanguage().get("NOPERMISSION-HELP").send(sender); - } - } - - // 重载 - else if (args[0].equalsIgnoreCase("reload")) { - if (sender.hasPermission("taboolib.admin")) { - new TLMReloadCommand(sender, args); - } else { - TLM.getInst().getLanguage().get("NOPERMISSION-RELOAD").send(sender); - } - } - - // 列出 - else if (args[0].equalsIgnoreCase("list")) { - if (sender.hasPermission("taboolib.admin")) { - new TLMListCommand(sender, args); - } else { - TLM.getInst().getLanguage().get("NOPERMISSION-LIST").send(sender); - } - } - - // InventorySave 模块 - else if (args[0].equalsIgnoreCase("inv")) { - if (sender.hasPermission("taboolib.admin")) { - new TLMInvCommand(sender, args); - } else { - TLM.getInst().getLanguage().get("NOPERMISSION-INV").send(sender); - } - } - - // Kit 模块 - else if (args[0].equalsIgnoreCase("kit")) { - new TLMKitCommand(sender, args); - } - - else { - TLM.getInst().getLanguage().get("COMMAND-ERROR").send(sender); - } - return true; - } + @Override + public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] args) { + if (args.length == 0 || args[0].equalsIgnoreCase("help")) { + if (sender.hasPermission("taboolib.admin")) { + TLM.getInst().getLanguage().get("COMMAND-HELP").send(sender); + } else { + TLM.getInst().getLanguage().get("NOPERMISSION-HELP").send(sender); + } + } + + // 重载 + else if (args[0].equalsIgnoreCase("reload")) { + if (sender.hasPermission("taboolib.admin")) { + new TLMReloadCommand(sender, args); + } else { + TLM.getInst().getLanguage().get("NOPERMISSION-RELOAD").send(sender); + } + } + + // 列出 + else if (args[0].equalsIgnoreCase("list")) { + if (sender.hasPermission("taboolib.admin")) { + new TLMListCommand(sender, args); + } else { + TLM.getInst().getLanguage().get("NOPERMISSION-LIST").send(sender); + } + } + + // InventorySave 模块 + else if (args[0].equalsIgnoreCase("inv")) { + if (sender.hasPermission("taboolib.admin")) { + new TLMInvCommand(sender, args); + } else { + TLM.getInst().getLanguage().get("NOPERMISSION-INV").send(sender); + } + } + + // Kit 模块 + else if (args[0].equalsIgnoreCase("kit")) { + new TLMKitCommand(sender, args); + } else { + TLM.getInst().getLanguage().get("COMMAND-ERROR").send(sender); + } + return true; + } } diff --git a/src/main/java/me/skymc/tlm/inventory/TLMInventoryHolder.java b/src/main/java/me/skymc/tlm/inventory/TLMInventoryHolder.java index ca1cdee..094e24a 100644 --- a/src/main/java/me/skymc/tlm/inventory/TLMInventoryHolder.java +++ b/src/main/java/me/skymc/tlm/inventory/TLMInventoryHolder.java @@ -1,35 +1,39 @@ package me.skymc.tlm.inventory; -import java.util.HashMap; - import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; -import lombok.Getter; +import java.util.HashMap; /** * @author sky * @since 2018年2月22日 下午3:34:59 */ public class TLMInventoryHolder implements InventoryHolder { - - @Getter - private String module; - - @Getter - private HashMap holderData = new HashMap<>(); - - /** - * 构造方法 - * - * @param module 模块名 - */ - public TLMInventoryHolder(String module) { - this.module = module; - } - @Override - public Inventory getInventory() { - return null; - } + private String module; + + private HashMap holderData = new HashMap<>(); + + public String getModule() { + return module; + } + + public HashMap getHolderData() { + return holderData; + } + + /** + * 构造方法 + * + * @param module 模块名 + */ + public TLMInventoryHolder(String module) { + this.module = module; + } + + @Override + public Inventory getInventory() { + return null; + } } diff --git a/src/main/java/me/skymc/tlm/module/ITabooLibraryModule.java b/src/main/java/me/skymc/tlm/module/ITabooLibraryModule.java index bc081f9..1526b90 100644 --- a/src/main/java/me/skymc/tlm/module/ITabooLibraryModule.java +++ b/src/main/java/me/skymc/tlm/module/ITabooLibraryModule.java @@ -7,17 +7,19 @@ import org.bukkit.configuration.file.FileConfiguration; * @since 2018年2月17日 下午11:22:42 */ public interface ITabooLibraryModule { - - default void onEnable() {} - - default void onDisable() {} - default void onReload() { - } + default void onEnable() { + } - String getName(); - - default FileConfiguration getConfig() { - return TabooLibraryModule.getInst().getConfig(this); - } + default void onDisable() { + } + + default void onReload() { + } + + String getName(); + + default FileConfiguration getConfig() { + return TabooLibraryModule.getInst().getConfig(this); + } } diff --git a/src/main/java/me/skymc/tlm/module/TabooLibraryModule.java b/src/main/java/me/skymc/tlm/module/TabooLibraryModule.java index ae1dd5c..9da328c 100644 --- a/src/main/java/me/skymc/tlm/module/TabooLibraryModule.java +++ b/src/main/java/me/skymc/tlm/module/TabooLibraryModule.java @@ -1,101 +1,100 @@ package me.skymc.tlm.module; -import java.io.File; -import java.util.HashMap; -import java.util.Set; - +import me.skymc.taboolib.Main; +import me.skymc.tlm.annotation.DisableConfig; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.event.Listener; -import me.skymc.taboolib.Main; -import me.skymc.tlm.annotation.DisableConfig; +import java.io.File; +import java.util.HashMap; +import java.util.Set; /** * @author sky * @since 2018年2月17日 下午11:22:48 */ public class TabooLibraryModule { - - private final HashMap TLM_MODULE = new HashMap<>(); - private static TabooLibraryModule inst = null; - - private TabooLibraryModule() { - - } - - public static TabooLibraryModule getInst() { - if (inst == null) { - synchronized (TabooLibraryModule.class) { - if (inst == null) { - inst = new TabooLibraryModule(); - } - } - } - return inst; - } - - public void register(ITabooLibraryModule module) { - if (!TLM_MODULE.containsKey(module)) { - TLM_MODULE.put(module, new YamlConfiguration()); - reloadConfig(module, false); - } - } - - public void loadModules() { - for (ITabooLibraryModule module : TLM_MODULE.keySet()) { - module.onEnable(); - if (module instanceof Listener) { - Bukkit.getPluginManager().registerEvents((Listener) module, Main.getInst()); - } - } - } - - public void unloadModules() { + + private static TabooLibraryModule inst = null; + private final HashMap TLM_MODULE = new HashMap<>(); + + private TabooLibraryModule() { + + } + + public static TabooLibraryModule getInst() { + if (inst == null) { + synchronized (TabooLibraryModule.class) { + if (inst == null) { + inst = new TabooLibraryModule(); + } + } + } + return inst; + } + + public void register(ITabooLibraryModule module) { + if (!TLM_MODULE.containsKey(module)) { + TLM_MODULE.put(module, new YamlConfiguration()); + reloadConfig(module, false); + } + } + + public void loadModules() { + for (ITabooLibraryModule module : TLM_MODULE.keySet()) { + module.onEnable(); + if (module instanceof Listener) { + Bukkit.getPluginManager().registerEvents((Listener) module, Main.getInst()); + } + } + } + + public void unloadModules() { TLM_MODULE.keySet().forEach(ITabooLibraryModule::onDisable); - } - - public void reloadConfig() { - TLM_MODULE.keySet().forEach(x -> reloadConfig(x, true)); - } - - public void reloadConfig(ITabooLibraryModule module, boolean isReload) { - if (module.getName() == null || module.getClass().getAnnotation(DisableConfig.class) != null) { - return; - } - File file = new File(Main.getInst().getDataFolder(), "TLM/" + module.getName() + ".yml"); - if (!file.exists()) { - Main.getInst().saveResource("TLM/" + module.getName() + ".yml", true); - } - try { - TLM_MODULE.get(module).load(file); - } catch (Exception e) { - // TODO Auto-generated catch block - } - if (isReload) { - module.onReload(); - } - } - - public FileConfiguration getConfig(ITabooLibraryModule module) { - return TLM_MODULE.get(module); - } - - public int getSize() { - return TLM_MODULE.size(); - } - - public Set keySet() { - return TLM_MODULE.keySet(); - } - - public ITabooLibraryModule valueOf(String name) { - for (ITabooLibraryModule module : TLM_MODULE.keySet()) { - if (module.getName().equals(name)) { - return module; - } - } - return null; - } + } + + public void reloadConfig() { + TLM_MODULE.keySet().forEach(x -> reloadConfig(x, true)); + } + + public void reloadConfig(ITabooLibraryModule module, boolean isReload) { + if (module.getName() == null || module.getClass().getAnnotation(DisableConfig.class) != null) { + return; + } + File file = new File(Main.getInst().getDataFolder(), "TLM/" + module.getName() + ".yml"); + if (!file.exists()) { + Main.getInst().saveResource("TLM/" + module.getName() + ".yml", true); + } + try { + TLM_MODULE.get(module).load(file); + } catch (Exception e) { + // TODO Auto-generated catch block + } + if (isReload) { + module.onReload(); + } + } + + public FileConfiguration getConfig(ITabooLibraryModule module) { + return TLM_MODULE.get(module); + } + + public int getSize() { + return TLM_MODULE.size(); + } + + public Set keySet() { + return TLM_MODULE.keySet(); + } + + public ITabooLibraryModule valueOf(String name) { + for (ITabooLibraryModule module : TLM_MODULE.keySet()) { + if (module.getName().equals(name)) { + return module; + } + } + return null; + } } diff --git a/src/main/resources/JavaShells/scripts/-testshell.java b/src/main/resources/JavaShells/scripts/-testshell.java index aa2f262..8c6b542 100644 --- a/src/main/resources/JavaShells/scripts/-testshell.java +++ b/src/main/resources/JavaShells/scripts/-testshell.java @@ -1,12 +1,12 @@ -import org.bukkit.*; +import org.bukkit.Bukkit; public class testshell { - - public void onEnable() { - Bukkit.broadcastMessage("testshell enable!"); - } - - public void onDisable() { - Bukkit.broadcastMessage("testshell disable!"); - } + + public void onEnable() { + Bukkit.broadcastMessage("testshell enable!"); + } + + public void onDisable() { + Bukkit.broadcastMessage("testshell disable!"); + } } \ No newline at end of file diff --git a/src/main/resources/internalLang.yml b/src/main/resources/internalLang.yml deleted file mode 100644 index b419155..0000000 --- a/src/main/resources/internalLang.yml +++ /dev/null @@ -1,9 +0,0 @@ -LANG-LOAD-FAIL: '语言文件加载失败' -TRY-LOADING-LANG: '插件 {0} 尝试加载 {1} .yml 作为语言文件' -SUCCESS-LOADING-LANG: '成功加载 {0} 插件的 {1} 语言文件,共 {2} 条' -ERROR-LOADING-LANG: '加载 {0} 插件的语言文件时发生异常:{1}' -RELOADING-LANG: '正在重新载入 {0} 插件的语言文件' -FETCH-LOCALE-ERROR: '语言文件获取失败:{0}' -SEND-LOCALE-ERROR: '语言文件发送失败:{0}' -LOCALE-ERROR-REASON: '原因:{0}' -MISSING-ARGUMENT: '语言文本含有没有找到的参数 {0}' \ No newline at end of file diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 77f4c75..f470690 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -1,6 +1,9 @@ +VERSION: 2 + TLIB: INJECTION-SUCCESS: '注入成功' INJECTION-FAILED: '注入失败' + DEPENDENCY: OFFLINE-DEPENDENCY-WARN: '已启用离线模式, 将不会下载第三方依赖库' DOWNLOAD-CONNECTED: ' 正在下载 {0} 大小 {1}' @@ -16,6 +19,7 @@ DEPENDENCY: LIBRARY-LOAD-SUCCESS: ' {0} 请求的库文件 {1} 加载成功' LIBRARY-LOAD-FAIL: ' {0} 请求的库文件 {1} 加载失败' LOAD-COMPLETE: '依赖加载完成' + CONFIG: LOAD-FAIL-NO-ANNOTATION: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解' LOAD-FAIL: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解' @@ -27,8 +31,221 @@ CONFIG: RELOAD-SUCCESS: '插件 {0} 的配置 {1} 成功重载' RELOAD-FAIL: '插件 {0} 的配置 {1} 成功重载' LISTEN-START: '开始监听 {0} 插件的 {1} 配置文件' + LOCALE: TITLE-SEND-TO-NON-PLAYER: '该语言类型只能发送给玩家:{0}' + MISC: FIELD-COPY-FAILED: '拷贝 {0} 对象失败' FIELD-COPY-ERROR: '拷贝 {0} 对象出错:{1}' + +COMMANDS: + GLOBAL: + ONLY-PLAYER: '&8[&3&lTabooLib&8] &4控制台无法这么做' + ONLY-STORAGE-SQL: '&8[&3&lTabooLib&8] &4只有启用数据库储存时才能这么做' + PARAMETER: + UNKNOWN: '&8[&3&lTabooLib&8] &4指令错误' + INSUFFICIENT: '&8[&3&lTabooLib&8] &4参数不足' + RELOAD: + LOADING: '&8[&3&lTabooLib&8] &7重载中...' + SUCCESS-NORMAL: '&8[&3&lTabooLib&8] &7重载成功' + SUCCESS-ELAPSED-TIME: '&8[&3&lTabooLib&8] &7重载成功, 耗时: &f{0} ms' + TABOOLIB: + HELP: + - '' + - '§b§l----- §3§lTaooLib Commands §b§l-----' + - '' + - '&f /taboolib save §8[§7名称§8] &6- §e保存手中物品' + - '&f /taboolib item §8[§7名称§8] §8<§7玩家§8> §8<§7数量§8> &6- §e给予玩家物品' + - '&f /taboolib iteminfo &6- §e查看物品信息' + - '&f /taboolib itemlist &6- §e查看所有物品' + - '&f /taboolib itemreload &6- §e重载物品缓存' + - '' + - '&f /taboolib attributes &6- §e查看所有属性' + - '&f /taboolib enchants &6- §e查看所有附魔' + - '&f /taboolib potions &6- §e查看所有药水' + - '&f /taboolib flags &6- §e查看所有标签' + - '&f /taboolib slots &6- §e查看所有部位' + - '&f /taboolib sounds &6- §e查看所有音效' + - '' + - '&f /taboolib getvariable §8[§7-s|a§8] §8[§7键§8] &6- §e查看变量' + - '&f /taboolib setvariable §8[§7-s|a§8] §8[§7键§8] §8[§7值§8] &6- §e更改变量' + - '' + - '&f /taboolib cycle list &6- §e列出所有时间检查器' + - '&f /taboolib cycle info §8[§7名称§8] &6- §e查询检查器信息' + - '&f /taboolib cycle reset §8[§7名称§8] &6- §e初始化时间检查器' + - '&f /taboolib cycle update §8[§7名称§8] &6- §e更新时间检查器' + - '' + - '&f /taboolib shell load §8[§7名称§8] &6- §e载入某个脚本' + - '&f /taboolib shell unload §8[§7名称§8] &6- §e卸载某个脚本' + - '' + - '&f /taboolib tagprefix §8[§7名称§8] §8[§7文本§8] &6- §e设置玩家头顶前缀' + - '&f /taboolib tagsuffix §8[§7名称§8] §8[§7文本§8] &6- §e设置玩家头顶后缀' + - '&f /taboolib tagdelete §8[§7名称§8] &6- §e删除玩家称号数据' + - '' + - '&f /taboolib importdata &6- §4向数据库导入本地数据 §8(该操作将会清空数据库)' + - '' + SAVE: + INVALID-NAME: '&8[&3&lTabooLib&8] &4请输入正确的名称' + INVALID-ITEM: '&8[&3&lTabooLib&8] &4请手持正确的物品' + INVALID-ITEM-FINAL-EXISTS: '&8[&3&lTabooLib&8] &4该名称所对应的物品保存于固定物品库中, 无法覆盖' + GUIDE-EXISTS: '&8[&3&lTabooLib&8] &4你有一个正在进行的聊天引导, 请完成后在这么做' + GUIDE-BEFORE: '&8[&3&lTabooLib&8] &7物品 &f{0}&7 已存在, 如果你想要覆盖它, 请在聊天框中输入 "&fYES&7"' + GUIDE-QUIT: '&8[&3&lTabooLib&8] &7退出引导' + SUCCESS: '&8[&3&lTabooLib&8] &7物品 &f{0} &7已替换' + ITEM: + INVALID-NAME: '&8[&3&lTabooLib&8] &4请输入正确的名称' + INVALID-ITEM: '&8[&3&lTabooLib&8] &4物品 &c{0} &4不存在' + INVALID-PLAYER: '&8[&3&lTabooLib&8] &4玩家 &c{0} &4不在线' + INVALID-NUMBER: '&8[&3&lTabooLib&8] &4数量必须大于0' + SUCCESS: '&8[&3&lTabooLib&8] &7物品已发送至玩家 &f{0} &7的背包中' + VARIABLE: + WRITE-ERROR-TYPE: '&8[&3&lTabooLib&8] &4请输入正确的写入方式: &c-s&4、&c-a' + WRITE-SUCCESS: '&8[&3&lTabooLib&8] &7写入完成, 耗时: &f{0} &7(ms)' + READ-ERROR-TYPE: '&8[&3&lTabooLib&8] &4请输入正确的写入方式: &c-s&4、&c-a' + READ-RESULT: '&8[&3&lTabooLib&8] &7变量 &f{0} &7的值为: &f{1}' + READ-SUCCESS: '&8[&3&lTabooLib&8] &7写入完成, 耗时: &f{0} &7(ms)' + IMPORTDATA: + CLEARING: '&8[&3&lTabooLib&8] &7正在清空数据库...' + EMPTYDATA: '&8[&3&lTabooLib&8] &4没有玩家数据可以导入' + IMPORTING-START: '&8[&3&lTabooLib&8] &7开始导入 &f{0} &7项玩家数据' + IMPORTING-PROGRESS: '&8[&3&lTabooLib&8] &7导入玩家数据: &f{0} &7进度: &f{1}/{2}' + SUCCESS: '&8[&3&lTabooLib&8] &7导入完成' + JAVASHELL: + INVALID-NAME: '&8[&3&lTabooLib&8] &4请输入正确的名称' + INVALID-SHELL: '&8[&3&lTabooLib&8] &4脚本 &c{0} &4不存在' + SUCCESS-LOAD: '&8[&3&lTabooLib&8] &7脚本 &f{0} &7已载入' + SUCCESS-UNLOAD: '&8[&3&lTabooLib&8] &7脚本 &f{0} &7已卸载' + INFO: + INVALID-ITEM: '&8[&3&lTabooLib&8] &4请手持正确的物品' + ITEM-INFO: + - ==: JSON + text: + - '' + - '§b§l----- §3§lItemStack Info §b§l-----' + - '' + - '§7 - 物品材质: §f<{0}@type>' + - '§7 - 物品名称: §f<{1}@name>' + - '§7 - 物品序号: §f<{2}@id>' + - '§7 - 物品数据: §f' + - '' + args: + type: + hover: '§f点击复制' + suggest: '{0}' + name: + hover: '§f点击复制' + suggest: '{1}' + id: + hover: '§f点击复制' + suggest: '{2}' + nbt: + hover: '{3}' + ITEMLIST: + MENU: + TITLE: '物品库 {0}' + NEXT: '§f上一页' + BACK: '§f下一页' + LORE: + - '' + - '§f§m ' + - '§f序列号: §8{0}' + SOUNDS: + MENU: + TITLE: '音效库 {0}' + NEXT: '§f上一页' + BACK: '§f下一页' + LORE: + - '' + - '§f左键: §71 音调' + - '§f右键: §72 音调' + - '§f中键: §7复制名称' + RESULT: + SEARCH: + - '§7查询名称: §f{0}' + - '§7查询结果: §f{1}' + COPY: + - ==: JSON + text: '&7点击复制: <&f&n{0}@sound>' + args: + sound: + hover: 点击复制音效 + suggest: '{0}' + ATTRIBUTES: + HEAD: + - '' + - '§b§l----- §3§lItemStack Attributes §b§l-----' + - '' + BODY: + - ==: JSON + text: ' §7- §f{0} <&8(点击复制)@copy>' + args: + copy: + hover: '§f点击复制' + suggest: '{0}' + FOOT: + - '' + ENCHANTS: + HEAD: + - '' + - '§b§l----- §3§lItemStack Enchantments §b§l-----' + - '' + BODY: + - ==: JSON + text: ' §7- §f{0}. {1} <&8(点击复制)@copy>' + args: + copy: + hover: '§f点击复制' + suggest: '{1}' + FOOT: + - '' + POTIONS: + HEAD: + - '' + - '§b§l----- §3§lItemStack PotionEffects §b§l-----' + - '' + BODY: + - ==: JSON + text: ' §7- §f{0}. {1} <&8(点击复制)@copy>' + args: + copy: + hover: '§f点击复制' + suggest: '{1}' + FOOT: + - '' + FLAGS: + HEAD: + - '' + - '§b§l----- §3§lItemStack Flags §b§l-----' + - '' + BODY: + - ==: JSON + text: ' §7- §f{0} <&8(点击复制)@copy>' + args: + copy: + hover: '§f点击复制' + suggest: '{0}' + FOOT: + - '' + SLOTS: + HEAD: + - '' + - '§b§l----- §3§lItemStack Slots §b§l-----' + - '' + BODY: + - ==: JSON + text: ' §7- §f{0} <&8(点击复制)@copy>' + args: + copy: + hover: '§f点击复制' + suggest: '{0}' + FOOT: + - '' + LANGUAGE2: + HELP: + - '' + - '§b§l----- §3§lLanguage2 Commands §b§l-----' + - '' + - '§f /language2 send §8[§7玩家/ALL§8] §8[§7语言§8] §8<§7变量§8> §6- §e发送语言提示' + - '§f /language2 reload §6- §e重载语言库' + - '' \ No newline at end of file