Name optimized

DataUtils => Local
PlayerDataManager => LocalPlayer
NMSHandler => NMS
HikariHandler => DBSource
This commit is contained in:
坏黑 2019-07-06 18:50:05 +08:00
parent 8b1b14ae7c
commit 6364f38d03
26 changed files with 343 additions and 342 deletions

View File

@ -1,11 +1,3 @@
# 数据储存地址
# 该配置将在启用数据库储存时失效
DATAURL:
# 玩家数据
PLAYER-DATA: 'plugins/TabooLib/playerdata/'
# 插件数据
SERVER-DATA: 'plugins/TabooLib/serverdata/'
# 语言文件相关设置
LOCALE:
# 加载语言文件的顺序
@ -17,6 +9,15 @@ LOCALE:
# 如果需要开启仍然可以在语言文件中加入 papi: true
USE_PAPI: false
# 玩家数据储存位置
# 如果服务器存在 TabooLib 的插件版本
# 请设置相同路径
LOCAL-PLAYER: 'plugins/TabooLib/playerdata/'
# 是否以 UUID 的形式创建玩家数据
# 如果服务器存在 TabooLib 的插件版本则不建议开启
LOCAL-PLAYER-UUID: false
# 是否在当前服务器启用交流网终端
# 启用后将会收到大量调试信息, 不建议使用
SERVER: false
@ -26,17 +27,3 @@ TABLIST-SORT: true
# 玩家列表TAB-API是否自动清理没有成员的队伍
TABLIST-AUTO-CLEAN-TEAM: true
# 是否在关闭服务器时清理玩家数据
# 该配置将在启用数据库储存时失效
DELETE-DATA: false
# 是否在服务器关闭时清理无效变量
# 该配置仅在启用数据库储存时有效
# 该方法可能会导致数据丢失?
# 不建议开启
DELETE-VARIABLE: false
# 是否以 UUID 的形式创建玩家数据
# 不建议开启!除非用 TabooLib 储存的插件支持新版储存方式!
ENABLE-UUID: false

View File

@ -2,15 +2,15 @@ package io.izzel.taboolib;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import io.izzel.taboolib.module.locale.TLocaleLoader;
import io.izzel.taboolib.module.command.TCommandHandler;
import io.izzel.taboolib.module.config.TConfig;
import io.izzel.taboolib.module.config.TConfigWatcher;
import io.izzel.taboolib.module.db.IHost;
import io.izzel.taboolib.module.db.local.Local;
import io.izzel.taboolib.module.db.source.DBSource;
import io.izzel.taboolib.module.dependency.TDependencyInjector;
import io.izzel.taboolib.module.inject.TListenerHandler;
import io.izzel.taboolib.module.db.IHost;
import io.izzel.taboolib.module.db.source.HikariHandler;
import io.izzel.taboolib.module.db.yaml.PluginDataManager;
import io.izzel.taboolib.module.locale.TLocaleLoader;
import org.bukkit.plugin.Plugin;
import java.util.List;
@ -59,12 +59,15 @@ public abstract class PluginLoader {
@Override
public void onStopping(Plugin plugin) {
// 保存数据
Local.saveFiles(plugin.getName());
Local.clearFiles(plugin.getName());
// 注销监听器
TListenerHandler.cancelListener(plugin);
// 储存插件数据
PluginDataManager.saveAllCaches(plugin, true);
// 注销插件类
TabooLibLoader.getPluginClassSafely(plugin).forEach(c -> TabooLibLoader.unloadClass(plugin, c));
// 注销数据库连接
Sets.newHashSet(HikariHandler.getDataSource().keySet()).stream().filter(IHost::isAutoClose).forEach(HikariHandler::closeDataSource);
Sets.newHashSet(DBSource.getDataSource().keySet()).stream().filter(IHost::isAutoClose).forEach(DBSource::closeDataSource);
// 释放文检动态读取
Optional.ofNullable(TConfig.getFiles().remove(plugin.getName())).ifPresent(files -> files.forEach(file -> TConfigWatcher.getInst().removeListener(file)));
}

View File

@ -1,21 +1,20 @@
package io.izzel.taboolib;
import io.izzel.taboolib.module.locale.TLocaleLoader;
import io.izzel.taboolib.common.plugin.InternalPlugin;
import io.izzel.taboolib.module.config.TConfig;
import io.izzel.taboolib.module.config.TConfigWatcher;
import io.izzel.taboolib.module.db.local.Local;
import io.izzel.taboolib.module.db.local.LocalPlayer;
import io.izzel.taboolib.module.db.source.DBSource;
import io.izzel.taboolib.module.dependency.Dependency;
import io.izzel.taboolib.module.locale.TLocaleLoader;
import io.izzel.taboolib.module.locale.logger.TLogger;
import io.izzel.taboolib.module.db.source.HikariHandler;
import io.izzel.taboolib.module.nms.NMSHandler;
import io.izzel.taboolib.module.db.yaml.PlayerDataManager;
import io.izzel.taboolib.module.db.yaml.PluginDataManager;
import io.izzel.taboolib.common.plugin.InternalPlugin;
import io.izzel.taboolib.module.nms.NMS;
import io.izzel.taboolib.util.Files;
import io.izzel.taboolib.util.IO;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.util.NumberConversions;
import java.io.File;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;
@ -38,10 +37,6 @@ public class TabooLib {
// 当前运行版本
private static double version;
// 本地数据文件
private File playerDataFolder;
private File serverDataFolder;
// 内部语言文件
private YamlConfiguration internal = new YamlConfiguration();
@ -50,9 +45,6 @@ public class TabooLib {
logger = TLogger.getUnformatted("TabooLib");
// 配置文件从 config.yml 修改为 settings.yml 防止与老版本插件冲突
config = TConfig.create(getPlugin(), "settings.yml");
// 数据文件
playerDataFolder = Files.folder(config.getString("DATAURL.PLAYER-DATA"));
serverDataFolder = Files.folder(config.getString("DATAURL.SERVER-DATA"));
// 加载版本号
try {
version = NumberConversions.toDouble(IO.readFully(Files.getResource("version"), Charset.forName("utf-8")));
@ -69,31 +61,22 @@ public class TabooLib {
TLocaleLoader.load(getPlugin(), false);
// 加载 TabooLib
TabooLibLoader.init();
// 创建 TabooLib 插件数据
PluginDataManager.addPluginData("TabooLib", null);
PluginDataManager.addPluginData("TabooLibrary", null);
// 创建线程检测服务器是否关闭
Executors.newSingleThreadExecutor().submit(() -> {
while (NMSHandler.getHandler().isRunning()) {
while (NMS.getHandler().isRunning()) {
}
// 关闭连接池
HikariHandler.closeDataSourceForce();
// 保存数据
PlayerDataManager.saveAllPlayers(false, true);
PluginDataManager.saveAllCaches();
// 插件关闭
Local.saveFiles();
LocalPlayer.saveFiles();
// 关闭文件监听
TConfigWatcher.getInst().unregisterAll();
// 关闭连接池
DBSource.closeDataSourceForce();
// 关闭插件
PluginLoader.stop(getPlugin());
// 清理数据
if (config.getBoolean("DELETE-DATA")) {
Files.deepDelete(getPlayerDataFolder());
}
});
}
public void cancel() {
TConfigWatcher.getInst().unregisterAll();
}
public static InternalPlugin getPlugin() {
return InternalPlugin.getPlugin();
}
@ -120,14 +103,6 @@ public class TabooLib {
return version;
}
public File getPlayerDataFolder() {
return playerDataFolder;
}
public File getServerDataFolder() {
return serverDataFolder;
}
public YamlConfiguration getInternal() {
return internal;
}

View File

@ -1,7 +1,7 @@
package io.izzel.taboolib;
import io.izzel.taboolib.module.nms.NMSHandler;
import io.izzel.taboolib.module.db.yaml.PluginDataManager;
import io.izzel.taboolib.module.db.local.Local;
import io.izzel.taboolib.module.nms.NMS;
import io.izzel.taboolib.util.Strings;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
@ -42,15 +42,15 @@ public class TabooLibAPI {
}
public static double[] getTPS() {
return NMSHandler.getHandler().getTPS();
return NMS.getHandler().getTPS();
}
public static boolean isDebug() {
return PluginDataManager.getPluginData("TabooLibrary", TabooLib.getPlugin()).getBoolean("debug");
return Local.get().get("data").getBoolean("debug");
}
public static void setDebug(boolean debug) {
PluginDataManager.getPluginData("TabooLibrary", TabooLib.getPlugin()).set("debug", debug);
Local.get().get("data").set("debug", debug);
}
public static void debug(String... args) {

View File

@ -2,12 +2,10 @@ package io.izzel.taboolib;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.izzel.taboolib.module.dependency.TDependencyInjector;
import io.izzel.taboolib.module.inject.TSchedule;
import io.izzel.taboolib.client.TabooLibClient;
import io.izzel.taboolib.client.TabooLibServer;
import io.izzel.taboolib.module.db.yaml.PlayerDataManager;
import io.izzel.taboolib.module.db.yaml.PluginDataManager;
import io.izzel.taboolib.module.dependency.TDependencyInjector;
import io.izzel.taboolib.module.inject.TSchedule;
import io.izzel.taboolib.util.Files;
import io.izzel.taboolib.util.Reflection;
import org.bukkit.Bukkit;
@ -29,12 +27,6 @@ public class TabooLibLoader {
static Map<String, List<Class>> pluginClasses = Maps.newHashMap();
static List<Loader> loaders = Lists.newArrayList();
@TSchedule(period = 20 * 60, async = true)
static void save() {
PluginDataManager.saveAllCaches();
PlayerDataManager.saveAllCaches(true, false);
}
@TSchedule
static void start() {
PluginLoader.active(TabooLib.getPlugin());

View File

@ -2,12 +2,12 @@ package io.izzel.taboolib.common.listener;
import io.izzel.taboolib.TabooLibAPI;
import io.izzel.taboolib.Version;
import io.izzel.taboolib.module.db.local.Local;
import io.izzel.taboolib.module.db.local.LocalPlayer;
import io.izzel.taboolib.module.inject.TListener;
import io.izzel.taboolib.util.item.Items;
import io.izzel.taboolib.module.locale.logger.TLogger;
import io.izzel.taboolib.module.tellraw.TellrawJson;
import io.izzel.taboolib.module.db.yaml.PlayerDataManager;
import io.izzel.taboolib.module.db.yaml.PluginDataManager;
import io.izzel.taboolib.util.item.Items;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
@ -25,8 +25,8 @@ public class ListenerPlayerCommand implements Listener {
if (Version.isAfter(Version.v1_8)) {
e.setCancelled(true);
}
PluginDataManager.saveAllCaches();
PlayerDataManager.saveAllCaches(true, false);
Local.saveFiles();
LocalPlayer.saveFiles();
TLogger.getGlobalLogger().info("Successfully.");
} else if (e.getCommand().equalsIgnoreCase("tDebug")) {
if (Version.isAfter(Version.v1_8)) {
@ -39,9 +39,6 @@ public class ListenerPlayerCommand implements Listener {
TabooLibAPI.setDebug(true);
TLogger.getGlobalLogger().info("&aEnabled.");
}
} else if (e.getCommand().equalsIgnoreCase("tExceptionEvent")) {
e.setCancelled(true);
throw new IllegalStateException("TabooLib Example Exception");
}
}

View File

@ -36,7 +36,6 @@ public class ListenerPlayerJump implements Listener {
} 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.setTo(event.getFrom());

View File

@ -0,0 +1,42 @@
package io.izzel.taboolib.module.db.local;
import com.google.common.collect.Maps;
import com.sun.istack.internal.NotNull;
import io.izzel.taboolib.module.inject.TSchedule;
import io.izzel.taboolib.util.Ref;
import java.util.Map;
import java.util.Optional;
/**
* @Author 坏黑
* @Since 2019-07-06 15:24
*/
public class Local {
private static Map<String, LocalPlugin> plugins = Maps.newConcurrentMap();
@TSchedule(delay = 20 * 30, period = 20 * 30, async = true)
public static void saveFiles() {
plugins.values().forEach(LocalPlugin::saveFiles);
}
public static void saveFiles(String name) {
Optional.ofNullable(plugins.get(name)).ifPresent(LocalPlugin::saveFiles);
}
public static void clearFiles(String name) {
Optional.ofNullable(plugins.remove(name)).ifPresent(LocalPlugin::clearFiles);
}
@NotNull
public static LocalPlugin get(String name) {
return plugins.computeIfAbsent(name, LocalPlugin::new);
}
@NotNull
public static LocalPlugin get() {
Class<?> callerClass = Ref.getCallerClass(3).orElse(null);
return get(callerClass == null ? "TabooLib" : Ref.getCallerPlugin(callerClass).getName());
}
}

View File

@ -0,0 +1,18 @@
package io.izzel.taboolib.module.db.local;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author sky
* @Since 2018-09-14 23:45
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LocalFile {
String value();
}

View File

@ -0,0 +1,41 @@
package io.izzel.taboolib.module.db.local;
import io.izzel.taboolib.TabooLibLoader;
import io.izzel.taboolib.module.locale.logger.TLogger;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* @Author 坏黑
* @Since 2019-07-06 17:35
*/
public class LocalLoader implements TabooLibLoader.Loader {
@Override
public void preLoad(Plugin plugin, Class<?> loadClass) {
for (Field field : loadClass.getDeclaredFields()) {
LocalFile annotation = field.getAnnotation(LocalFile.class);
if (annotation == null) {
continue;
}
Object instance = null;
// 如果是非静态类型
if (!Modifier.isStatic(field.getModifiers())) {
// 是否为主类
if (loadClass.equals(plugin.getClass())) {
instance = plugin;
} else {
TLogger.getGlobalLogger().error(field.getName() + " is not a static field. (" + loadClass.getName() + ")");
continue;
}
}
field.setAccessible(true);
try {
field.set(instance, Local.get(plugin.getName()).get(annotation.value()));
} catch (IllegalAccessException ignored) {
}
}
}
}

View File

@ -0,0 +1,75 @@
package io.izzel.taboolib.module.db.local;
import com.google.common.collect.Maps;
import com.sun.istack.internal.NotNull;
import io.izzel.taboolib.TabooLib;
import io.izzel.taboolib.TabooLibAPI;
import io.izzel.taboolib.module.inject.TSchedule;
import io.izzel.taboolib.util.Files;
import me.skymc.taboolib.database.PlayerDataManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.io.File;
import java.util.Map;
import java.util.UUID;
/**
* @Author 坏黑
* @Since 2019-07-06 17:43
*/
public class LocalPlayer {
private static Map<String, FileConfiguration> files = Maps.newConcurrentMap();
@NotNull
public static FileConfiguration get(OfflinePlayer player) {
return TabooLibAPI.isOriginLoaded() ? PlayerDataManager.getPlayerData(player) : files.computeIfAbsent(toName(player), n -> Files.load(toFile(n)));
}
@TSchedule(delay = 20 * 30, period = 20 * 30, async = true)
public static void saveFiles() {
files.forEach((name, file) -> {
try {
file.save(toFile(name));
} catch (Throwable t) {
t.printStackTrace();
}
});
}
@TSchedule(delay = 20 * 30, period = 20 * 30, async = true)
public static void checkFile() {
files.forEach((name, file) -> {
if (toPlayer(name) == null) {
try {
files.remove(name).save(toFile(name));
} catch (Throwable t) {
t.printStackTrace();
}
}
});
}
public static File getFolder() {
return Files.folder(TabooLib.getConfig().getString("LOCAL-PLAYER"));
}
private static File toFile(String name) {
return Files.file(getFolder(), name + ".yml");
}
private static String toName(OfflinePlayer player) {
return isUniqueIdMode() ? player.getUniqueId().toString() : player.getName();
}
private static boolean isUniqueIdMode() {
return TabooLib.getConfig().getBoolean("LOCAL-PLAYER-UUID");
}
private static Player toPlayer(String name) {
return isUniqueIdMode() ? Bukkit.getPlayer(UUID.fromString(name)) : Bukkit.getPlayerExact(name);
}
}

View File

@ -0,0 +1,77 @@
package io.izzel.taboolib.module.db.local;
import com.google.common.collect.Maps;
import com.sun.istack.internal.NotNull;
import io.izzel.taboolib.util.Files;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import javax.annotation.Nullable;
import java.io.File;
import java.util.Map;
/**
* @Author 坏黑
* @Since 2019-07-06 16:55
*/
public class LocalPlugin {
private String name;
private Map<String, FileConfiguration> files = Maps.newConcurrentMap();
public LocalPlugin(String name) {
this.name = name;
}
@NotNull
public FileConfiguration get(String name) {
return files.computeIfAbsent(fixName(name), n -> Files.load(toFile(n)));
}
@NotNull
public FileConfiguration getFile(String name) {
return files.getOrDefault(fixName(name), new YamlConfiguration());
}
@NotNull
public FileConfiguration addFile(String name) {
FileConfiguration file = Files.load(toFile(name));
files.put(fixName(name), file);
return file;
}
@Nullable
public FileConfiguration clearFile(String name) {
return files.remove(fixName(name));
}
public void clearFiles() {
files.clear();
}
public void saveFiles() {
files.forEach((name, file) -> {
try {
file.save(toFile(name));
} catch (Throwable t) {
t.printStackTrace();
}
});
}
private File toFile(String name) {
return Files.file("plugins/" + this.name + "/" + fixName(name));
}
private String fixName(String name) {
return name.endsWith(".yml") ? name : name + ".yml";
}
public String getName() {
return name;
}
public Map<String, FileConfiguration> getFiles() {
return files;
}
}

View File

@ -17,18 +17,18 @@ import java.util.concurrent.ConcurrentHashMap;
* @Author sky
* @Since 2018-05-16 21:59
*/
public class HikariHandler {
public class DBSource {
@TInject("datasource.yml")
private static TConfig settings;
private static ConcurrentHashMap<IHost, MapDataSource> dataSource = new ConcurrentHashMap<>();
private static ConcurrentHashMap<IHost, DBSourceData> dataSource = new ConcurrentHashMap<>();
public static DataSource createDataSource(IHost host) {
return createDataSource(host, null);
public static DataSource create(IHost host) {
return create(host, null);
}
public static HikariDataSource createDataSource(IHost host, HikariConfig hikariConfig) {
MapDataSource mapDataSource = dataSource.computeIfAbsent(host, x -> new MapDataSource(x, new HikariDataSource(hikariConfig == null ? createConfig(host) : hikariConfig)));
public static DataSource create(IHost host, HikariConfig hikariConfig) {
DBSourceData mapDataSource = dataSource.computeIfAbsent(host, x -> new DBSourceData(x, new HikariDataSource(hikariConfig == null ? createConfig(host) : hikariConfig)));
mapDataSource.getActivePlugin().getAndIncrement();
if (mapDataSource.getActivePlugin().get() == 1) {
TLocale.Logger.info("MYSQL-HIKARI.CREATE-SUCCESS", host.getPlugin().getName(), host.getConnectionUrlSimple());
@ -44,7 +44,7 @@ public class HikariHandler {
public static void closeDataSource(IHost host) {
if (host != null && dataSource.containsKey(host)) {
MapDataSource mapDataSource = dataSource.get(host);
DBSourceData mapDataSource = dataSource.get(host);
if (mapDataSource.getActivePlugin().getAndDecrement() <= 1) {
mapDataSource.getHikariDataSource().close();
dataSource.remove(host);
@ -89,7 +89,7 @@ public class HikariHandler {
//
// *********************************
public static ConcurrentHashMap<IHost, MapDataSource> getDataSource() {
public static ConcurrentHashMap<IHost, DBSourceData> getDataSource() {
return dataSource;
}

View File

@ -9,13 +9,13 @@ import java.util.concurrent.atomic.AtomicInteger;
* @Author sky
* @Since 2018-05-17 23:47
*/
public class MapDataSource {
public class DBSourceData {
private IHost host;
private AtomicInteger activePlugin;
private HikariDataSource hikariDataSource;
MapDataSource(IHost host, HikariDataSource hikariDataSource) {
DBSourceData(IHost host, HikariDataSource hikariDataSource) {
this.host = host;
this.activePlugin = new AtomicInteger();
this.hikariDataSource = hikariDataSource;

View File

@ -1,95 +0,0 @@
package io.izzel.taboolib.module.db.yaml;
import io.izzel.taboolib.TabooLib;
import io.izzel.taboolib.module.inject.TListener;
import io.izzel.taboolib.common.event.PlayerLoadedEvent;
import io.izzel.taboolib.util.Files;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.io.File;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@TListener
public class PlayerDataManager implements Listener {
private static final ConcurrentHashMap<String, FileConfiguration> PLAYER_DATA = new ConcurrentHashMap<>();
public static UsernameType getUsernameType() {
return TabooLib.getConfig().getBoolean("ENABLE-UUID") ? UsernameType.UUID : UsernameType.USERNAME;
}
public static FileConfiguration getPlayerData(Player player) {
return getUsernameType() == UsernameType.UUID ? loadPlayerData(player.getUniqueId().toString()) : loadPlayerData(player.getName());
}
public static FileConfiguration loadPlayerData(String username) {
return PLAYER_DATA.computeIfAbsent(username, n -> YamlConfiguration.loadConfiguration(Files.file(TabooLib.getInst().getPlayerDataFolder(), username + ".yml")));
}
public static void savePlayerData(String username, boolean remove) {
// 没有数据
if (!PLAYER_DATA.containsKey(username)) {
return;
}
// 读取文件
File file = Files.file(TabooLib.getInst().getPlayerDataFolder(), username + ".yml");
// 保存配置
try {
PLAYER_DATA.get(username).save(file);
} catch (Throwable t) {
t.printStackTrace();
}
// 获取玩家
Player player = getUsernameType() == UsernameType.UUID ? Bukkit.getPlayer(UUID.fromString(username)) : Bukkit.getPlayerExact(username);
// 移除数据
if (remove || player == null) {
PLAYER_DATA.remove(username);
}
}
public static void saveAllCaches(boolean sync, boolean remove) {
if (sync) {
Bukkit.getScheduler().runTaskAsynchronously(TabooLib.getPlugin(), () -> PLAYER_DATA.keySet().forEach(name -> savePlayerData(name, false)));
} else {
PLAYER_DATA.keySet().forEach(name -> savePlayerData(name, false));
}
}
public static void saveAllPlayers(boolean sync, boolean remove) {
if (sync) {
Bukkit.getScheduler().runTaskAsynchronously(TabooLib.getPlugin(), () -> Bukkit.getOnlinePlayers().forEach(player -> savePlayerData(TabooLib.getConfig().getBoolean("ENABLE-UUID") ? player.getUniqueId().toString() : player.getName(), remove)));
} else {
Bukkit.getOnlinePlayers().forEach(player -> savePlayerData(TabooLib.getConfig().getBoolean("ENABLE-UUID") ? player.getUniqueId().toString() : player.getName(), remove));
}
}
@EventHandler
public void join(PlayerJoinEvent e) {
Bukkit.getScheduler().runTaskAsynchronously(TabooLib.getPlugin(), () -> {
// 载入数据
loadPlayerData(TabooLib.getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName());
// 载入完成
Bukkit.getPluginManager().callEvent(new PlayerLoadedEvent(e.getPlayer()));
});
}
@EventHandler
public void quit(PlayerQuitEvent e) {
Bukkit.getScheduler().runTaskAsynchronously(TabooLib.getPlugin(), () -> {
// 保存数据
savePlayerData(TabooLib.getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName(), true);
});
}
public enum UsernameType {
UUID, USERNAME
}
}

View File

@ -1,83 +0,0 @@
package io.izzel.taboolib.module.db.yaml;
import io.izzel.taboolib.TabooLib;
import io.izzel.taboolib.module.locale.TLocale;
import io.izzel.taboolib.util.Files;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
public class PluginDataManager {
public static final ConcurrentHashMap<String, HashMap<String, FileConfiguration>> 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), Files.file(getDataSaveFolder(plugin), fileName));
}
if (remove) {
CACHE_DATA_PLUGIN.remove(plugin.getName());
}
}
public static void saveAllCaches() {
saveAllCaches(false);
}
public static void saveAllCaches(boolean remove) {
CACHE_DATA_PLUGIN.keySet().forEach(plugin -> saveAllCaches(getFixedPlugin(plugin), remove));
}
public static void saveConfiguration(FileConfiguration conf, File file) {
try {
conf.save(file);
} catch (IOException e) {
TLocale.Logger.error("DATA-UTILS.FAIL-SAVE-FILE", file.getName(), e.toString());
}
}
public static String getFixedFileName(String name) {
return name.contains(".") ? name : name + ".yml";
}
public static Plugin getFixedPlugin(String pluginName) {
return Bukkit.getPluginManager().getPlugin(pluginName) == null ? TabooLib.getPlugin() : Bukkit.getPluginManager().getPlugin(pluginName);
}
public static File getDataSaveFolder(Plugin plugin) {
return plugin == null || plugin.getName().equals("TabooLib") ? TabooLib.getInst().getServerDataFolder() : plugin.getDataFolder();
}
public static String getDataSaveKey(Plugin plugin) {
return plugin == null ? "TabooLib" : plugin.getName();
}
public static FileConfiguration addPluginData(String name, Plugin plugin) {
return setPluginData(getFixedFileName(name), plugin, YamlConfiguration.loadConfiguration(Files.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;
}
}

View File

@ -103,7 +103,7 @@ public class TInjectLoader implements TabooLibLoader.Loader {
if (pluginClass.equals(plugin.getClass())) {
instance = plugin;
} else {
TLogger.getGlobalLogger().error(declaredField.getName() + " is not a static field. (" + declaredField.getType().getName() + ")");
TLogger.getGlobalLogger().error(declaredField.getName() + " is not a static field. (" + pluginClass.getName() + ")");
continue;
}
}
@ -125,7 +125,7 @@ public class TInjectLoader implements TabooLibLoader.Loader {
if (pluginClass.equals(plugin.getClass())) {
instance = plugin;
} else {
TLogger.getGlobalLogger().error(declaredField.getName() + " is not a static field. (" + declaredField.getType().getName() + ")");
TLogger.getGlobalLogger().error(declaredField.getName() + " is not a static field. (" + pluginClass.getName() + ")");
continue;
}
}
@ -133,7 +133,7 @@ public class TInjectLoader implements TabooLibLoader.Loader {
if (tInjectTask != null) {
inject(plugin, declaredField, instance, annotation, tInjectTask);
} else {
TLogger.getGlobalLogger().error(declaredField.getName() + " is an invalid inject type. (" + declaredField.getType().getName() + ")");
TLogger.getGlobalLogger().error(declaredField.getName() + " is an invalid inject type. (" + pluginClass.getName() + ")");
}
}
}

View File

@ -4,7 +4,7 @@ import io.izzel.taboolib.TabooLib;
import io.izzel.taboolib.Version;
import io.izzel.taboolib.module.locale.TLocaleLoader;
import io.izzel.taboolib.module.inject.TFunction;
import io.izzel.taboolib.module.nms.NMSHandler;
import io.izzel.taboolib.module.nms.NMS;
import io.izzel.taboolib.module.nms.nbt.NBTCompound;
import io.izzel.taboolib.util.Files;
import org.bukkit.configuration.file.FileConfiguration;
@ -34,7 +34,7 @@ public class SimpleI18n {
if (localeFile == null) {
lang = new YamlConfiguration();
} else {
lang = Files.load(TabooLib.getPlugin(), localeFile);
lang = Files.load(localeFile);
}
if (lang.getInt("version") < 3 && !released) {
released = true;
@ -56,7 +56,7 @@ public class SimpleI18n {
}
public static String getName(Entity entity) {
return entity == null ? "-" : lang.getString(NMSHandler.getHandler().getName(entity).replace(".", "_"), entity.getName());
return entity == null ? "-" : lang.getString(NMS.getHandler().getName(entity).replace(".", "_"), entity.getName());
}
public static String getName(ItemStack item) {
@ -69,7 +69,7 @@ public class SimpleI18n {
}
if (!Version.isAfter(Version.v1_11)) {
if (item.getType().name().equals("MONSTER_EGG")) {
NBTCompound nbtCompound = NMSHandler.getHandler().loadNBT(item);
NBTCompound nbtCompound = NMS.getHandler().loadNBT(item);
if (nbtCompound.containsKey("EntityTag")) {
return lang.getString("item_monsterPlacer_name") + " " + lang.getString("entity_" + nbtCompound.get("EntityTag").asCompound().get("id").asString() + "_name");
}
@ -79,11 +79,11 @@ public class SimpleI18n {
if (itemMeta instanceof SpawnEggMeta) {
String spawnEggType = lang.getString("entity_" + ((SpawnEggMeta) itemMeta).getSpawnedType().getEntityClass().getSimpleName().replace(".", "_") + "_name");
if (spawnEggType != null) {
return lang.getString(NMSHandler.getHandler().getName(item).replace(".", "_"), item.getType().name().toLowerCase().replace("_", "")) + " " + spawnEggType;
return lang.getString(NMS.getHandler().getName(item).replace(".", "_"), item.getType().name().toLowerCase().replace("_", "")) + " " + spawnEggType;
}
}
}
return lang.getString(NMSHandler.getHandler().getName(item).replace(".", "_"), item.getType().name().toLowerCase().replace("_", ""));
return lang.getString(NMS.getHandler().getName(item).replace(".", "_"), item.getType().name().toLowerCase().replace("_", ""));
}
private static void releaseLocales(Plugin plugin) {

View File

@ -2,7 +2,7 @@ package io.izzel.taboolib.module.locale;
import io.izzel.taboolib.TabooLib;
import io.izzel.taboolib.module.locale.logger.TLoggerManager;
import io.izzel.taboolib.module.nms.NMSHandler;
import io.izzel.taboolib.module.nms.NMS;
import io.izzel.taboolib.module.tellraw.TellrawCreator;
import io.izzel.taboolib.util.Ref;
import io.izzel.taboolib.util.Strings;
@ -96,11 +96,11 @@ public class TLocale {
}
public static void sendTitle(Player player, String title, String subTitle, int fadein, int stay, int fadeout) {
NMSHandler.getHandler().sendTitle(player, title, fadein, stay, fadeout, subTitle, fadein, stay, fadeout);
NMS.getHandler().sendTitle(player, title, fadein, stay, fadeout, subTitle, fadein, stay, fadeout);
}
public static void sendActionBar(Player player, String text) {
NMSHandler.getHandler().sendActionBar(player, text);
NMS.getHandler().sendActionBar(player, text);
}
}

View File

@ -74,13 +74,13 @@ public class TLocaleLoader {
return;
}
// 加载文件
YamlConfiguration localeConfiguration = Files.loadYaml(plugin, localeFile);
YamlConfiguration localeConfiguration = Files.loadYaml(localeFile);
YamlConfiguration localeConfigurationAtStream = getLocaleAtStream(plugin, localeFile);
// 载入配置
loadPluginLocale(plugin, localeFile, localeConfiguration, localeConfigurationAtStream);
// 注册监听
TConfigWatcher.getInst().removeListener(localeFile);
TConfigWatcher.getInst().addListener(localeFile, null, obj -> loadPluginLocale(plugin, localeFile, Files.loadYaml(plugin, localeFile), getLocaleAtStream(plugin, localeFile)));
TConfigWatcher.getInst().addListener(localeFile, null, obj -> loadPluginLocale(plugin, localeFile, Files.loadYaml(localeFile), getLocaleAtStream(plugin, localeFile)));
}
} catch (Exception e) {
errorLogger("ERROR-LOADING-LANG", plugin.getName(), e.toString() + "\n" + e.getStackTrace()[0].toString());

View File

@ -13,17 +13,17 @@ import org.bukkit.inventory.ItemStack;
* @Since 2018-11-09 14:38
*/
@TFunction(enable = "init")
public abstract class NMSHandler {
public abstract class NMS {
private static NMSHandler handler;
private static NMS handler;
public static NMSHandler getHandler() {
public static NMS getHandler() {
return handler;
}
static void init() {
try {
handler = (NMSHandler) SimpleVersionControl.createNMS("io.izzel.taboolib.module.nms.NMSHandlerImpl").translate().newInstance();
handler = (NMS) SimpleVersionControl.createNMS("io.izzel.taboolib.module.nms.NMSHandlerImpl").translate().newInstance();
} catch (Exception e) {
e.printStackTrace();
}

View File

@ -31,7 +31,7 @@ import java.util.Map;
* @Author 坏黑
* @Since 2018-11-09 14:42
*/
public class NMSHandlerImpl extends NMSHandler {
public class NMSImpl extends NMS {
private Field entityTypesField;
@ -49,7 +49,7 @@ public class NMSHandlerImpl extends NMSHandler {
SimpleReflection.saveField(NBTTagCompound.class);
}
public NMSHandlerImpl() {
public NMSImpl() {
if (Version.isAfter(Version.v1_13)) {
SimpleReflection.saveField(net.minecraft.server.v1_12_R1.Entity.class);
for (Field declaredField : SimpleReflection.getFields(net.minecraft.server.v1_12_R1.Entity.class).values()) {

View File

@ -1,10 +1,7 @@
package io.izzel.taboolib.util;
import io.izzel.taboolib.TabooLib;
import io.izzel.taboolib.module.locale.TLocale;
import io.izzel.taboolib.common.plugin.InternalPlugin;
import io.izzel.taboolib.util.eagletdl.EagletTask;
import io.izzel.taboolib.util.eagletdl.ProgressEvent;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
@ -238,44 +235,19 @@ public class Files {
return null;
}
public static void download(String url, File file) {
download(url, file, false);
}
public static void download(String url, File file, boolean async) {
EagletTask eagletTask = new EagletTask()
.url(url)
.file(file)
.setThreads(8)
.setOnError(event -> {
})
.setOnConnected(event -> TLocale.Logger.info("UTIL.DOWNLOAD-CONNECTED", file.getName(), ProgressEvent.format(event.getContentLength())))
.setOnProgress(event -> TLocale.Logger.info("UTIL.DOWNLOAD-PROGRESS", event.getSpeedFormatted(), event.getPercentageFormatted()))
.setOnComplete(event -> {
if (event.isSuccess()) {
TLocale.Logger.info("UTIL.DOWNLOAD-SUCCESS", file.getName());
} else {
TLocale.Logger.error("UTIL.DOWNLOAD-FAILED", file.getName());
}
}).start();
if (!async) {
eagletTask.waitUntil();
}
public static String encodeYAML(FileConfiguration file) {
return Base64Coder.encodeLines(file.saveToString().getBytes()).replaceAll("\\s+", "");
}
public static FileConfiguration decodeYAML(String args) {
return YamlConfiguration.loadConfiguration(new StringReader(Base64Coder.decodeString(args)));
}
public static String encodeYAML(FileConfiguration file) {
return Base64Coder.encodeLines(file.saveToString().getBytes()).replaceAll("\\s+", "");
public static FileConfiguration load(File file) {
return loadYaml(file);
}
public static FileConfiguration load(Plugin plugin, File file) {
return loadYaml(plugin, file);
}
public static YamlConfiguration loadYaml(Plugin plugin, File file) {
public static YamlConfiguration loadYaml( File file) {
YamlConfiguration configuration = new YamlConfiguration();
try {
String yaml = com.google.common.io.Files.toString(file, Charset.forName("utf-8"));

View File

@ -3,7 +3,7 @@ package io.izzel.taboolib.util.item;
import io.izzel.taboolib.Version;
import io.izzel.taboolib.module.locale.TLocale;
import io.izzel.taboolib.module.lite.SimpleI18n;
import io.izzel.taboolib.module.nms.NMSHandler;
import io.izzel.taboolib.module.nms.NMS;
import io.izzel.taboolib.module.nms.nbt.NBTBase;
import io.izzel.taboolib.module.nms.nbt.NBTCompound;
import io.izzel.taboolib.module.nms.nbt.NBTList;
@ -232,7 +232,7 @@ public class Items {
// 元数据
item.setItemMeta(meta);
// 数据
NBTCompound nbt = NMSHandler.getHandler().loadNBT(item);
NBTCompound nbt = NMS.getHandler().loadNBT(item);
// 物品标签
if (section.contains("nbt")) {
for (String name : section.getConfigurationSection("nbt").getKeys(false)) {
@ -281,6 +281,6 @@ public class Items {
}
nbt.put("AttributeModifiers", attr);
}
return NMSHandler.getHandler().saveNBT(item, nbt);
return NMS.getHandler().saveNBT(item, nbt);
}
}

View File

@ -1,7 +1,7 @@
package io.izzel.taboolib.util.lite;
import io.izzel.taboolib.Version;
import io.izzel.taboolib.module.nms.NMSHandler;
import io.izzel.taboolib.module.nms.NMS;
import io.izzel.taboolib.module.packet.TPacketHandler;
import io.izzel.taboolib.util.Reflection;
import org.bukkit.Bukkit;
@ -843,7 +843,7 @@ public enum Particles {
data = getDustColor((OrdinaryColor) data, size);
}
}
this.packet = NMSHandler.getHandler().toPacketPlayOutWorldParticles(effect.getBukkitParticle(), longDistance, (float) center.getX(), (float) center.getY(), (float) center.getZ(), offsetX, offsetY, offsetZ, speed, amount, data);
this.packet = NMS.getHandler().toPacketPlayOutWorldParticles(effect.getBukkitParticle(), longDistance, (float) center.getX(), (float) center.getY(), (float) center.getZ(), offsetX, offsetY, offsetZ, speed, amount, data);
} catch (Throwable exception) {
throw new PacketInstantiationException("Packet instantiation failed", exception);
}

View File

@ -23,14 +23,14 @@ public class TSerializer {
private static Map<String, TSerializerElement> generated = Maps.newHashMap();
public static TSerializable read(TSerializable serializable, String serializedString) {
SimpleReflection.checkAndSave(serializable.getClass());
try {
JsonObject jsonObject = (JsonObject) new JsonParser().parse(serializedString);
if (jsonObject.has("serializeObject")) {
JsonObject serializeObject = jsonObject.getAsJsonObject("serializeObject");
for (Map.Entry<String, JsonElement> jsonElementEntry : serializeObject.entrySet()) {
try {
Field declaredField = SimpleReflection.getField(serializable.getClass(), jsonElementEntry.getKey());
Field declaredField = serializable.getClass().getDeclaredField(jsonElementEntry.getKey());
declaredField.setAccessible(true);
if (declaredField.isAnnotationPresent(DoNotSerialize.class)) {
continue;
}
@ -91,7 +91,8 @@ public class TSerializer {
SimpleReflection.checkAndSave(serializable.getClass());
JsonObject jsonObject = new JsonObject();
JsonObject serializeObject = new JsonObject();
for (Field declaredField : SimpleReflection.getFields(serializable.getClass()).values()) {
for (Field declaredField : serializable.getClass().getDeclaredFields()) {
declaredField.setAccessible(true);
try {
if (!declaredField.isAnnotationPresent(DoNotSerialize.class) && !Modifier.isStatic(declaredField.getModifiers())) {
Object fieldObject = declaredField.get(serializable);