From 250d168c2eb536f244dff1facd7e81a83e71cdc7 Mon Sep 17 00:00:00 2001 From: Izzel_Aliz Date: Sat, 28 Apr 2018 22:56:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8A=8A=E9=83=A8=E5=88=86=E7=A1=AC=E7=BC=96?= =?UTF-8?q?=E7=A0=81=E8=AF=AD=E8=A8=80=E6=96=87=E4=BB=B6=E6=8A=BD=E5=8F=96?= =?UTF-8?q?=E5=88=B0=E6=96=B0=E7=9A=84=E8=AF=AD=E8=A8=80=E7=B3=BB=E7=BB=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/dictionaries/csh20.xml | 2 + pom.xml | 4 + src/main/java/com/ilummc/tlib/TLib.java | 53 ++++--- .../com/ilummc/tlib/config/TLibConfig.java | 6 - .../ilummc/tlib/dependency/TDependency.java | 31 ++-- .../ilummc/tlib/inject/TConfigInjector.java | 14 +- .../tlib/inject/TDependencyInjector.java | 49 +++--- .../ilummc/tlib/inject/TLoggerManager.java | 25 ++++ .../ilummc/tlib/inject/TPluginManager.java | 33 ++--- .../java/com/ilummc/tlib/logger/TLogger.java | 19 ++- .../com/ilummc/tlib/resources/TLocale.java | 46 +++++- .../tlib/resources/TLocaleInstance.java | 44 +++--- .../ilummc/tlib/resources/TLocaleLoader.java | 27 ++-- .../tlib/resources/TLocaleSendable.java | 43 ++++-- .../tlib/resources/type/TLocaleText.java | 110 +++++++------- .../tlib/resources/type/TLocaleTitle.java | 139 +++++++++--------- src/main/java/com/ilummc/tlib/util/Ref.java | 14 +- .../java/com/ilummc/tlib/util/Strings.java | 2 +- .../tlib/util/asm/AsmClassTransformer.java | 4 + src/main/java/me/skymc/taboolib/Main.java | 29 ++-- .../skymc/taboolib/fileutils/ConfigUtils.java | 13 +- src/main/resources/config.yml | 11 ++ src/main/resources/internalLang.yml | 7 +- src/main/resources/lang/zh_CN.yml | 34 +++++ 24 files changed, 434 insertions(+), 325 deletions(-) create mode 100644 src/main/java/com/ilummc/tlib/inject/TLoggerManager.java create mode 100644 src/main/java/com/ilummc/tlib/util/asm/AsmClassTransformer.java diff --git a/.idea/dictionaries/csh20.xml b/.idea/dictionaries/csh20.xml index 47c7813..31d1c02 100644 --- a/.idea/dictionaries/csh20.xml +++ b/.idea/dictionaries/csh20.xml @@ -1,9 +1,11 @@ + autoload mvdw papi sendable + tlib unserialize unserializer yaml diff --git a/pom.xml b/pom.xml index 0f99a1e..c56e5db 100644 --- a/pom.xml +++ b/pom.xml @@ -8,6 +8,9 @@ TabooLib 3.832 + + UTF-8 + clean install package @@ -42,6 +45,7 @@ com.ilummc.eagletdl + org.ow2.asm false diff --git a/src/main/java/com/ilummc/tlib/TLib.java b/src/main/java/com/ilummc/tlib/TLib.java index eed40c6..6686c94 100644 --- a/src/main/java/com/ilummc/tlib/TLib.java +++ b/src/main/java/com/ilummc/tlib/TLib.java @@ -1,11 +1,5 @@ package com.ilummc.tlib; -import java.io.File; -import java.io.InputStreamReader; -import java.lang.reflect.Field; - -import org.bukkit.Bukkit; - import com.ilummc.tlib.annotations.Dependency; import com.ilummc.tlib.compat.PlaceholderHook; import com.ilummc.tlib.config.TLibConfig; @@ -14,21 +8,29 @@ import com.ilummc.tlib.inject.TConfigWatcher; import com.ilummc.tlib.inject.TDependencyInjector; import com.ilummc.tlib.inject.TPluginManager; 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; import org.bukkit.configuration.file.YamlConfiguration; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.charset.Charset; + @Dependency(type = Dependency.Type.LIBRARY, maven = "org.ow2.asm:asm:6.1.1") @Dependency(type = Dependency.Type.LIBRARY, maven = "com.zaxxer:HikariCP:3.1.0") @Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-api:1.7.25") public class TLib { - @Getter + @Getter private static TLib tLib; - @Getter + @Getter private TLogger logger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE); @Getter @@ -36,7 +38,7 @@ public class TLib { @Getter private TConfigWatcher configWatcher = new TConfigWatcher(); - + @Getter private File libsFolder; @@ -44,33 +46,33 @@ public class TLib { private YamlConfiguration internalLang; private TLib() { - libsFolder = new File(Main.getInst().getDataFolder(), "/libs"); - if (!libsFolder.exists()) { - libsFolder.mkdirs(); - } - internalLang = YamlConfiguration.loadConfiguration(new InputStreamReader(TLib.class.getResourceAsStream("/internalLang.yml"))); + 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); + } catch (IOException | InvalidConfigurationException ignored) { + } } public static void init() { tLib = new TLib(); - + TLoggerFilter.init(); TLocaleLoader.init(); PlaceholderHook.init(); + TLocaleLoader.load(Main.getInst(), false); TDependencyInjector.inject(Main.getInst(), tLib); - - if (Bukkit.getPluginManager() instanceof TPluginManager) { - tLib.getLogger().info("注入成功"); - } else { - tLib.getLogger().fatal("注入失败"); - } } public static void unload() { tLib.getConfigWatcher().unregisterAll(); TDependencyInjector.eject(Main.getInst(), tLib); } - + public static void injectPluginManager() { try { Field field = Bukkit.getServer().getClass().getDeclaredField("pluginManager"); @@ -78,5 +80,10 @@ public class TLib { field.set(Bukkit.getServer(), new TPluginManager()); } catch (NoSuchFieldException | IllegalAccessException ignored) { } + if (Bukkit.getPluginManager() instanceof TPluginManager) { + TLocale.Logger.info("TLIB.INJECTION-SUCCESS"); + } else { + TLocale.Logger.fatal("TLIB.INJECTION-FAILED"); + } } } diff --git a/src/main/java/com/ilummc/tlib/config/TLibConfig.java b/src/main/java/com/ilummc/tlib/config/TLibConfig.java index 744d9f0..f0c4cfc 100644 --- a/src/main/java/com/ilummc/tlib/config/TLibConfig.java +++ b/src/main/java/com/ilummc/tlib/config/TLibConfig.java @@ -9,12 +9,6 @@ import com.ilummc.tlib.annotations.Config; @Config(name = "tlib.yml", listenChanges = true, readOnly = false) public class TLibConfig { - private String[] locale = {"zh_CN", "en_US"}; - - public String[] getLocale() { - return locale; - } - private boolean enablePlaceholderHookByDefault = false; public boolean isEnablePlaceholderHookByDefault() { diff --git a/src/main/java/com/ilummc/tlib/dependency/TDependency.java b/src/main/java/com/ilummc/tlib/dependency/TDependency.java index 61e86a1..193f115 100644 --- a/src/main/java/com/ilummc/tlib/dependency/TDependency.java +++ b/src/main/java/com/ilummc/tlib/dependency/TDependency.java @@ -1,14 +1,13 @@ package com.ilummc.tlib.dependency; -import java.io.File; -import java.util.concurrent.atomic.AtomicBoolean; - import com.ilummc.eagletdl.EagletTask; import com.ilummc.eagletdl.ProgressEvent; -import com.ilummc.tlib.TLib; - +import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.Main; +import java.io.File; +import java.util.concurrent.atomic.AtomicBoolean; + public class TDependency { public static final String MAVEN_REPO = "http://repo.maven.apache.org/maven2"; @@ -54,7 +53,7 @@ public class TDependency { private static boolean downloadMaven(String url, String groupId, String artifactId, String version, File target, String dl) { if (Main.getInst().getConfig().getBoolean("OFFLINE-MODE")) { - TLib.getTLib().getLogger().warn("已启用离线模式, 将不会下载第三方依赖库"); + TLocale.Logger.warn("DEPENDENCY.OFFLINE-DEPENDENCY-WARN"); return false; } AtomicBoolean failed = new AtomicBoolean(false); @@ -63,22 +62,26 @@ public class TDependency { .url(link) .file(target) .setThreads(getDownloadPoolSize()) - .setOnError(event -> {}) - .setOnConnected(event -> TLib.getTLib().getLogger().info(" 正在下载 " + String.join(":", new String[]{groupId, artifactId, version}) + " 大小 " + ProgressEvent.format(event.getContentLength()))) - .setOnProgress(event -> TLib.getTLib().getLogger().info(" 下载速度 " + event.getSpeedFormatted() + " 进度 " + event.getPercentageFormatted())) + .setOnError(event -> { + }) + .setOnConnected(event -> TLocale.Logger.info("DEPENDENCY.DOWNLOAD-CONNECTED", + String.join(":", new String[]{groupId, artifactId, version}), ProgressEvent.format(event.getContentLength()))) + .setOnProgress(event -> TLocale.Logger.info("DEPENDENCY.DOWNLOAD-PROGRESS", + event.getSpeedFormatted(), event.getPercentageFormatted())) .setOnComplete(event -> { if (event.isSuccess()) { - TLib.getTLib().getLogger().info(" 下载 " + String.join(":", new String[]{groupId, artifactId, version}) + " 完成"); + TLocale.Logger.info("DEPENDENCY.DOWNLOAD-SUCCESS", + String.join(":", new String[]{groupId, artifactId, version})); } else { failed.set(true); - TLib.getTLib().getLogger().error(" 下载 " + String.join(":", new String[]{groupId, artifactId, version}) + " 失败"); - TLib.getTLib().getLogger().error(" 请手动下载 " + link + " 并重命名为 " + target.getName() + " 后放在 /TabooLib/libs 文件夹内"); + TLocale.Logger.error("DEPENDENCY.DOWNLOAD-FAILED", + String.join(":", new String[]{groupId, artifactId, version}), link, target.getName()); } }).start().waitUntil(); return !failed.get(); } - + private static int getDownloadPoolSize() { - return Main.getInst().getConfig().contains("DOWNLOAD-POOL-SIZE") ? Main.getInst().getConfig().getInt("DOWNLOAD-POOL-SIZE") : 4; + return Main.getInst().getConfig().getInt("DOWNLOAD-POOL-SIZE", 4); } } diff --git a/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java b/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java index 063a1c9..00cb178 100644 --- a/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java +++ b/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java @@ -1,8 +1,8 @@ package com.ilummc.tlib.inject; import com.google.common.io.Files; -import com.ilummc.tlib.TLib; import com.ilummc.tlib.annotations.Config; +import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.fileutils.ConfigUtils; import org.apache.commons.lang3.Validate; import org.bukkit.configuration.file.YamlConfiguration; @@ -59,9 +59,9 @@ public class TConfigInjector { if (!config.readOnly()) saveConfig(plugin, obj); return obj; } catch (NullPointerException e) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解"); + TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), clazz.getSimpleName()); } catch (Exception e) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败"); + TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName()); } return null; } @@ -75,13 +75,13 @@ public class TConfigInjector { ConfigUtils.yamlToMap( Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz); } catch (NullPointerException e) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解或文件不存在"); + TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-FILE", plugin.toString(), clazz.getSimpleName()); return null; } catch (Exception e) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e1) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败"); + TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName()); return null; } } @@ -93,9 +93,9 @@ public class TConfigInjector { Validate.notNull(config); return ConfigUtils.objToConf(object).getValues(false); } catch (NullPointerException e) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败:没有 @Config 注解"); + TLocale.Logger.warn("CONFIG.SAVE-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName()); } catch (Exception e) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败"); + TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), object.getClass().getSimpleName()); } return null; } diff --git a/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java b/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java index d60e313..09a8a0a 100644 --- a/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java +++ b/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java @@ -1,22 +1,18 @@ package com.ilummc.tlib.inject; -import java.io.File; -import java.lang.reflect.Field; - +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 org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.annotations.Config; -import com.ilummc.tlib.annotations.Dependencies; -import com.ilummc.tlib.annotations.Dependency; -import com.ilummc.tlib.annotations.Logger; -import com.ilummc.tlib.annotations.PluginInstance; -import com.ilummc.tlib.dependency.TDependency; -import com.ilummc.tlib.logger.TLogger; -import com.ilummc.tlib.resources.TLocaleLoader; -import com.ilummc.tlib.util.Ref; +import java.io.File; +import java.lang.reflect.Field; public class TDependencyInjector { @@ -50,9 +46,9 @@ public class TDependencyInjector { try { field.setAccessible(true); TConfigInjector.saveConfig(plugin, field.get(o)); - TLib.getTLib().getLogger().info("插件 " + plugin + " 的配置 " + config.name() + " 已保存"); + TLocale.Logger.info("CONFIG.SAVE-SUCCESS", plugin.toString(), config.name()); } catch (Exception e) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置 " + config.name() + " 保存失败"); + TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), config.name()); e.printStackTrace(); } } @@ -67,10 +63,10 @@ public class TDependencyInjector { field.setAccessible(true); Object obj = TConfigInjector.loadConfig(plugin, field.getType()); if (obj != null) { - TLib.getTLib().getLogger().info("插件 " + plugin.getName() + " 的 " + config.name() + " 配置文件成功加载"); + TLocale.Logger.info("CONFIG.LOAD-SUCCESS", plugin.toString(), config.name()); field.set(o, obj); if (config.listenChanges()) { - TLib.getTLib().getLogger().info("开始监听插件 " + plugin.getName() + " 的 " + config.name() + " 配置文件"); + TLocale.Logger.info("CONFIG.LISTEN-START", plugin.toString(), config.name()); TLib.getTLib().getConfigWatcher().addOnListen( new File(plugin.getDataFolder(), config.name()), obj, @@ -81,9 +77,9 @@ public class TDependencyInjector { f.setAccessible(true); f.set(obj, f.get(newObj)); } - TLib.getTLib().getLogger().info("插件 " + plugin.getName() + " 的 " + config.name() + " 配置文件成功重载"); + TLocale.Logger.info("CONFIG.RELOAD-SUCCESS", plugin.toString(), config.name()); } catch (Exception ignored) { - TLib.getTLib().getLogger().warn("插件 " + plugin.getName() + " 的 " + config.name() + " 配置文件重载时发生错误"); + TLocale.Logger.warn("CONFIG.RELOAD-FAIL", plugin.toString(), config.name()); } } ); @@ -105,6 +101,7 @@ public class TDependencyInjector { if (!field.isAccessible()) field.setAccessible(true); field.set(o, tLogger); + TLoggerManager.setDefaultLogger(plugin, tLogger); } } catch (Exception ignored2) { } @@ -122,7 +119,7 @@ public class TDependencyInjector { Plugin pl; if ((pl = Bukkit.getPluginManager().getPlugin(instance.value())) == null) { if (!TDependency.requestPlugin(instance.value())) { - TLib.getTLib().getLogger().warn(plugin.getName() + " 所需的依赖插件 " + instance.value() + " 自动加载失败"); + TLocale.Logger.warn("PLUGIN-AUTOLOAD-FAIL", plugin.getName(), instance.value()); return; } else { pl = Bukkit.getPluginManager().getPlugin(instance.value()); @@ -149,24 +146,24 @@ public class TDependencyInjector { } } if (dependencies.length != 0) { - TLib.getTLib().getLogger().info("正在加载 " + plugin.getName() + " 插件所需的依赖"); + TLocale.Logger.info("DEPENDENCY.LOADING-START", plugin.getName()); for (Dependency dependency : dependencies) { if (dependency.type() == Dependency.Type.PLUGIN) { if (TDependency.requestPlugin(dependency.plugin())) { - TLib.getTLib().getLogger().info(" " + plugin.getName() + " 请求的插件 " + dependency.plugin() + " 加载成功。"); + TLocale.Logger.info("DEPENDENCY.PLUGIN-LOAD-SUCCESS", plugin.getName(), dependency.plugin()); } else { - TLib.getTLib().getLogger().warn(" " + plugin.getName() + " 请求的插件 " + dependency.plugin() + " 加载失败。"); + TLocale.Logger.warn("DEPENDENCY.PLUGIN-LOAD-FAIL", plugin.getName(), dependency.plugin()); } } if (dependency.type() == Dependency.Type.LIBRARY) { if (TDependency.requestLib(dependency.maven(), dependency.mavenRepo(), dependency.url())) { - TLib.getTLib().getLogger().info(" " + plugin.getName() + " 请求的库文件 " + String.join(":", dependency.maven()) + " 加载成功。"); + TLocale.Logger.info("DEPENDENCY.LIBRARY-LOAD-SUCCESS", plugin.getName(), String.join(":", dependency.maven())); } else { - TLib.getTLib().getLogger().warn(" " + plugin.getName() + " 请求的库文件 " + String.join(":", dependency.maven()) + " 加载失败。"); + TLocale.Logger.warn("DEPENDENCY.LIBRARY-LOAD-FAIL", plugin.getName(), String.join(":", dependency.maven())); } } } - TLib.getTLib().getLogger().info("依赖加载完成"); + TLocale.Logger.info("DEPENDENCY.LOAD-COMPLETE"); } } diff --git a/src/main/java/com/ilummc/tlib/inject/TLoggerManager.java b/src/main/java/com/ilummc/tlib/inject/TLoggerManager.java new file mode 100644 index 0000000..98f30f4 --- /dev/null +++ b/src/main/java/com/ilummc/tlib/inject/TLoggerManager.java @@ -0,0 +1,25 @@ +package com.ilummc.tlib.inject; + +import com.ilummc.tlib.logger.TLogger; +import org.bukkit.plugin.Plugin; + +import java.util.HashMap; +import java.util.Map; + +public class TLoggerManager { + + private static final Map map = new HashMap<>(); + + public static void setDefaultLogger(Plugin plugin, TLogger logger) { + map.put(plugin, logger); + } + + public static TLogger getLogger(Plugin plugin) { + TLogger logger = map.get(plugin); + if (logger == null) { + logger = TLogger.getUnformatted(plugin); + map.put(plugin, logger); + } + return logger; + } +} diff --git a/src/main/java/com/ilummc/tlib/inject/TPluginManager.java b/src/main/java/com/ilummc/tlib/inject/TPluginManager.java index 59b80df..bb1aa46 100644 --- a/src/main/java/com/ilummc/tlib/inject/TPluginManager.java +++ b/src/main/java/com/ilummc/tlib/inject/TPluginManager.java @@ -1,15 +1,7 @@ package com.ilummc.tlib.inject; -import java.io.File; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - +import com.ilummc.tlib.resources.TLocale; +import me.skymc.taboolib.Main; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.command.SimpleCommandMap; @@ -18,17 +10,12 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.permissions.Permissible; import org.bukkit.permissions.Permission; -import org.bukkit.plugin.EventExecutor; -import org.bukkit.plugin.InvalidDescriptionException; -import org.bukkit.plugin.InvalidPluginException; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginLoader; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.UnknownDependencyException; +import org.bukkit.plugin.*; -import com.ilummc.tlib.TLib; - -import me.skymc.taboolib.Main; +import java.io.File; +import java.lang.reflect.Field; +import java.util.*; +import java.util.regex.Pattern; @SuppressWarnings("unused") public class TPluginManager implements PluginManager { @@ -68,14 +55,14 @@ public class TPluginManager implements PluginManager { Field bukkitField = instance.getClass().getDeclaredField(bukkitName); Field thisFiled = this.getClass().getDeclaredField(bukkitName); if (bukkitField == null || thisFiled == null) { - TLib.getTLib().getLogger().warn("拷贝 " + bukkitName + " 对象失败"); + TLocale.Logger.warn("MISC.FIELD-COPY-FAILED", bukkitName); return; } bukkitField.setAccessible(true); thisFiled.setAccessible(true); thisFiled.set(this, bukkitField.get(instance)); - } catch (Exception ignored) { - TLib.getTLib().getLogger().error("拷贝 " + bukkitName + " 对象出错"); + } catch (Exception e) { + TLocale.Logger.error("MISC.FIELD-COPY-ERROR", bukkitName, e.toString()); } } diff --git a/src/main/java/com/ilummc/tlib/logger/TLogger.java b/src/main/java/com/ilummc/tlib/logger/TLogger.java index 2f6b3e0..b2ee777 100644 --- a/src/main/java/com/ilummc/tlib/logger/TLogger.java +++ b/src/main/java/com/ilummc/tlib/logger/TLogger.java @@ -1,19 +1,17 @@ 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; import org.bukkit.plugin.Plugin; -import com.ilummc.tlib.util.Strings; - -import lombok.Getter; -import lombok.Setter; -import me.skymc.taboolib.Main; - 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 @@ -64,4 +62,9 @@ public class TLogger { if (level <= FATAL) Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, plugin.getName(), "§4致命错误", "§4" + ChatColor.translateAlternateColorCodes('&', msg))); } + + public static TLogger getUnformatted(Plugin plugin) { + return new TLogger("§8[§3§l{0}§8][§r{1}§8] §f{2}", plugin, TLogger.FINE); + } + } diff --git a/src/main/java/com/ilummc/tlib/resources/TLocale.java b/src/main/java/com/ilummc/tlib/resources/TLocale.java index 147812e..a948875 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocale.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocale.java @@ -1,7 +1,9 @@ package com.ilummc.tlib.resources; import com.ilummc.tlib.TLib; +import com.ilummc.tlib.inject.TLoggerManager; import com.ilummc.tlib.util.Ref; +import com.ilummc.tlib.util.Strings; import me.skymc.taboolib.Main; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; @@ -9,7 +11,7 @@ import org.bukkit.plugin.java.JavaPlugin; import java.lang.reflect.Field; -public final class TLocale { +public class TLocale { private TLocale() { throw new AssertionError(); @@ -30,8 +32,8 @@ public final class TLocale { TLocaleLoader.sendTo(getCallerPlugin(callerClass), path, sender, args); } - private static String asString(String path, String[] args, Class callerClass) { - return TLocaleLoader.asString(getCallerPlugin(callerClass), path); + static String asString(String path, Class callerClass, String... args) { + return TLocaleLoader.asString(getCallerPlugin(callerClass), path, args); } public static void sendToConsole(String path, String... args) { @@ -48,10 +50,10 @@ public final class TLocale { public static String asString(String path, String... args) { try { - return asString(path, args, Ref.getCallerClass(3).get()); + return asString(path, Ref.getCallerClass(3).get(), args); } catch (Exception e) { - TLib.getTLib().getLogger().error("语言文件获取失败: " + path); - TLib.getTLib().getLogger().error("原因: " + e.getMessage()); + 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())); return "§4<" + path + "§4>"; } } @@ -59,4 +61,36 @@ public final class TLocale { public static void reload() { Ref.getCallerClass(3).ifPresent(clazz -> TLocaleLoader.load(getCallerPlugin(clazz), false)); } + + public static final class Logger extends TLocale { + + public static void info(String path, String... args) { + Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).info(asString(path, clazz, args))); + } + + public static void warn(String path, String... args) { + Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).warn(asString(path, clazz, args))); + } + + public static void error(String path, String... args) { + Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).error(asString(path, clazz, args))); + } + + public static void fatal(String path, String... args) { + Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).fatal(asString(path, clazz, args))); + } + + public static void fine(String path, String... args) { + Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).fine(asString(path, clazz, args))); + } + + public static void finest(String path, String... args) { + Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).finest(asString(path, clazz, args))); + } + + public static void verbose(String path, String... args) { + Ref.getCallerClass(3).ifPresent(clazz -> TLoggerManager.getLogger(TLocale.getCallerPlugin(clazz)).verbose(asString(path, clazz, args))); + } + } + } diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java b/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java index 900598e..6fde383 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleInstance.java @@ -3,6 +3,7 @@ package com.ilummc.tlib.resources; import com.google.common.collect.ImmutableList; import com.ilummc.tlib.TLib; import com.ilummc.tlib.resources.type.TLocaleText; +import com.ilummc.tlib.util.Strings; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; @@ -37,30 +38,38 @@ class TLocaleInstance { } }); } catch (Exception e) { - TLib.getTLib().getLogger().error("语言文件发送失败: " + path); - TLib.getTLib().getLogger().error("原因: " + e.getMessage()); + 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.getMessage())); } } - String asString(String path) { - return map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).get(0).asString(); + String asString(String path, String... args) { + return map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).get(0).asString(args); } void load(YamlConfiguration configuration) { - configuration.getKeys(false).forEach(s -> { + configuration.getKeys(true).forEach(s -> { Object object = configuration.get(s); - if (object instanceof ConfigurationSection) { - loadRecursively(s, (ConfigurationSection) object); - } else if (object instanceof TLocaleSendable) { + if (object instanceof TLocaleSendable) { map.put(s, Collections.singletonList((TLocaleSendable) object)); } else if (object instanceof List && !((List) object).isEmpty()) { map.put(s, ((List) object).stream().map(TO_SENDABLE).collect(Collectors.toList())); - } else { - map.put(s, Collections.singletonList(TLocaleText.of(String.valueOf(object)))); + } else if (!(object instanceof ConfigurationSection)) { + String str = String.valueOf(object); + map.put(s, Collections.singletonList(str.length() == 0 ? TLocaleSendable.getEmpty() : TLocaleText.of(str))); } }); } + 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); @@ -73,19 +82,4 @@ class TLocaleInstance { private final Map> map = new HashMap<>(); - private void loadRecursively(String path, ConfigurationSection section) { - section.getKeys(false).forEach(s -> { - Object object = section.get(path + "." + s); - if (object instanceof ConfigurationSection) { - loadRecursively(path + "." + s, (ConfigurationSection) object); - } else if (object instanceof TLocaleSendable) { - map.put(path + "." + s, Collections.singletonList((TLocaleSendable) object)); - } else if (object instanceof List && !((List) object).isEmpty()) { - map.put(path + "." + s, ((List) object).stream().map(TO_SENDABLE).collect(Collectors.toList())); - } else { - map.put(path + "." + s, Collections.singletonList(TLocaleText.of(String.valueOf(object)))); - } - }); - } - } diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java index 09edb2a..c979109 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java @@ -6,7 +6,6 @@ import com.ilummc.tlib.resources.type.TLocaleTitle; import com.ilummc.tlib.util.Strings; import me.skymc.taboolib.Main; import me.skymc.taboolib.fileutils.ConfigUtils; -import me.skymc.taboolib.fileutils.FileUtils; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; @@ -14,8 +13,6 @@ import org.bukkit.configuration.serialization.ConfigurationSerialization; import org.bukkit.plugin.Plugin; import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.StandardOpenOption; @@ -35,8 +32,8 @@ public class TLocaleLoader { } } - static String asString(Plugin plugin, String path) { - return map.get(plugin.getName()).asString(path); + static String asString(Plugin plugin, String path, String... args) { + return map.get(plugin.getName()).asString(path, args); } public static void init() { @@ -46,11 +43,11 @@ public class TLocaleLoader { 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")) { + 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 : TLib.getTLib().getConfig().getLocale()) { + for (String s : Main.getInst().getConfig().getStringList("LOCALE.PRIORITY")) { lang = s; file = new File(plugin.getDataFolder(), "/lang/" + s + ".yml"); if (file.exists()) { @@ -67,10 +64,10 @@ public class TLocaleLoader { if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); - saveResource(inputStream, file); + plugin.saveResource("lang/" + lang + ".yml", true); } TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("TRY-LOADING-LANG"), plugin.getName(), lang)); - synchronized (TLocaleLoader.class) { + { YamlConfiguration configuration = ConfigUtils.loadYaml(plugin, file); TLocaleInstance localeInstance = new TLocaleInstance(plugin); localeInstance.load(configuration); @@ -84,19 +81,15 @@ public class TLocaleLoader { 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)); + TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SUCCESS-LOADING-LANG"), + plugin.getName(), finalLang, String.valueOf(localeInstance.size()))); }); TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SUCCESS-LOADING-LANG"), plugin.getName(), lang)); } } catch (Exception e) { - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("ERROR-LOADING-LANG"), plugin.getName(), e.toString())); + TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("ERROR-LOADING-LANG"), + plugin.getName(), e.toString() + "\n" + e.getStackTrace()[0].toString())); } } - private static void saveResource(InputStream inputStream, File file) throws IOException { - byte[] data = FileUtils.read(inputStream); - try (FileOutputStream fileOutputStream = new FileOutputStream(file)) { - fileOutputStream.write(data); - } - } } diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleSendable.java b/src/main/java/com/ilummc/tlib/resources/TLocaleSendable.java index 46db128..61959e5 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleSendable.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleSendable.java @@ -3,22 +3,35 @@ package com.ilummc.tlib.resources; import org.bukkit.command.CommandSender; public interface TLocaleSendable { - - static TLocaleSendable getEmpty(String path) { - return new TLocaleSendable() { - @Override - public void sendTo(CommandSender sender, String... args) { - sender.sendMessage("§4<" + path + "§4>"); - } - - @Override - public String asString(String... args) { - return "§4<" + path + "§4>"; - } - }; - } + + static TLocaleSendable getEmpty(String path) { + return new TLocaleSendable() { + @Override + public void sendTo(CommandSender sender, String... args) { + sender.sendMessage("§4<" + path + "§4>"); + } + + @Override + 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 ""; + } + }; + } void sendTo(CommandSender sender, String... args); - + String asString(String... 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 7ce0a0b..0cb0ce5 100644 --- a/src/main/java/com/ilummc/tlib/resources/type/TLocaleText.java +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleText.java @@ -1,26 +1,20 @@ package com.ilummc.tlib.resources.type; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -import javax.annotation.concurrent.Immutable; - -import org.bukkit.Bukkit; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.ilummc.tlib.compat.PlaceholderHook; +import com.ilummc.tlib.resources.TLocaleSendable; +import com.ilummc.tlib.util.Strings; +import me.skymc.taboolib.Main; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.configuration.serialization.SerializableAs; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.compat.PlaceholderHook; -import com.ilummc.tlib.resources.TLocaleSendable; -import com.ilummc.tlib.util.Strings; +import javax.annotation.concurrent.Immutable; +import java.util.*; +import java.util.stream.Collectors; @Immutable @SerializableAs("TEXT") @@ -35,74 +29,78 @@ public class TLocaleText implements TLocaleSendable, ConfigurationSerializable { this.usePlaceholder = usePlaceholder; if (text instanceof String) { this.text = text; - } - else if (text instanceof List) { + } else if (text instanceof List) { this.text = ImmutableList.copyOf(((List) text)); - } - else { - throw new IllegalArgumentException("Param 'text' can only be an instance of String or String[] or List"); + } else { + throw new IllegalArgumentException("Param 'text' can only be an instance of String or List"); } } - + private String replaceMsg(CommandSender sender, String s) { return usePlaceholder ? PlaceholderHook.replace(sender, s) : s; } + public static TLocaleText valueOf(Map map) { + if (map.containsKey("text")) { + Object object = map.get("text"); + Object objPapi = map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false)); + boolean papi = objPapi instanceof Boolean ? (boolean) objPapi : objPapi instanceof String && objPapi.equals("true"); + if (object instanceof List) { + return new TLocaleText(((List) object).stream() + .map(s -> ChatColor.translateAlternateColorCodes('&', s)) + .collect(Collectors.toList()), papi); + } else if (object instanceof String[]) { + return new TLocaleText(Arrays.stream(((String[]) object)) + .map(s -> ChatColor.translateAlternateColorCodes('&', s)) + .collect(Collectors.toList()), papi); + } else { + return new TLocaleText(ChatColor.translateAlternateColorCodes('&', Objects.toString(object)), papi); + } + } + return new TLocaleText("§cError chat message loaded.", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false)); + } + + public static TLocaleText of(String s) { + return new TLocaleText(ChatColor.translateAlternateColorCodes('&', s), Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false)); + } + @Override public void sendTo(CommandSender sender, String... args) { if (text instanceof String) { sender.sendMessage(replaceMsg(sender, Strings.replaceWithOrder((String) text, args))); - } - else if (text instanceof List) { + } else if (text instanceof List) { ((List) text).forEach(s -> sender.sendMessage(replaceMsg(sender, Strings.replaceWithOrder(String.valueOf(s), args)))); } } - + @Override public String asString(String... args) { - return Strings.replaceWithOrder((String) text, args); + return Strings.replaceWithOrder(objectToString(text), args); + } + + private String objectToString(Object text) { + if (text instanceof String) return ((String) text); + else { + StringJoiner joiner = new StringJoiner("\n"); + ((List) text).forEach(joiner::add); + return joiner.toString(); + } } @Override public String toString() { if (text instanceof String[]) { - return Arrays.toString((String[]) text); + return Arrays.toString((String[]) text); } else { - return text.toString(); + return text.toString(); } } - + @Override public Map serialize() { if (usePlaceholder) { - return Maps.newHashMap(ImmutableMap.of("text", text, "papi", true)); + return Maps.newHashMap(ImmutableMap.of("text", text, "papi", true)); } return Maps.newHashMap(ImmutableMap.of("text", text)); } - - public static TLocaleText valueOf(Map map) { - if (map.containsKey("text")) { - Object object = map.get("text"); - Object objPapi = map.getOrDefault("papi", TLib.getTLib().getConfig().isEnablePlaceholderHookByDefault()); - boolean papi = objPapi instanceof Boolean ? (boolean) objPapi : objPapi instanceof String && objPapi.equals("true"); - if (object instanceof List) { - return new TLocaleText(((List) object).stream() - .map(s -> ChatColor.translateAlternateColorCodes('&', s)) - .collect(Collectors.toList()), papi); - } - else if (object instanceof String[]) { - return new TLocaleText(Arrays.stream(((String[]) object)) - .map(s -> ChatColor.translateAlternateColorCodes('&', s)) - .collect(Collectors.toList()), papi); - } - else { - return new TLocaleText(ChatColor.translateAlternateColorCodes('&', Objects.toString(object)), papi); - } - } - return new TLocaleText("§cError chat message loaded.", TLib.getTLib().getConfig().isEnablePlaceholderHookByDefault()); - } - - public static TLocaleText of(String s) { - return new TLocaleText(ChatColor.translateAlternateColorCodes('&', s), TLib.getTLib().getConfig().isEnablePlaceholderHookByDefault()); - } } 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 320cdae..7628140 100644 --- a/src/main/java/com/ilummc/tlib/resources/type/TLocaleTitle.java +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleTitle.java @@ -1,23 +1,21 @@ package com.ilummc.tlib.resources.type; -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.concurrent.Immutable; - +import com.google.common.collect.Maps; +import com.ilummc.tlib.TLib; +import com.ilummc.tlib.compat.PlaceholderHook; +import com.ilummc.tlib.resources.TLocale; +import com.ilummc.tlib.resources.TLocaleSendable; +import com.ilummc.tlib.util.Strings; +import me.skymc.taboolib.display.TitleUtils; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.entity.Player; -import com.google.common.collect.Maps; -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.compat.PlaceholderHook; -import com.ilummc.tlib.resources.TLocaleSendable; -import com.ilummc.tlib.util.Strings; - -import me.skymc.taboolib.display.TitleUtils; +import javax.annotation.concurrent.Immutable; +import java.util.HashMap; +import java.util.Map; /** * @author Bkm016 @@ -27,66 +25,71 @@ import me.skymc.taboolib.display.TitleUtils; @Immutable @SerializableAs("TITLE") public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable { - - private final String title; - private final String subtitle; - private final int fadein; - private final int fadeout; - private final int stay; - - private boolean usePlaceholder; - - private TLocaleTitle(String title, String subString, int fadein, int fadeout, int stay, boolean usePlaceholder) { - this.title = title; - this.subtitle = subString; - this.fadein = fadein; - this.fadeout = fadeout; - this.stay = stay; - this.usePlaceholder = usePlaceholder; - } - @Override - public void sendTo(CommandSender sender, String... args) { - if (sender instanceof Player) { - TitleUtils.sendTitle((Player) sender, replaceText(sender, title), replaceText(sender, subtitle), fadein, stay, fadeout); - } else { - TLib.getTLib().getLogger().error("该语言类型只能发送给玩家"); - } - } + private final String title; + private final String subtitle; + private final int fadein; + private final int fadeout; + private final int stay; - @Override - public String asString(String... args) { - return Strings.replaceWithOrder(title, args); - } + private boolean usePlaceholder; - @Override - public Map serialize() { - HashMap map = Maps.newHashMap(); - map.put("papi", usePlaceholder); - map.put("title", title); - map.put("subtitle", subtitle); - map.put("fadein", fadein); - map.put("fadeout", fadeout); - map.put("stay", stay); - return map; - } - - public static TLocaleTitle valueOf(Map map) { - TLocaleTitle title; - try { + private TLocaleTitle(String title, String subString, int fadein, int fadeout, int stay, boolean usePlaceholder) { + this.title = title; + this.subtitle = subString; + this.fadein = fadein; + this.fadeout = fadeout; + this.stay = stay; + this.usePlaceholder = usePlaceholder; + } + + public static TLocaleTitle valueOf(Map map) { + TLocaleTitle title; + try { title = new TLocaleTitle( - (String) map.getOrDefault("title", ""), - (String) map.getOrDefault("subtitle", ""), - (int) map.getOrDefault("fadein", 10), - (int) map.getOrDefault("fadeout", 10), - (int) map.getOrDefault("stay", 20), - (boolean) map.getOrDefault("papi", TLib.getTLib().getConfig().isEnablePlaceholderHookByDefault())); - } catch (Exception e) { - title = new TLocaleTitle("§4Load failed!", "§c" + e.getMessage(), 10, 20, 10, false); - } - return title; - } - + (String) map.getOrDefault("title", ""), + (String) map.getOrDefault("subtitle", ""), + (int) map.getOrDefault("fadein", 10), + (int) map.getOrDefault("fadeout", 10), + (int) map.getOrDefault("stay", 20), + (boolean) map.getOrDefault("papi", TLib.getTLib().getConfig().isEnablePlaceholderHookByDefault())); + } catch (Exception e) { + title = new TLocaleTitle("§4Load failed!", "§c" + e.getMessage(), 10, 20, 10, false); + } + return title; + } + + @Override + public void sendTo(CommandSender sender, String... args) { + if (sender instanceof Player) { + TitleUtils.sendTitle((Player) sender, replaceText(sender, title), replaceText(sender, subtitle), fadein, stay, fadeout); + } else { + TLocale.Logger.error("LOCALE.TITLE-SEND-TO-NON-PLAYER", asString(args)); + } + } + + @Override + public String asString(String... args) { + return Strings.replaceWithOrder("TITLE: [title: '" + title + "', subtitle: '" + subtitle + "', fadeIn: " + fadein + ", fadeOut: " + fadeout + "]", args); + } + + @Override + public String toString() { + return asString(); + } + + @Override + public Map serialize() { + HashMap map = Maps.newHashMap(); + map.put("papi", usePlaceholder); + map.put("title", title); + map.put("subtitle", subtitle); + map.put("fadein", fadein); + map.put("fadeout", fadeout); + map.put("stay", stay); + return map; + } + private String replaceText(CommandSender sender, String s) { return ChatColor.translateAlternateColorCodes('&', usePlaceholder ? PlaceholderHook.replace(sender, s) : s); } diff --git a/src/main/java/com/ilummc/tlib/util/Ref.java b/src/main/java/com/ilummc/tlib/util/Ref.java index 0ee1f1e..53f20ea 100644 --- a/src/main/java/com/ilummc/tlib/util/Ref.java +++ b/src/main/java/com/ilummc/tlib/util/Ref.java @@ -22,7 +22,7 @@ public class Ref { public static final int ACC_SYNTHETIC = 0x1000; public static List getDeclaredFields(Class clazz) { - return getDeclaredFields(clazz, 0, false); + return getDeclaredFields(clazz, 0, true); } public static List getDeclaredFields(String clazz, int excludeModifiers, boolean cache) { @@ -40,7 +40,6 @@ public class Ref { if (clazz == TLib.class) return Arrays.asList(clazz.getDeclaredFields()); - Class.forName("org.objectweb.asm.ClassVisitor"); List fields; if ((fields = cachedFields.get(clazz.getName())) != null) return fields; ClassReader classReader = new ClassReader(clazz.getResourceAsStream("/" + clazz.getName().replace('.', '/') + ".class")); @@ -55,8 +54,15 @@ public class Ref { }).filter(Objects::nonNull).collect(Collectors.toList()); if (cache) cachedFields.putIfAbsent(clazz.getName(), fields); return fields; - } catch (Exception e) { - return Collections.emptyList(); + } catch (Exception | Error e) { + try { + List list = Arrays.stream(clazz.getDeclaredFields()) + .filter(field -> (field.getModifiers() & excludeModifiers) == 0).collect(Collectors.toList()); + cachedFields.putIfAbsent(clazz.getName(), list); + return list; + } catch (Error err) { + return Collections.emptyList(); + } } } diff --git a/src/main/java/com/ilummc/tlib/util/Strings.java b/src/main/java/com/ilummc/tlib/util/Strings.java index 3e5bba3..04acc68 100644 --- a/src/main/java/com/ilummc/tlib/util/Strings.java +++ b/src/main/java/com/ilummc/tlib/util/Strings.java @@ -10,7 +10,7 @@ public class Strings { * @return 替换好的字符串 */ public static String replaceWithOrder(String template, String... args) { - if (args.length == 0) return template; + if (args.length == 0 || template.length() == 0) return template; char[] arr = template.toCharArray(); StringBuilder stringBuilder = new StringBuilder(template.length()); for (int i = 0; i < arr.length; i++) { diff --git a/src/main/java/com/ilummc/tlib/util/asm/AsmClassTransformer.java b/src/main/java/com/ilummc/tlib/util/asm/AsmClassTransformer.java new file mode 100644 index 0000000..5bd04d8 --- /dev/null +++ b/src/main/java/com/ilummc/tlib/util/asm/AsmClassTransformer.java @@ -0,0 +1,4 @@ +package com.ilummc.tlib.util.asm; + +public class AsmClassTransformer { +} diff --git a/src/main/java/me/skymc/taboolib/Main.java b/src/main/java/me/skymc/taboolib/Main.java index 9dd4698..c435b2a 100644 --- a/src/main/java/me/skymc/taboolib/Main.java +++ b/src/main/java/me/skymc/taboolib/Main.java @@ -1,17 +1,6 @@ package me.skymc.taboolib; -import java.io.File; -import java.util.Random; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.event.Listener; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitRunnable; - import com.ilummc.tlib.TLib; - import lombok.Getter; import lombok.Setter; import me.skymc.taboolib.anvil.AnvilContainerAPI; @@ -30,11 +19,7 @@ import me.skymc.taboolib.fileutils.ConfigUtils; import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.inventory.speciaitem.SpecialItem; import me.skymc.taboolib.javashell.JavaShell; -import me.skymc.taboolib.listener.ListenerNetWork; -import me.skymc.taboolib.listener.ListenerPlayerCommand; -import me.skymc.taboolib.listener.ListenerPlayerJump; -import me.skymc.taboolib.listener.ListenerPlayerQuit; -import me.skymc.taboolib.listener.ListenerPluginDisable; +import me.skymc.taboolib.listener.*; import me.skymc.taboolib.message.ChatCatcher; import me.skymc.taboolib.message.MsgUtils; import me.skymc.taboolib.mysql.protect.MySQLConnection; @@ -54,6 +39,15 @@ import me.skymc.tlm.TLM; import me.skymc.tlm.command.TLMCommands; import me.skymc.tlm.module.TabooLibraryModule; import net.milkbowl.vault.economy.Economy; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.event.Listener; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitRunnable; + +import java.io.File; +import java.util.Random; @SuppressWarnings("deprecation") public class Main extends JavaPlugin implements Listener { @@ -111,13 +105,12 @@ public class Main extends JavaPlugin implements Listener { inst = this; disable = false; - TLib.injectPluginManager(); - // 载入配置 saveDefaultConfig(); // 加载依赖 TLib.init(); + TLib.injectPluginManager(); // 载入目录 setupDataFolder(); diff --git a/src/main/java/me/skymc/taboolib/fileutils/ConfigUtils.java b/src/main/java/me/skymc/taboolib/fileutils/ConfigUtils.java index b7a5658..b05ce00 100644 --- a/src/main/java/me/skymc/taboolib/fileutils/ConfigUtils.java +++ b/src/main/java/me/skymc/taboolib/fileutils/ConfigUtils.java @@ -1,7 +1,7 @@ package me.skymc.taboolib.fileutils; -import com.google.common.base.Charsets; import com.google.common.collect.Maps; +import com.google.common.io.Files; import com.ilummc.tlib.TLib; import com.ilummc.tlib.util.Ref; import org.bukkit.configuration.ConfigurationSection; @@ -14,11 +14,10 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; import java.io.StringReader; import java.lang.reflect.Field; import java.lang.reflect.Modifier; +import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.Map; @@ -164,15 +163,17 @@ public class ConfigUtils { } public static YamlConfiguration loadYaml(Plugin plugin, File file) { - YamlConfiguration yaml = new YamlConfiguration(); + YamlConfiguration configuration = new YamlConfiguration(); try { - yaml = YamlConfiguration.loadConfiguration(new InputStreamReader(new FileInputStream(file), Charsets.UTF_8)); + String yaml = Files.toString(file, Charset.forName("utf-8")); + configuration.loadFromString(yaml); + return configuration; } catch (Exception e) { TLib.getTLib().getLogger().error("配置文件载入失败!"); TLib.getTLib().getLogger().error("插件: &4" + plugin.getName()); TLib.getTLib().getLogger().error("文件: &4" + file); } - return yaml; + return configuration; } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index b7c6087..93de0ee 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -24,6 +24,17 @@ OFFLINE-MODE: false # 下载依赖时启用的线程数 DOWNLOAD-POOL-SIZE: 4 +# 语言文件相关设置 +LOCALE: + # 加载语言文件的顺序 + PRIORITY: + - zh_CN + - en_US + # 默认是否启用语言文件中 PlaceholderAPI 的替换功能 + # 关闭可提升性能 + # 如果需要开启仍然可以在语言文件中加入 papi: true + USE_PAPI: false + # 是否启用更新检测 UPDATE-CHECK: true diff --git a/src/main/resources/internalLang.yml b/src/main/resources/internalLang.yml index dcb45bb..6060850 100644 --- a/src/main/resources/internalLang.yml +++ b/src/main/resources/internalLang.yml @@ -1,5 +1,8 @@ LANG-LOAD-FAIL: '语言文件加载失败' TRY-LOADING-LANG: '插件 {0} 尝试加载 {1} .yml 作为语言文件' -SUCCESS-LOADING-LANG: '成功加载 {0} 插件的 {1} 语言文件' +SUCCESS-LOADING-LANG: '成功加载 {0} 插件的 {1} 语言文件,共 {2} 条' ERROR-LOADING-LANG: '加载 {0} 插件的语言文件时发生异常:{1}' -RELOADING-LANG: '正在重新载入 {0} 插件的语言文件' \ No newline at end of file +RELOADING-LANG: '正在重新载入 {0} 插件的语言文件' +FETCH-LOCALE-ERROR: '语言文件获取失败:{0}' +SEND-LOCALE-ERROR: '语言文件发送失败:{0}' +LOCALE-ERROR-REASON: '原因:{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 e69de29..77f4c75 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -0,0 +1,34 @@ +TLIB: + INJECTION-SUCCESS: '注入成功' + INJECTION-FAILED: '注入失败' +DEPENDENCY: + OFFLINE-DEPENDENCY-WARN: '已启用离线模式, 将不会下载第三方依赖库' + DOWNLOAD-CONNECTED: ' 正在下载 {0} 大小 {1}' + DOWNLOAD-PROGRESS: ' 下载速度 {0} 进度 {1}' + DOWNLOAD-SUCCESS: ' 下载 {0} 完成' + DOWNLOAD-FAILED: + - ' 下载 {0} 失败' + - ' 请手动下载 {1} 并重命名为 {2} 后放在 /TabooLib/libs 文件夹内' + PLUGIN-AUTOLOAD-FAIL: '{0} 所依赖的插件 {1} 尝试自动加载失败,请尝试手动下载' + PLUGIN-LOAD-SUCCESS: ' {0} 请求的插件 {1} 加载成功' + PLUGIN-LOAD-FAIL: ' {0} 请求的插件 {1} 加载失败' + LOADING-START: '正在加载 {0} 插件所需的依赖' + 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 注解' + LOAD-FAIL-NO-FILE: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解或文件不存在' + LOAD-SUCCESS: '插件 {0} 的 {1} 配置文件成功加载' + SAVE-FAIL-NO-ANNOTATION: '插件 {0} 的配置类 {1} 序列化失败:没有 @Config 注解' + SAVE-FAIL: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解' + SAVE-SUCCESS: '插件 {0} 的配置 {1} 已保存' + 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}'