From a34c655315edce7c91295f8d7c49f9e7e2955f10 Mon Sep 17 00:00:00 2001 From: nulli0n Date: Thu, 31 Oct 2024 21:39:29 +0500 Subject: [PATCH] v2.7.0-beta --- pom.xml | 29 +- .../su/nightexpress/nightcore/NightCore.java | 104 ++---- .../nightcore/NightCorePlugin.java | 5 +- .../nightcore/NightDataPlugin.java | 1 + .../nightexpress/nightcore/NightPlugin.java | 105 +++--- .../nightcore/command/CommandManager.java | 4 + .../experimental/argument/ArgumentTypes.java | 73 ++-- .../experimental/impl/ReloadCommand.java | 12 +- .../command/impl/WrappedCommand.java | 1 + .../nightcore/config/ConfigValue.java | 83 ++++- .../nightcore/config/FileConfig.java | 9 +- .../nightcore/config/PluginDetails.java | 3 + .../nightcore/config/Writeable.java | 8 + .../nightcore/core/CoreConfig.java | 96 ++--- .../nightexpress/nightcore/core/CoreLang.java | 18 +- .../nightcore/core/CoreManager.java | 28 +- ...heckPermCommand.java => CoreCommands.java} | 30 +- .../nightcore/core/listener/CoreListener.java | 4 +- .../nightcore/database/AbstractConnector.java | 1 + .../database/AbstractDataHandler.java | 11 +- .../nightcore/database/AbstractUser.java | 1 + .../database/AbstractUserDataHandler.java | 5 +- .../database/AbstractUserManager.java | 15 +- .../nightcore/database/DataUser.java | 1 + .../nightcore/database/DatabaseConfig.java | 4 +- .../nightcore/database/DatabaseType.java | 1 + .../nightcore/database/UserdataConfig.java | 58 +-- .../database/connection/MySQLConnector.java | 1 + .../database/connection/SQLiteConnector.java | 1 + .../database/listener/UserListener.java | 8 +- .../serialize/ItemStackSerializer.java | 1 + .../nightcore/database/sql/SQLColumn.java | 8 + .../nightcore/database/sql/SQLCondition.java | 1 + .../nightcore/database/sql/SQLExecutor.java | 1 + .../nightcore/database/sql/SQLQueries.java | 1 + .../nightcore/database/sql/SQLUtils.java | 12 + .../nightcore/database/sql/SQLValue.java | 1 + .../database/sql/column/ColumnFormer.java | 1 + .../database/sql/column/ColumnType.java | 1 + .../sql/executor/AlterTableExecutor.java | 1 + .../sql/executor/CreateTableExecutor.java | 1 + .../sql/executor/DeleteQueryExecutor.java | 1 + .../sql/executor/InsertQueryExecutor.java | 1 + .../sql/executor/RenameTableExecutor.java | 1 + .../sql/executor/SelectQueryExecutor.java | 1 + .../database/sql/query/AbstractQuery.java | 25 -- .../database/sql/query/UpdateEntity.java | 1 + .../database/sql/query/UpdateQuery.java | 45 +-- .../nightcore/db/AbstractDataManager.java | 217 ++++++++++++ .../nightcore/db/AbstractUser.java | 147 ++++++++ .../nightcore/db/AbstractUserDataManager.java | 161 +++++++++ .../nightcore/db/AbstractUserManager.java | 332 ++++++++++++++++++ .../nightcore/db/config/DatabaseConfig.java | 187 ++++++++++ .../nightcore/db/config/DatabaseType.java | 7 + .../nightcore/db/config/UserdataConfig.java | 112 ++++++ .../db/connection/AbstractConnector.java | 50 +++ .../db/connection/impl/MySQLConnector.java | 28 ++ .../db/connection/impl/SQLiteConnector.java | 24 ++ .../nightcore/db/listener/UserListener.java | 50 +++ .../nightcore/db/sql/column/Column.java | 57 +++ .../nightcore/db/sql/column/ColumnType.java | 35 ++ .../nightcore/db/sql/query/QueryValue.java | 31 ++ .../nightcore/db/sql/query/SQLQueries.java | 200 +++++++++++ .../nightcore/db/sql/query/UserQueries.java | 42 +++ .../db/sql/query/impl/DeleteQuery.java | 46 +++ .../db/sql/query/impl/InsertQuery.java | 62 ++++ .../db/sql/query/impl/SelectQuery.java | 99 ++++++ .../db/sql/query/impl/UpdateQuery.java | 77 ++++ .../db/sql/query/type/AbstractQuery.java | 22 ++ .../db/sql/query/type/ConditionalQuery.java | 49 +++ .../db/sql/query/type/ValuedQuery.java | 11 + .../nightcore/db/sql/util/SQLUtils.java | 25 ++ .../nightcore/db/sql/util/WhereOperator.java | 24 ++ .../nightcore/dialog/DialogListener.java | 2 +- .../nightcore/dialog/WrappedInput.java | 6 +- .../nightcore/integration/VaultHook.java | 51 ++- .../nightcore/language/LangAssets.java | 7 +- .../nightcore/language/LangManager.java | 4 +- .../nightcore/language/entry/LangEntry.java | 6 +- .../nightcore/language/entry/LangItem.java | 8 +- .../nightcore/language/entry/LangString.java | 7 +- .../nightcore/language/entry/LangText.java | 7 +- .../language/message/LangMessage.java | 55 ++- .../language/tag/impl/OutputTag.java | 4 +- .../nightcore/manager/AbstractManager.java | 30 +- .../nightcore/menu/MenuViewer.java | 6 +- .../nightcore/menu/impl/ConfigMenu.java | 3 +- .../nightcore/menu/item/ItemOptions.java | 4 +- .../nightcore/util/BukkitThing.java | 20 +- .../nightcore/util/CommandUtil.java | 1 + .../nightcore/util/EntityUtil.java | 9 +- .../nightexpress/nightcore/util/ItemNbt.java | 19 +- .../nightcore/util/ItemReplacer.java | 134 ++++--- .../nightexpress/nightcore/util/ItemUtil.java | 103 +----- .../su/nightexpress/nightcore/util/Lists.java | 6 +- .../nightcore/util/LocationUtil.java | 6 +- .../nightcore/util/NumberUtil.java | 199 +++++++++-- .../su/nightexpress/nightcore/util/Pair.java | 1 + .../nightcore/util/Placeholders.java | 71 +++- .../nightexpress/nightcore/util/Players.java | 133 +++---- .../nightexpress/nightcore/util/Plugins.java | 38 +- .../nightexpress/nightcore/util/RankMap.java | 61 ++-- .../nightcore/util/StringUtil.java | 107 ++++-- .../nightexpress/nightcore/util/TimeUtil.java | 26 +- .../nightcore/util/TriFunction.java | 1 + .../nightexpress/nightcore/util/Version.java | 84 ++++- .../util/blocktracker/PlayerBlockTracker.java | 2 +- .../nightcore/util/bukkit/NightSound.java | 124 +++++++ .../nightcore/util/bukkit/NightTask.java | 67 ++++ .../nightcore/util/number/CompactNumber.java | 33 ++ .../nightcore/util/number/NumberShortcut.java | 52 +++ .../util/placeholder/Placeholder.java | 1 + .../util/placeholder/PlaceholderEntry.java | 31 ++ .../util/placeholder/PlaceholderList.java | 69 ++++ .../util/placeholder/PlaceholderMap.java | 1 + .../nightcore/util/placeholder/Replacer.java | 95 +++++ .../nightcore/util/random/Rnd.java | 34 +- .../nightcore/util/random/WeightedItem.java | 28 ++ .../nightcore/util/rankmap/DoubleRankMap.java | 38 ++ .../nightcore/util/rankmap/IntRankMap.java | 38 ++ .../nightcore/util/rankmap/LongRankMap.java | 38 ++ .../nightcore/util/rankmap/RankMap.java | 166 +++++++++ .../nightcore/util/regex/TimedMatcher.java | 6 +- .../nightcore/util/text/TextRoot.java | 1 + .../nightcore/util/text/tag/TagUtils.java | 31 ++ .../nightcore/util/text/tag/Tags.java | 30 ++ .../util/text/tag/api/ContentTag.java | 3 +- .../util/text/tag/impl/ColorTag.java | 10 +- .../util/text/tag/impl/GradientTag.java | 19 +- .../util/text/tag/impl/HexColorTag.java | 18 +- .../util/text/tag/impl/ShortHexColorTag.java | 18 +- .../util/version/VersionComponent.java | 6 + .../nightcore/util/wrapper/UniSound.java | 1 + .../nightcore/util/wrapper/UniTask.java | 17 +- src/main/resources/plugin.yml | 6 +- 135 files changed, 4305 insertions(+), 816 deletions(-) create mode 100644 src/main/java/su/nightexpress/nightcore/config/Writeable.java rename src/main/java/su/nightexpress/nightcore/core/command/{CheckPermCommand.java => CoreCommands.java} (66%) delete mode 100644 src/main/java/su/nightexpress/nightcore/database/sql/query/AbstractQuery.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/AbstractDataManager.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/AbstractUser.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/AbstractUserDataManager.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/AbstractUserManager.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/config/DatabaseConfig.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/config/DatabaseType.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/config/UserdataConfig.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/connection/AbstractConnector.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/connection/impl/MySQLConnector.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/connection/impl/SQLiteConnector.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/listener/UserListener.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/column/Column.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/column/ColumnType.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/query/QueryValue.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/query/SQLQueries.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/query/UserQueries.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/query/impl/DeleteQuery.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/query/impl/InsertQuery.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/query/impl/SelectQuery.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/query/impl/UpdateQuery.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/query/type/AbstractQuery.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/query/type/ConditionalQuery.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/query/type/ValuedQuery.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/util/SQLUtils.java create mode 100644 src/main/java/su/nightexpress/nightcore/db/sql/util/WhereOperator.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/bukkit/NightSound.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/bukkit/NightTask.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/number/CompactNumber.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/number/NumberShortcut.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderEntry.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderList.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/placeholder/Replacer.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/random/WeightedItem.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/rankmap/DoubleRankMap.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/rankmap/IntRankMap.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/rankmap/LongRankMap.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/rankmap/RankMap.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/text/tag/TagUtils.java create mode 100644 src/main/java/su/nightexpress/nightcore/util/version/VersionComponent.java diff --git a/pom.xml b/pom.xml index 368cb95..c5296ae 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ su.nightexpress.nightcore nightcore - 2.6.4 + 2.7.0 17 @@ -20,17 +20,9 @@ https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - placeholderapi https://repo.extendedclip.com/content/repositories/placeholderapi/ - - false - @@ -66,25 +58,12 @@ org.openjdk.jmh jmh-generator-annprocess 1.21 - - - - io.papermc.paper - paper-api - 1.20.2-R0.1-SNAPSHOT - provided --> com.zaxxer HikariCP - 5.0.1 - - - - com.mojang - authlib - 5.0.47 + 6.0.0 @@ -96,7 +75,7 @@ org.xerial sqlite-jdbc - 3.41.2.2 + 3.46.1.3 @@ -115,7 +94,7 @@ me.clip placeholderapi - 2.11.2 + 2.11.6 provided diff --git a/src/main/java/su/nightexpress/nightcore/NightCore.java b/src/main/java/su/nightexpress/nightcore/NightCore.java index 58e1e1c..c0fb148 100644 --- a/src/main/java/su/nightexpress/nightcore/NightCore.java +++ b/src/main/java/su/nightexpress/nightcore/NightCore.java @@ -1,50 +1,53 @@ package su.nightexpress.nightcore; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.command.experimental.ImprovedCommands; -import su.nightexpress.nightcore.command.experimental.impl.ReloadCommand; -import su.nightexpress.nightcore.command.experimental.node.ChainedNode; import su.nightexpress.nightcore.config.PluginDetails; import su.nightexpress.nightcore.core.CoreConfig; import su.nightexpress.nightcore.core.CoreLang; import su.nightexpress.nightcore.core.CoreManager; import su.nightexpress.nightcore.core.CorePerms; -import su.nightexpress.nightcore.core.command.CheckPermCommand; +import su.nightexpress.nightcore.core.command.CoreCommands; import su.nightexpress.nightcore.dialog.Dialog; import su.nightexpress.nightcore.integration.VaultHook; import su.nightexpress.nightcore.language.LangAssets; -import su.nightexpress.nightcore.util.*; +import su.nightexpress.nightcore.util.Plugins; +import su.nightexpress.nightcore.util.Version; import su.nightexpress.nightcore.util.blocktracker.PlayerBlockTracker; +import su.nightexpress.nightcore.util.text.tag.Tags; import java.util.HashSet; import java.util.Set; public class NightCore extends NightPlugin implements ImprovedCommands { - private final Set childrens; - private final CoreManager coreManager; + private final Set childrens; + private final CoreManager coreManager; public NightCore() { + Plugins.load(this); + Version.load(this); + this.childrens = new HashSet<>(); this.coreManager = new CoreManager(this); } + @Override + @NotNull + protected PluginDetails getDefaultDetails() { + return PluginDetails.create("nightcore", new String[]{"nightcore", "ncore"}) + .setConfigClass(CoreConfig.class) + .setLangClass(CoreLang.class) + .setPermissionsClass(CorePerms.class); + } + @Override public void enable() { - LangAssets.load(); + Tags.loadColorsFromFile(this); + LangAssets.load(this); + this.loadIntegrations(); + this.loadCommands(); - ChainedNode rootNode = this.getRootNode(); - - if (Plugins.hasVault()) { - VaultHook.setup(); - CheckPermCommand.inject(this, rootNode); - } - ReloadCommand.inject(this, rootNode, CorePerms.COMMAND_RELOAD); - - this.testMethods(); this.coreManager.setup(); } @@ -60,64 +63,25 @@ public class NightCore extends NightPlugin implements ImprovedCommands { LangAssets.shutdown(); } - @Override - @NotNull - protected PluginDetails getDefaultDetails() { - return PluginDetails.create("nightcore", new String[]{"nightcore", "ncore"}) - .setConfigClass(CoreConfig.class) - .setLangClass(CoreLang.class) - .setPermissionsClass(CorePerms.class); + private void loadCommands() { + CoreCommands.load(this); } - void addChildren(@NotNull NightCorePlugin child) { + private void loadIntegrations() { + Plugins.detectPlugins(); + + if (Plugins.hasVault()) { + VaultHook.load(this); + } + } + + void addChildren(@NotNull NightPlugin child) { this.childrens.add(child); child.info("Powered by " + this.getName()); } @NotNull - public Set getChildrens() { + public Set getChildrens() { return new HashSet<>(this.childrens); } - - private void testMethods() { - if (Version.getCurrent() == Version.UNKNOWN) { - this.warn("Server Version: UNSUPPORTED ✘"); - } - else this.info("Server Version: " + Version.getCurrent().getLocalized() + " ✔"); - - if (EntityUtil.setupEntityCounter(this)) { - this.info("Entity Id Counter: OK ✔"); - } - else this.error("Entity Id Counter: FAIL ✘"); - - if (this.testItemNbt()) { - this.info("Item NBT Compress: OK ✔"); - } - else this.error("Item NBT Compress: FAIL ✘"); - - if (Version.isAtLeast(Version.MC_1_20_6) && CoreConfig.DATA_FIXER_ENABLED.get()) { - this.warn("=".repeat(10) + " WARNING " + "=".repeat(10)); - this.warn("Enabled Mojang's DataFixer for ItemStacks to update/fix NBT structure from <= 1.20.4 to 1.20.6+"); - this.warn("This may significally affect server's performance."); - this.warn("Please, re-save all configuration(s) using in-game GUI editor(s) (if there is any)."); - this.warn("Then disable this 'feature' in the config.yml of nightcore."); - } - } - - private boolean testItemNbt() { - if (!ItemNbt.setup(this)) return false; - - ItemStack testItem = new ItemStack(Material.DIAMOND_SWORD); - ItemUtil.editMeta(testItem, meta -> { - meta.setDisplayName("Test Item"); - meta.setLore(Lists.newList("Test Lore 1", "Test Lore 2", "Test Lore 3")); - meta.addEnchant(Enchantment.FIRE_ASPECT, 10, true); - }); - - String nbt = ItemNbt.compress(testItem); - if (nbt == null) return false; - - ItemStack decompressed = ItemNbt.decompress(nbt); - return decompressed != null && decompressed.isSimilar(testItem); - } } diff --git a/src/main/java/su/nightexpress/nightcore/NightCorePlugin.java b/src/main/java/su/nightexpress/nightcore/NightCorePlugin.java index fa86b03..1ecfcea 100644 --- a/src/main/java/su/nightexpress/nightcore/NightCorePlugin.java +++ b/src/main/java/su/nightexpress/nightcore/NightCorePlugin.java @@ -16,7 +16,7 @@ import java.util.function.Consumer; public interface NightCorePlugin extends Plugin { - boolean isEngine(); + //boolean isEngine(); void enable(); @@ -24,6 +24,7 @@ public interface NightCorePlugin extends Plugin { void reload(); + @Deprecated NightPluginCommand getBaseCommand(); @Override @@ -112,11 +113,13 @@ public interface NightCorePlugin extends Plugin { } @NotNull + @Deprecated default UniTask createTask(@NotNull Runnable runnable) { return new UniTask(this, runnable); } @NotNull + @Deprecated default UniTask createAsyncTask(@NotNull Runnable runnable) { return this.createTask(runnable).setAsync(); } diff --git a/src/main/java/su/nightexpress/nightcore/NightDataPlugin.java b/src/main/java/su/nightexpress/nightcore/NightDataPlugin.java index 7280b47..92b5194 100644 --- a/src/main/java/su/nightexpress/nightcore/NightDataPlugin.java +++ b/src/main/java/su/nightexpress/nightcore/NightDataPlugin.java @@ -5,6 +5,7 @@ import su.nightexpress.nightcore.database.AbstractUserDataHandler; import su.nightexpress.nightcore.database.AbstractUserManager; import su.nightexpress.nightcore.database.DataUser; +@Deprecated public abstract class NightDataPlugin extends NightPlugin { @Override diff --git a/src/main/java/su/nightexpress/nightcore/NightPlugin.java b/src/main/java/su/nightexpress/nightcore/NightPlugin.java index 3cf4c43..a74a0b2 100644 --- a/src/main/java/su/nightexpress/nightcore/NightPlugin.java +++ b/src/main/java/su/nightexpress/nightcore/NightPlugin.java @@ -13,55 +13,40 @@ import su.nightexpress.nightcore.util.*; import su.nightexpress.nightcore.util.wrapper.UniPermission; import java.io.File; +import java.util.ArrayList; +import java.util.List; public abstract class NightPlugin extends JavaPlugin implements NightCorePlugin { + protected List postLoaders; + protected LangManager langManager; protected CommandManager commandManager; protected FileConfig config; protected PluginDetails details; - private boolean isEngine; - public final boolean isEngine() { - return this.isEngine; +// public final boolean isEngine() { +// return this == Plugins.getCore(); +// } + + private boolean isCore() { + return this instanceof NightCore; } @Override public void onEnable() { - long loadTook = System.currentTimeMillis(); - this.isEngine = this instanceof NightCore; - - if (!this.isEngine()) { - Plugins.CORE.addChildren(this); - } - - Version version = Version.getCurrent(); - if (version == Version.UNKNOWN) { - this.warn("=".repeat(35)); - this.warn("WARNING: The plugin is not yet compatible with your server version!"); - this.warn("Expect bugs and broken features."); - this.warn("ABSOLUTELY NO DISCORD SUPPORT WILL BE PROVIDED!"); - this.warn("=".repeat(35)); - } - else if (version.isDeprecated()) { - this.warn("=".repeat(35)); - this.warn("WARNING: You're running an outdated server version (" + Version.getCurrent().getLocalized() + ")!"); - this.warn("This version will no longer be supported in future relases."); - this.warn("Please upgrade your server to " + Lists.next(Version.getCurrent(), (Version::isSupported)).getLocalized() + "."); - this.warn("NO DISCORD SUPPORT WILL BE PROVIDED!"); - this.warn("=".repeat(35)); - } - else if (version.isDropped()) { - this.error("=".repeat(35)); - this.error("ERROR: You're running an unsupported server version (" + Version.getCurrent().getLocalized() + ")!"); - this.error("Please upgrade your server to " + Lists.next(Version.getCurrent(), (Version::isSupported)).getLocalized() + "."); - this.error("ABSOLUTELY NO DISCORD SUPPORT WILL BE PROVIDED!"); - this.error("=".repeat(35)); + Version.printCaution(this); + if (Version.getCurrent().isDropped()) { this.getPluginManager().disablePlugin(this); return; } + if (!this.isCore()) { + Plugins.getCore().addChildren(this); + } + + long loadTook = System.currentTimeMillis(); this.loadManagers(); this.info("Plugin loaded in " + (System.currentTimeMillis() - loadTook) + " ms!"); } @@ -72,7 +57,7 @@ public abstract class NightPlugin extends JavaPlugin implements NightCorePlugin } public final void reload() { - if (this.isEngine()) { + if (this.isCore()) { this.setupConfig(); this.setupLanguage(); return; @@ -81,17 +66,6 @@ public abstract class NightPlugin extends JavaPlugin implements NightCorePlugin this.loadManagers(); } - /*@Override - public final void reloadConfig() { - this.getConfig().reload(); - this.loadConfig(); - } - - public final void reloadLang() { - this.getLang().reload(); - this.loadLang(); - }*/ - @Override @NotNull public final FileConfig getConfig() { @@ -100,7 +74,7 @@ public abstract class NightPlugin extends JavaPlugin implements NightCorePlugin @NotNull public final FileConfig getLang() { - return this.getLangManager().getConfig(); + return this.langManager.getConfig(); } @NotNull @@ -124,8 +98,8 @@ public abstract class NightPlugin extends JavaPlugin implements NightCorePlugin this.config = FileConfig.loadOrExtract(this, "config.yml"); this.details = PluginDetails.read(this); - if (this.getDetails().getConfigClass() != null) { - this.getConfig().initializeOptions(this.getDetails().getConfigClass()); + if (this.details.getConfigClass() != null) { + this.config.initializeOptions(this.details.getConfigClass()); } } @@ -133,13 +107,13 @@ public abstract class NightPlugin extends JavaPlugin implements NightCorePlugin this.langManager = new LangManager(this); this.langManager.setup(); - if (this.getDetails().getLangClass() != null) { - this.getLangManager().loadEntries(this.getDetails().getLangClass()); + if (this.details.getLangClass() != null) { + this.langManager.loadEntries(this.details.getLangClass()); } } protected void setupPermissions() { - Class clazz = this.getDetails().getPermissionsClass(); + Class clazz = this.details.getPermissionsClass(); if (clazz == null) return; this.registerPermissions(clazz); @@ -151,6 +125,8 @@ public abstract class NightPlugin extends JavaPlugin implements NightCorePlugin } protected void loadManagers() { + this.postLoaders = new ArrayList<>(); // Initialize a list for post-loading code. + this.setupConfig(); // Load configuration. this.setupLanguage(); // Load language. this.setupPermissions(); // Register plugin permissions. @@ -158,24 +134,41 @@ public abstract class NightPlugin extends JavaPlugin implements NightCorePlugin this.enable(); // Load the plugin. + this.postLoad(); // Load some stuff that needs to be injected after the rest managers. + this.getConfig().saveChanges(); this.getLang().saveChanges(); } protected void unloadManagers() { - this.getScheduler().cancelTasks(this); // Stop all plugin tasks. + this.getScheduler().cancelTasks(this); // Stop all plugin tasks. this.disable(); - AbstractMenu.clearAll(this); // Close all GUIs. - HandlerList.unregisterAll(this); // Unregister all plugin listeners. + AbstractMenu.clearAll(this); // Close all GUIs. + HandlerList.unregisterAll(this); // Unregister all plugin listeners. - this.getCommandManager().shutdown(); - this.getLangManager().shutdown(); - this.details = null; // Reset so it will use default ones on config read. + this.commandManager.shutdown(); + this.langManager.shutdown(); + this.details = null; // Reset so it will use default ones on config read. + } + + protected void postLoad() { + this.debug("Inject post-loading code..."); + this.postLoaders.forEach(Runnable::run); + this.postLoaders.clear(); + this.postLoaders = null; // Prevent from adding post-load code during runtime. + } + + public void onPostLoad(@NotNull Runnable runnable) { + if (this.postLoaders == null) { + throw new IllegalStateException("Can't inject post loading code during runtime."); + } + this.postLoaders.add(runnable); } @NotNull + @Deprecated public final NightPluginCommand getBaseCommand() { return this.getCommandManager().getMainCommand(); } diff --git a/src/main/java/su/nightexpress/nightcore/command/CommandManager.java b/src/main/java/su/nightexpress/nightcore/command/CommandManager.java index 2a4ea82..0c31ff2 100644 --- a/src/main/java/su/nightexpress/nightcore/command/CommandManager.java +++ b/src/main/java/su/nightexpress/nightcore/command/CommandManager.java @@ -69,6 +69,7 @@ public class CommandManager extends SimpleManager { } @NotNull + @Deprecated public Set getCommands() { return this.commands; } @@ -79,6 +80,7 @@ public class CommandManager extends SimpleManager { } @NotNull + @Deprecated public BaseCommand getMainCommand() { return this.mainCommand; } @@ -102,6 +104,7 @@ public class CommandManager extends SimpleManager { .findFirst().orElse(null); } + @Deprecated public void registerCommand(@NotNull NightPluginCommand command) { if (this.commands.add(command)) { CommandUtil.register(this.plugin, command); @@ -116,6 +119,7 @@ public class CommandManager extends SimpleManager { return false; } + @Deprecated public boolean unregisterCommand(@NotNull NightPluginCommand command) { if (this.commands.remove(command)) { return CommandUtil.unregister(command.getAliases()[0]); diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/argument/ArgumentTypes.java b/src/main/java/su/nightexpress/nightcore/command/experimental/argument/ArgumentTypes.java index d02b055..a8664eb 100644 --- a/src/main/java/su/nightexpress/nightcore/command/experimental/argument/ArgumentTypes.java +++ b/src/main/java/su/nightexpress/nightcore/command/experimental/argument/ArgumentTypes.java @@ -9,30 +9,36 @@ import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.command.experimental.builder.ArgumentBuilder; import su.nightexpress.nightcore.core.CoreLang; import su.nightexpress.nightcore.util.BukkitThing; -import su.nightexpress.nightcore.util.Lists; import su.nightexpress.nightcore.util.NumberUtil; import su.nightexpress.nightcore.util.Players; public class ArgumentTypes { - public static final ArgumentParser STRING = (string, context) -> string; - public static final ArgumentParser BOOLEAN = (string, context) -> Boolean.parseBoolean(string); - public static final ArgumentParser INTEGER = (string, context) -> NumberUtil.parseInteger(string).orElse(null); - public static final ArgumentParser INTEGER_ABS = (string, context) -> NumberUtil.parseInteger(string).map(Math::abs).orElse(null); - public static final ArgumentParser DOUBLE = (string, context) -> NumberUtil.parseDouble(string).orElse(null); - public static final ArgumentParser DOUBLE_ABS = (string, context) -> NumberUtil.parseDouble(string).map(Math::abs).orElse(null); - public static final ArgumentParser PLAYER = (string, context) -> Players.getPlayer(string); - public static final ArgumentParser WORLD = (string, context) -> Bukkit.getWorld(string); - public static final ArgumentParser MATERIAL = (string, context) -> BukkitThing.getMaterial(string); - public static final ArgumentParser ITEM_MATERIAL = (string, context) -> { + public static final ArgumentParser STRING = (string, context) -> string; + public static final ArgumentParser BOOLEAN = (string, context) -> Boolean.parseBoolean(string); + public static final ArgumentParser INTEGER = (string, context) -> NumberUtil.parseInteger(string).orElse(null); + public static final ArgumentParser INTEGER_ABS = (string, context) -> NumberUtil.parseInteger(string).map(Math::abs).orElse(null); + public static final ArgumentParser INTEGER_COMPACT = (string, context) -> NumberUtil.parseIntCompact(string).orElse(null); + public static final ArgumentParser INTEGER_COMPACT_ABS = (string, context) -> NumberUtil.parseIntCompact(string).map(Math::abs).orElse(null); + public static final ArgumentParser DOUBLE = (string, context) -> NumberUtil.parseDouble(string).orElse(null); + public static final ArgumentParser DOUBLE_ABS = (string, context) -> NumberUtil.parseDouble(string).map(Math::abs).orElse(null); + public static final ArgumentParser DOUBLE_COMPACT = (string, context) -> NumberUtil.parseCompact(string).orElse(null); + public static final ArgumentParser DOUBLE_COMPACT_ABS = (string, context) -> NumberUtil.parseCompact(string).map(Math::abs).orElse(null); + public static final ArgumentParser PLAYER = (string, context) -> Players.getPlayer(string); + public static final ArgumentParser WORLD = (string, context) -> Bukkit.getWorld(string); + public static final ArgumentParser MATERIAL = (string, context) -> BukkitThing.getMaterial(string); + + public static final ArgumentParser ITEM_MATERIAL = (string, context) -> { Material material = BukkitThing.getMaterial(string); return material == null || !material.isItem() ? null : material; }; - public static final ArgumentParser BLOCK_MATERIAL = (string, context) -> { + + public static final ArgumentParser BLOCK_MATERIAL = (string, context) -> { Material material = BukkitThing.getMaterial(string); return material == null || !material.isBlock() ? null : material; }; - public static final ArgumentParser ENCHANTMENT = (string, context) -> BukkitThing.getEnchantment(string); + + public static final ArgumentParser ENCHANTMENT = (string, context) -> BukkitThing.getEnchantment(string); //public static final ArgumentParser POTION_EFFECT = BukkitThing::getPotionEffect; //public static final ArgumentParser ATTRIBUTE = BukkitThing::getAttribute; @@ -48,28 +54,47 @@ public class ArgumentTypes { @NotNull public static ArgumentBuilder integer(@NotNull String name) { - return CommandArgument.builder(name, INTEGER) - .localized(CoreLang.COMMAND_ARGUMENT_NAME_GENERIC) - .customFailure(CoreLang.ERROR_COMMAND_INVALID_NUMBER_ARGUMENT); + return numeric(name, INTEGER); } @NotNull public static ArgumentBuilder integerAbs(@NotNull String name) { - return CommandArgument.builder(name, INTEGER_ABS) - .localized(CoreLang.COMMAND_ARGUMENT_NAME_GENERIC) - .customFailure(CoreLang.ERROR_COMMAND_INVALID_NUMBER_ARGUMENT); + return numeric(name, INTEGER_ABS); + } + + @NotNull + public static ArgumentBuilder integerCompact(@NotNull String name) { + return numeric(name, INTEGER_COMPACT); + } + + @NotNull + public static ArgumentBuilder integerCompactAbs(@NotNull String name) { + return numeric(name, INTEGER_COMPACT_ABS); } @NotNull public static ArgumentBuilder decimal(@NotNull String name) { - return CommandArgument.builder(name, DOUBLE) - .localized(CoreLang.COMMAND_ARGUMENT_NAME_GENERIC) - .customFailure(CoreLang.ERROR_COMMAND_INVALID_NUMBER_ARGUMENT); + return numeric(name, DOUBLE); } @NotNull public static ArgumentBuilder decimalAbs(@NotNull String name) { - return CommandArgument.builder(name, DOUBLE_ABS) + return numeric(name, DOUBLE_ABS); + } + + @NotNull + public static ArgumentBuilder decimalCompact(@NotNull String name) { + return numeric(name, DOUBLE_COMPACT); + } + + @NotNull + public static ArgumentBuilder decimalCompactAbs(@NotNull String name) { + return numeric(name, DOUBLE_COMPACT_ABS); + } + + @NotNull + private static ArgumentBuilder numeric(@NotNull String name, @NotNull ArgumentParser parser) { + return CommandArgument.builder(name, parser) .localized(CoreLang.COMMAND_ARGUMENT_NAME_GENERIC) .customFailure(CoreLang.ERROR_COMMAND_INVALID_NUMBER_ARGUMENT); } @@ -94,7 +119,7 @@ public class ArgumentTypes { return CommandArgument.builder(name, WORLD) .localized(CoreLang.COMMAND_ARGUMENT_NAME_WORLD) .customFailure(CoreLang.ERROR_COMMAND_INVALID_WORLD_ARGUMENT) - .withSamples(tabContext -> Lists.worldNames()); + .withSamples(tabContext -> BukkitThing.worldNames()); } @NotNull diff --git a/src/main/java/su/nightexpress/nightcore/command/experimental/impl/ReloadCommand.java b/src/main/java/su/nightexpress/nightcore/command/experimental/impl/ReloadCommand.java index bfcfef8..0459890 100644 --- a/src/main/java/su/nightexpress/nightcore/command/experimental/impl/ReloadCommand.java +++ b/src/main/java/su/nightexpress/nightcore/command/experimental/impl/ReloadCommand.java @@ -4,6 +4,7 @@ import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.NightCorePlugin; import su.nightexpress.nightcore.command.experimental.CommandContext; import su.nightexpress.nightcore.command.experimental.argument.ParsedArguments; +import su.nightexpress.nightcore.command.experimental.builder.DirectNodeBuilder; import su.nightexpress.nightcore.command.experimental.node.ChainedNode; import su.nightexpress.nightcore.command.experimental.node.DirectNode; import su.nightexpress.nightcore.core.CoreLang; @@ -11,12 +12,17 @@ import su.nightexpress.nightcore.util.wrapper.UniPermission; public class ReloadCommand { + @Deprecated public static void inject(@NotNull NightCorePlugin plugin, @NotNull ChainedNode node, @NotNull UniPermission permission) { - node.addChildren(DirectNode.builder(plugin, "reload") + node.addChildren(builder(plugin, permission)); + } + + @NotNull + public static DirectNodeBuilder builder(@NotNull NightCorePlugin plugin, @NotNull UniPermission permission) { + return DirectNode.builder(plugin, "reload") .permission(permission) .description(CoreLang.COMMAND_RELOAD_DESC) - .executes((context, arguments) -> execute(plugin, context, arguments)) - ); + .executes((context, arguments) -> execute(plugin, context, arguments)); } public static boolean execute(@NotNull NightCorePlugin plugin, @NotNull CommandContext context, @NotNull ParsedArguments arguments) { diff --git a/src/main/java/su/nightexpress/nightcore/command/impl/WrappedCommand.java b/src/main/java/su/nightexpress/nightcore/command/impl/WrappedCommand.java index d3c1d8d..c9f0ae0 100644 --- a/src/main/java/su/nightexpress/nightcore/command/impl/WrappedCommand.java +++ b/src/main/java/su/nightexpress/nightcore/command/impl/WrappedCommand.java @@ -17,6 +17,7 @@ public class WrappedCommand extends Command implements PluginIdentifiableCommand protected final CommandExecutor executor; protected final TabCompleter tabCompleter; + @Deprecated public WrappedCommand(@NotNull Plugin plugin, @NotNull NightPluginCommand command) { this(plugin, command, command, command.getAliases(), command.getDescription(), command.getUsage(), command.getPermission()); //this.setPermission(command.getPermission()); diff --git a/src/main/java/su/nightexpress/nightcore/config/ConfigValue.java b/src/main/java/su/nightexpress/nightcore/config/ConfigValue.java index 84e14f9..27088f3 100644 --- a/src/main/java/su/nightexpress/nightcore/config/ConfigValue.java +++ b/src/main/java/su/nightexpress/nightcore/config/ConfigValue.java @@ -3,15 +3,15 @@ package su.nightexpress.nightcore.config; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.StringUtil; import su.nightexpress.nightcore.util.TriFunction; +import su.nightexpress.nightcore.util.bukkit.NightSound; import su.nightexpress.nightcore.util.wrapper.UniFormatter; import su.nightexpress.nightcore.util.wrapper.UniParticle; import su.nightexpress.nightcore.util.wrapper.UniSound; import java.util.*; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.function.UnaryOperator; +import java.util.function.*; import java.util.stream.Collectors; public class ConfigValue { @@ -117,6 +117,7 @@ public class ConfigValue { } @NotNull + @Deprecated public static ConfigValue create(@NotNull String path, @NotNull UniSound defaultValue, @Nullable String... description) { Reader reader = (cfg, path1, def) -> UniSound.read(cfg, path1); Writer writer = (cfg, path1, obj) -> obj.write(cfg, path1); @@ -124,6 +125,14 @@ public class ConfigValue { return create(path, reader, writer, defaultValue, description); } + @NotNull + public static ConfigValue create(@NotNull String path, @NotNull NightSound defaultValue, @Nullable String... description) { + Reader reader = (cfg, readPath, def) -> NightSound.read(cfg, readPath); + Writer writer = (cfg, writePath, sound) -> sound.write(cfg, writePath); + + return create(path, reader, writer, defaultValue, description); + } + @NotNull public static ConfigValue create(@NotNull String path, @NotNull UniParticle defaultValue, @Nullable String... description) { Reader reader = (cfg, path1, def) -> UniParticle.read(cfg, path1); @@ -170,6 +179,7 @@ public class ConfigValue { } @NotNull + @Deprecated public static ConfigValue> forMap(@NotNull String path, @NotNull Function keyFun, @NotNull TriFunction valFun, @@ -180,6 +190,7 @@ public class ConfigValue { } @NotNull + @Deprecated public static ConfigValue> forMap(@NotNull String path, @NotNull Function keyFun, @NotNull TriFunction valFun, @@ -190,6 +201,7 @@ public class ConfigValue { } @NotNull + @Deprecated public static ConfigValue> forTreeMap(@NotNull String path, @NotNull Function keyFun, @NotNull TriFunction valFun, @@ -199,6 +211,7 @@ public class ConfigValue { } @NotNull + @Deprecated public static ConfigValue> forTreeMap(@NotNull String path, @NotNull Function keyFun, @NotNull TriFunction valFun, @@ -208,6 +221,7 @@ public class ConfigValue { } @NotNull + @Deprecated public static > ConfigValue forMap(@NotNull String path, @NotNull Function keyFun, @NotNull TriFunction valFun, @@ -230,6 +244,68 @@ public class ConfigValue { } @NotNull + public static ConfigValue> forMap(@NotNull String path, + @NotNull Function keyReadFun, + @NotNull Function keyWriteFun, + @NotNull BiFunction valReadFun, + //@NotNull Supplier> mapSupplier, + @NotNull Consumer> defaultValue, + @Nullable String... description) { + Reader> reader = (cfg, readPath, def) -> { + var map = new HashMap();//mapSupplier.get(); + for (String keyRaw : cfg.getSection(readPath)) { + K key = keyReadFun.apply(keyRaw); + V val = valReadFun.apply(cfg, readPath + "." + keyRaw); + if (key == null || val == null) continue; + + map.put(key, val); + } + return map; + }; + + Writer> writer = (cfg, writePath, map) -> { + map.forEach((key, value) -> { + String keyRaw = keyWriteFun.apply(key); + value.write(cfg, writePath + "." + keyRaw); + }); + }; + + // Linked map used only to preserve the order of default values when writing it in the config. + Map defaultMap = new LinkedHashMap<>(); + defaultValue.accept(defaultMap); + + return create(path, reader, writer, defaultMap, description); + } + +// @NotNull +// public static ConfigValue> forHashMap(@NotNull String path, +// @NotNull Function keyReadFun, +// @NotNull Function keyWriteFun, +// @NotNull BiFunction valReadFun, +// @NotNull Consumer> defaultValue, +// @Nullable String... description) { +// return forMap(path, keyReadFun, keyWriteFun, valReadFun, HashMap::new, defaultValue, description); +// } + + @NotNull + public static ConfigValue> forMapById(@NotNull String path, + @NotNull BiFunction valReadFun, + @NotNull Consumer> defaultValue, + @Nullable String... description) { + return forMap(path, String::toLowerCase, key -> key, valReadFun, defaultValue, description); + } + + @NotNull + public static , V extends Writeable> ConfigValue> forMapByEnum(@NotNull String path, + @NotNull Class clazz, + @NotNull BiFunction valReadFun, + @NotNull Consumer> defaultValue, + @Nullable String... description) { + return forMap(path, str -> StringUtil.getEnum(str, clazz).orElse(null), Enum::name, valReadFun, defaultValue, description); + } + + @NotNull + @Deprecated public static ConfigValue> forMap(@NotNull String path, @NotNull TriFunction function, @NotNull Writer> writer, @@ -239,6 +315,7 @@ public class ConfigValue { } @NotNull + @Deprecated public static ConfigValue> forMap(@NotNull String path, @NotNull TriFunction function, @NotNull Writer> writer, diff --git a/src/main/java/su/nightexpress/nightcore/config/FileConfig.java b/src/main/java/su/nightexpress/nightcore/config/FileConfig.java index f051703..73d656e 100644 --- a/src/main/java/su/nightexpress/nightcore/config/FileConfig.java +++ b/src/main/java/su/nightexpress/nightcore/config/FileConfig.java @@ -150,7 +150,10 @@ public class FileConfig extends YamlConfiguration { @Override public void set(@NotNull String path, @Nullable Object value) { - if (value instanceof String str) { + if (value instanceof Writeable writeable) { + writeable.write(this, path); + } + else if (value instanceof String str) { value = Colorizer.plain(str); } else if (value instanceof Collection collection) { @@ -222,6 +225,7 @@ public class FileConfig extends YamlConfiguration { @Override @Nullable + @Deprecated public Location getLocation(@NotNull String path) { String raw = this.getString(path); return raw == null ? null : LocationUtil.deserialize(raw); @@ -408,9 +412,6 @@ public class FileConfig extends YamlConfiguration { this.set(path + "Material", material.name()); this.set(path + "Amount", item.getAmount() <= 1 ? null : item.getAmount()); this.set(path + "SkinURL", ItemUtil.getHeadSkin(item)); -// if (!this.contains(path + "SkinURL")) { -// this.set(path + "Head_Texture", ItemUtil.getSkullTexture(item)); -// } ItemMeta meta = item.getItemMeta(); if (meta == null) return; diff --git a/src/main/java/su/nightexpress/nightcore/config/PluginDetails.java b/src/main/java/su/nightexpress/nightcore/config/PluginDetails.java index 39822d2..8c85610 100644 --- a/src/main/java/su/nightexpress/nightcore/config/PluginDetails.java +++ b/src/main/java/su/nightexpress/nightcore/config/PluginDetails.java @@ -17,6 +17,7 @@ public class PluginDetails { private final String[] commandAliases; private final String language; + @Deprecated private DatabaseConfig databaseConfig; private Class configClass; @@ -102,11 +103,13 @@ public class PluginDetails { } @Nullable + @Deprecated public DatabaseConfig getDatabaseConfig() { return databaseConfig; } @NotNull + @Deprecated public PluginDetails setDatabaseConfig(@Nullable DatabaseConfig databaseConfig) { this.databaseConfig = databaseConfig; return this; diff --git a/src/main/java/su/nightexpress/nightcore/config/Writeable.java b/src/main/java/su/nightexpress/nightcore/config/Writeable.java new file mode 100644 index 0000000..b812ea1 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/config/Writeable.java @@ -0,0 +1,8 @@ +package su.nightexpress.nightcore.config; + +import org.jetbrains.annotations.NotNull; + +public interface Writeable { + + void write(@NotNull FileConfig config, @NotNull String path); +} diff --git a/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java b/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java index 5cf0c72..b3c5eef 100644 --- a/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java +++ b/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java @@ -3,19 +3,17 @@ package su.nightexpress.nightcore.core; import su.nightexpress.nightcore.config.ConfigValue; import su.nightexpress.nightcore.util.Placeholders; import su.nightexpress.nightcore.util.StringUtil; -import su.nightexpress.nightcore.util.text.tag.Tags; -import su.nightexpress.nightcore.util.text.tag.impl.ColorTag; +import su.nightexpress.nightcore.util.number.NumberShortcut; import su.nightexpress.nightcore.util.wrapper.UniFormatter; -import java.awt.*; import java.math.RoundingMode; -import java.util.HashMap; import java.util.Map; public class CoreConfig { + @Deprecated public static final ConfigValue DATA_FIXER_ENABLED = ConfigValue.create("DataFixer.Enabled", - true, + false, "When enabled, uses Mojang's DataFixer util to update ItemStacks from <= 1.20.4 NBT format to 1.20.5+ NBT format.", "IMPORTANT NOTE: You need to use this setting only once! Enable it, reboot the server and re-save all configurations that stores compressed item data: shops, crates, etc." ); @@ -26,70 +24,72 @@ public class CoreConfig { "When disabled, parses (deserializes) language texts to Spigot TextComponent(s) in runtime when sending it to player.", "Enabling this setting is good for performance, however messages with placeholders will be recompiled in runtime anyway.", "(Side Note) Unlike NexEngine, it does not uses regex anymore, which makes deserialization significantly faster and accurate.", - "[Default is true]"); - - public static final ConfigValue> MODERN_TEXT_DEFAULT_COLORS = ConfigValue.forMap("ModernTextFormation.Default_Colors", - (cfg, path, id) -> { - try { - Color color = Color.decode(cfg.getString(path + "." + id, "#ffffff")); - Tags.registerTag(new ColorTag(id, color)); - return color; - } - catch (Exception exception) { - exception.printStackTrace(); - return Color.WHITE; - } - }, - (cfg, path, map) -> map.forEach((id, value) -> cfg.set(path + "." + id, "#" + Integer.toHexString(value.getRGB()).substring(2))), - () -> { - Map map = new HashMap<>(); - map.put("aqua", Color.CYAN); - return map; - }, - "Here you can define custom colors to use it in all nightcore plugins like Text.", - "You can also override default ones." + "[Default is true]" ); public static final ConfigValue MENU_CLICK_COOLDOWN = ConfigValue.create("Menu.Click_Cooldown", 150L, "Sets cooldown (in milliseconds) for player clicks in GUIs.", - "[Default is 150ms]"); + "[Default is 150ms]" + ); - public static final ConfigValue USER_DEBUG_ENABLED = ConfigValue.create("UserData.Debug", - false, - "Enables debug messages for user data management.", - "[Default is false]"); +// @Deprecated +// public static final ConfigValue USER_DEBUG_ENABLED = ConfigValue.create("UserData.Debug", +// false, +// "Enables debug messages for user data management.", +// "[Default is false]"); + @Deprecated public static final ConfigValue USER_CACHE_LIFETIME = ConfigValue.create("UserData.Cache.LifeTime", 300, - "Sets how long (in seconds) user data will be cached for offline users", - "until removed and needs to be loaded from the database again.", - "[Default is 300 (5 minutes)]"); + "[ OUTDATED, MOVED IN PER-PLUGIN config.yml ]" + ); - public static final ConfigValue USER_CACHE_NAME_AND_UUID = ConfigValue.create("UserData.Cache.Names_And_UUIDs", - true, - "Sets whether or not plugin will cache player names and UUIDs.", - "This will improve database performance when checking if user exists, but will use more memory to store UUIDs and names.", - "[Default is true]"); +// @Deprecated +// public static final ConfigValue USER_CACHE_NAME_AND_UUID = ConfigValue.create("UserData.Cache.Names_And_UUIDs", +// true, +// "Sets whether or not plugin will cache player names and UUIDs.", +// "This will improve database performance when checking if user exists, but will use more memory to store UUIDs and names.", +// "[Default is true]"); public static final ConfigValue LEGACY_COLOR_SUPPORT = ConfigValue.create("Engine.Legacy_Color_Support", true, "Allows to use legacy color codes (such as '&7', '&l', etc.) in plugin configurations.", "This setting exist for backwards compatibility only! There are NO GUARANTEES that it will persist for future updates!", "You should NOT use it unless you need to add support for your custom language configurations & translations with legacy codes.", - "You should migrate to new text format as soon as possible: " + Placeholders.WIKI_TEXT_URL); + "You should migrate to new text format as soon as possible: " + Placeholders.WIKI_TEXT_URL + ); - public static final ConfigValue RESPECT_PLAYER_DISPLAYNAME = ConfigValue.create("Engine.Respect_Player_DisplayName", - false, - "Sets whether or not 'Player#getDisplayName' can be used to find & get players in addition to regular 'Player#getName'.", - "This is useful if you want to use custom player nicknames in commands.", - "(Works only for nightcore based plugins.)", - "[Default is false]"); +// public static final ConfigValue RESPECT_PLAYER_DISPLAYNAME = ConfigValue.create("Engine.Respect_Player_DisplayName", +// false, +// "Sets whether or not 'Player#getDisplayName' can be used to find & get players in addition to regular 'Player#getName'.", +// "This is useful if you want to use custom player nicknames in commands.", +// "(Works only for nightcore based plugins.)", +// "[Default is false]"); - public static final ConfigValue NUMBER_FORMAT = ConfigValue.create("Engine.Number_Format", + public static final ConfigValue NUMBER_FORMAT = ConfigValue.create("Number.Format", UniFormatter.of("#,###.###", RoundingMode.HALF_EVEN), "Control over how numerical data is formatted and rounded.", "Allowed modes: " + StringUtil.inlineEnum(RoundingMode.class, ", "), "A tutorial can be found here: https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html" ); + + public static final ConfigValue NUMBER_SHORTCUT_STEP = ConfigValue.create("Number.Shortcut_Step", + 1000, + "Sets step for the Number Shortcut's magnitude.", + "When a number is about to be compacted, it will be divided by this value to determine if it falls under specific Number Shortcut.", + "[Default is 1000]" + ); + + public static final ConfigValue> NUMBER_SHORTCUT_LIST = ConfigValue.forMapById("Number.Shortcut_List", + NumberShortcut::read, + map -> { + map.put("thousand", new NumberShortcut(1, "k")); + map.put("million", new NumberShortcut(2, "m")); + map.put("billion", new NumberShortcut(3, "b")); + map.put("trillion", new NumberShortcut(4, "t")); + map.put("quadrillion", new NumberShortcut(5, "q")); + }, + "Custom number shortcuts." + ); } diff --git a/src/main/java/su/nightexpress/nightcore/core/CoreLang.java b/src/main/java/su/nightexpress/nightcore/core/CoreLang.java index 5331d8c..d0a3c41 100644 --- a/src/main/java/su/nightexpress/nightcore/core/CoreLang.java +++ b/src/main/java/su/nightexpress/nightcore/core/CoreLang.java @@ -50,11 +50,9 @@ public class CoreLang { " " + YELLOW.enclose("/" + COMMAND_LABEL) + " " + ORANGE.enclose(COMMAND_USAGE) + GRAY.enclose(" - " + COMMAND_DESCRIPTION) ); - public static final LangString COMMAND_HELP_DESC = LangString.of("Command.Help.Desc", "Show help page."); - + public static final LangString COMMAND_HELP_DESC = LangString.of("Command.Help.Desc", "Show help page."); public static final LangString COMMAND_CHECKPERM_DESC = LangString.of("Command.CheckPerm.Desc", "Print player permission info."); - - public static final LangString COMMAND_RELOAD_DESC = LangString.of("Command.Reload.Desc", "Reload the plugin."); + public static final LangString COMMAND_RELOAD_DESC = LangString.of("Command.Reload.Desc", "Reload the plugin."); public static final LangText COMMAND_RELOAD_DONE = LangText.of("Command.Reload.Done", LIGHT_GRAY.enclose("Plugin " + LIGHT_GREEN.enclose("reloaded") + "!")); @@ -89,9 +87,11 @@ public class CoreLang { public static final LangText ERROR_INVALID_NUMBER = LangText.of("Error.Invalid_Number", RED.enclose("Invalid number!")); + @Deprecated public static final LangText ERROR_INVALID_MATERIAL = LangText.of("Error.InvalidMaterial", RED.enclose("Invalid material!")); + @Deprecated public static final LangText ERROR_INVALID_ENCHANTMENT = LangText.of("Error.InvalidEnchantment", RED.enclose("Invalid enchantment!")); @@ -160,11 +160,11 @@ public class CoreLang { public static final LangItem EDITOR_ITEM_NEXT_PAGE = LangItem.of("Editor.Generic.NextPage", LIGHT_GRAY.enclose("Next Page →")); public static final LangItem EDITOR_ITEM_PREVIOUS_PAGE = LangItem.of("Editor.Generic.PreviousPage", LIGHT_GRAY.enclose("← Previous Page")); - public static final LangString NUMBER_SHORT_THOUSAND = LangString.of("Number.Thousand", "k"); - public static final LangString NUMBER_SHORT_MILLION = LangString.of("Number.Million", "m"); - public static final LangString NUMBER_SHORT_BILLION = LangString.of("Number.Billion", "b"); - public static final LangString NUMBER_SHORT_TRILLION = LangString.of("Number.Trillion", "t"); - public static final LangString NUMBER_SHORT_QUADRILLION = LangString.of("Number.Quadrillion", "q"); +// public static final LangString NUMBER_SHORT_THOUSAND = LangString.of("Number.Thousand", "k"); +// public static final LangString NUMBER_SHORT_MILLION = LangString.of("Number.Million", "m"); +// public static final LangString NUMBER_SHORT_BILLION = LangString.of("Number.Billion", "b"); +// public static final LangString NUMBER_SHORT_TRILLION = LangString.of("Number.Trillion", "t"); +// public static final LangString NUMBER_SHORT_QUADRILLION = LangString.of("Number.Quadrillion", "q"); @NotNull public static String getYesOrNo(boolean value) { diff --git a/src/main/java/su/nightexpress/nightcore/core/CoreManager.java b/src/main/java/su/nightexpress/nightcore/core/CoreManager.java index f78ff43..86258c2 100644 --- a/src/main/java/su/nightexpress/nightcore/core/CoreManager.java +++ b/src/main/java/su/nightexpress/nightcore/core/CoreManager.java @@ -9,6 +9,8 @@ import su.nightexpress.nightcore.manager.AbstractManager; import su.nightexpress.nightcore.menu.MenuListener; import su.nightexpress.nightcore.menu.impl.AbstractMenu; +import java.util.HashSet; + public class CoreManager extends AbstractManager { public CoreManager(@NotNull NightCore plugin) { @@ -21,21 +23,25 @@ public class CoreManager extends AbstractManager { this.addListener(new DialogListener(this.plugin)); this.addListener(new MenuListener(this.plugin)); - this.addTask(this.plugin.createTask(() -> { - AbstractMenu.PLAYER_MENUS.values().forEach(menu -> { - if (menu.getOptions().isReadyToRefresh()) { - menu.flush(); - menu.getOptions().setLastAutoRefresh(System.currentTimeMillis()); - } - }); - - Dialog.checkTimeOut(); - - }).setSecondsInterval(1)); + this.addAsyncTask(this::tickDialogs, 1); + this.addTask(this::tickMenus, 1); } @Override protected void onShutdown() { } + + private void tickDialogs() { + Dialog.checkTimeOut(); + } + + private void tickMenus() { + new HashSet<>(AbstractMenu.PLAYER_MENUS.values()).forEach(menu -> { + if (menu.getOptions().isReadyToRefresh()) { + menu.flush(); + menu.getOptions().setLastAutoRefresh(System.currentTimeMillis()); + } + }); + } } diff --git a/src/main/java/su/nightexpress/nightcore/core/command/CheckPermCommand.java b/src/main/java/su/nightexpress/nightcore/core/command/CoreCommands.java similarity index 66% rename from src/main/java/su/nightexpress/nightcore/core/command/CheckPermCommand.java rename to src/main/java/su/nightexpress/nightcore/core/command/CoreCommands.java index 501b470..727f162 100644 --- a/src/main/java/su/nightexpress/nightcore/core/command/CheckPermCommand.java +++ b/src/main/java/su/nightexpress/nightcore/core/command/CoreCommands.java @@ -6,31 +6,41 @@ import su.nightexpress.nightcore.NightCore; import su.nightexpress.nightcore.command.experimental.CommandContext; import su.nightexpress.nightcore.command.experimental.argument.ArgumentTypes; import su.nightexpress.nightcore.command.experimental.argument.ParsedArguments; +import su.nightexpress.nightcore.command.experimental.impl.ReloadCommand; import su.nightexpress.nightcore.command.experimental.node.ChainedNode; import su.nightexpress.nightcore.command.experimental.node.DirectNode; import su.nightexpress.nightcore.core.CoreLang; import su.nightexpress.nightcore.core.CorePerms; import su.nightexpress.nightcore.integration.VaultHook; import su.nightexpress.nightcore.util.Colorizer; +import su.nightexpress.nightcore.util.Plugins; import su.nightexpress.nightcore.util.text.NightMessage; +import static su.nightexpress.nightcore.util.Placeholders.TAG_LINE_BREAK; import static su.nightexpress.nightcore.util.text.tag.Tags.*; -import static su.nightexpress.nightcore.util.Placeholders.*; -public class CheckPermCommand { +public class CoreCommands { + + private static final String CMD_CHECKPERM = "checkperm"; private static final String ARG_PLAYER = "player"; - public static void inject(@NotNull NightCore plugin, @NotNull ChainedNode node) { - node.addChildren(DirectNode.builder(plugin, "checkperm") - .permission(CorePerms.COMMAND_CHECK_PERM) - .description(CoreLang.COMMAND_CHECKPERM_DESC) - .withArgument(ArgumentTypes.player(ARG_PLAYER).required()) - .executes(CheckPermCommand::execute) - ); + public static void load(@NotNull NightCore core) { + ChainedNode root = core.getRootNode(); + + if (Plugins.hasVault()) { + root.addChildren(DirectNode.builder(core, CMD_CHECKPERM) + .permission(CorePerms.COMMAND_CHECK_PERM) + .description(CoreLang.COMMAND_CHECKPERM_DESC) + .withArgument(ArgumentTypes.player(ARG_PLAYER).required()) + .executes(CoreCommands::checkPermissions) + ); + } + + root.addChildren(ReloadCommand.builder(core, CorePerms.COMMAND_RELOAD)); } - public static boolean execute(@NotNull CommandContext context, @NotNull ParsedArguments arguments) { + private static boolean checkPermissions(@NotNull CommandContext context, @NotNull ParsedArguments arguments) { Player player = arguments.getPlayerArgument(ARG_PLAYER); String builder = BOLD.enclose(LIGHT_YELLOW.enclose("Permissions report for ") + LIGHT_ORANGE.enclose(player.getName() + ":")) + diff --git a/src/main/java/su/nightexpress/nightcore/core/listener/CoreListener.java b/src/main/java/su/nightexpress/nightcore/core/listener/CoreListener.java index 02b045c..31146a6 100644 --- a/src/main/java/su/nightexpress/nightcore/core/listener/CoreListener.java +++ b/src/main/java/su/nightexpress/nightcore/core/listener/CoreListener.java @@ -16,8 +16,8 @@ public class CoreListener extends AbstractListener { } @EventHandler(priority = EventPriority.NORMAL) - public void onServiceRegisterEvent(ServiceRegisterEvent event) { - if (Plugins.isLoaded(Plugins.VAULT)) { + public void onServiceRegister(ServiceRegisterEvent event) { + if (Plugins.hasVault()) { VaultHook.onServiceRegisterEvent(event); } } diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractConnector.java b/src/main/java/su/nightexpress/nightcore/database/AbstractConnector.java index 2174c1a..bd57ac8 100644 --- a/src/main/java/su/nightexpress/nightcore/database/AbstractConnector.java +++ b/src/main/java/su/nightexpress/nightcore/database/AbstractConnector.java @@ -10,6 +10,7 @@ import su.nightexpress.nightcore.database.connection.SQLiteConnector; import java.sql.Connection; import java.sql.SQLException; +@Deprecated public abstract class AbstractConnector { protected final NightCorePlugin plugin; diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java b/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java index c160ed4..756c330 100644 --- a/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java +++ b/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java @@ -24,6 +24,7 @@ import java.util.List; import java.util.Optional; import java.util.function.Function; +@Deprecated public abstract class AbstractDataHandler

extends AbstractManager

{ protected final DatabaseConfig config; @@ -150,11 +151,6 @@ public abstract class AbstractDataHandler

extends Abs return UpdateEntity.create(values, conditions); } -// @NotNull -// public UpdateQuery updateQuery(@NotNull String table, @NotNull List values, @NotNull List conditions) { -// return UpdateQuery.create(table, values, conditions); -// } -// public void executeUpdate(@NotNull String table, @NotNull List values, @NotNull List conditions) { this.executeUpdate(UpdateQuery.create(table, values, conditions)); } @@ -163,11 +159,6 @@ public abstract class AbstractDataHandler

extends Abs SQLQueries.executeUpdate(this.connector, query); } -// @Deprecated -// public void executeUpdates(@NotNull UpdateQuery queries) { -// SQLQueries.executeUpdates(this.connector, queries); -// } - diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUser.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUser.java index ba8122a..df8a4eb 100644 --- a/src/main/java/su/nightexpress/nightcore/database/AbstractUser.java +++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUser.java @@ -8,6 +8,7 @@ import su.nightexpress.nightcore.NightCorePlugin; import java.util.UUID; +@Deprecated public abstract class AbstractUser

implements DataUser { protected final P plugin; diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java index 382d1d6..5981d3f 100644 --- a/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java +++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java @@ -9,7 +9,6 @@ import su.nightexpress.nightcore.database.sql.SQLCondition; import su.nightexpress.nightcore.database.sql.SQLQueries; import su.nightexpress.nightcore.database.sql.SQLValue; import su.nightexpress.nightcore.database.sql.column.ColumnType; -import su.nightexpress.nightcore.core.CoreConfig; import su.nightexpress.nightcore.database.sql.query.UpdateEntity; import su.nightexpress.nightcore.database.sql.query.UpdateQuery; import su.nightexpress.nightcore.util.Lists; @@ -21,6 +20,7 @@ import java.time.LocalDateTime; import java.util.*; import java.util.function.Function; +@Deprecated public abstract class AbstractUserDataHandler

, U extends DataUser> extends AbstractDataHandler

{ protected static final SQLColumn COLUMN_USER_ID = SQLColumn.of("uuid", ColumnType.STRING); @@ -83,8 +83,7 @@ public abstract class AbstractUserDataHandler

, U ex } public boolean isNameIdCacheEnabled() { - // TODO NOT WORKING FOR MYSQL DUE TO LOCAL CACHE, OTHER SERVERS THINK THAT PLAYER NOT EXISTS - return CoreConfig.USER_CACHE_NAME_AND_UUID.get() && this.getDatabaseType() == DatabaseType.SQLITE; + return false;//CoreConfig.USER_CACHE_NAME_AND_UUID.get() && this.getDatabaseType() == DatabaseType.SQLITE; } public void cacheNamesAndIds() { diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java index 7992012..f289f14 100644 --- a/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java +++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java @@ -15,6 +15,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.function.Supplier; +@Deprecated public abstract class AbstractUserManager

, U extends DataUser> extends AbstractManager

{ private final UserdataConfig config; @@ -34,7 +35,7 @@ public abstract class AbstractUserManager

, U extend @Override protected void onLoad() { this.addListener(new UserListener<>(this.plugin)); - this.addTask(this.plugin.createAsyncTask(this::saveScheduled).setTicksInterval(this.config.getScheduledSaveInterval())); + this.addTask(this.plugin.createAsyncTask(this::saveScheduled).setTicksInterval(this.config.getSaveInterval())); } @Override @@ -74,7 +75,7 @@ public abstract class AbstractUserManager

, U extend users.forEach(user -> { user.cancelAutoSave(); // Reset autosave timestamp. - user.setNextSyncIn(this.config.getScheduledSaveSyncPause()); // Unlock synchronization only when all data was pushed to the database. + user.setNextSyncIn(this.config.getSaveSyncPause()); // Unlock synchronization only when all data was pushed to the database. }); this.scheduledSaves.values().removeAll(users); @@ -99,10 +100,10 @@ public abstract class AbstractUserManager

, U extend if (Players.isReal(player)) { user = this.getUserData(uuid); if (user != null) { - if (CoreConfig.USER_DEBUG_ENABLED.get()) { - new Throwable().printStackTrace(); - this.plugin.warn("Main thread user data load for '" + uuid + "' aka '" + player.getName() + "'."); - } +// if (CoreConfig.USER_DEBUG_ENABLED.get()) { +// new Throwable().printStackTrace(); +// this.plugin.warn("Main thread user data load for '" + uuid + "' aka '" + player.getName() + "'."); +// } return user; } } @@ -253,7 +254,7 @@ public abstract class AbstractUserManager

, U extend } public void scheduleSave(@NotNull U user) { - user.setAutoSaveIn(this.config.getScheduledSaveDelay()); + user.setAutoSaveIn(this.config.getSaveDelay()); user.cancelSynchronization(); this.scheduledSaves.put(user.getId(), user); } diff --git a/src/main/java/su/nightexpress/nightcore/database/DataUser.java b/src/main/java/su/nightexpress/nightcore/database/DataUser.java index 527831f..7bc6ce4 100644 --- a/src/main/java/su/nightexpress/nightcore/database/DataUser.java +++ b/src/main/java/su/nightexpress/nightcore/database/DataUser.java @@ -7,6 +7,7 @@ import org.jetbrains.annotations.Nullable; import java.util.UUID; +@Deprecated public interface DataUser { void onLoad(); diff --git a/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java b/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java index a58844c..7e36b72 100644 --- a/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java +++ b/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java @@ -8,9 +8,10 @@ import su.nightexpress.nightcore.util.StringUtil; import java.util.stream.Stream; +@Deprecated public class DatabaseConfig { - private final int saveInterval; + @Deprecated private final int saveInterval; private final int syncInterval; private final DatabaseType databaseType; private final String tablePrefix; @@ -152,6 +153,7 @@ public class DatabaseConfig { return tablePrefix; } + @Deprecated public int getSaveInterval() { return saveInterval; } diff --git a/src/main/java/su/nightexpress/nightcore/database/DatabaseType.java b/src/main/java/su/nightexpress/nightcore/database/DatabaseType.java index c850fcd..df54904 100644 --- a/src/main/java/su/nightexpress/nightcore/database/DatabaseType.java +++ b/src/main/java/su/nightexpress/nightcore/database/DatabaseType.java @@ -1,5 +1,6 @@ package su.nightexpress.nightcore.database; +@Deprecated public enum DatabaseType { MYSQL, diff --git a/src/main/java/su/nightexpress/nightcore/database/UserdataConfig.java b/src/main/java/su/nightexpress/nightcore/database/UserdataConfig.java index 5e6c27d..e7f385a 100644 --- a/src/main/java/su/nightexpress/nightcore/database/UserdataConfig.java +++ b/src/main/java/su/nightexpress/nightcore/database/UserdataConfig.java @@ -5,23 +5,37 @@ import su.nightexpress.nightcore.NightPlugin; import su.nightexpress.nightcore.config.ConfigValue; import su.nightexpress.nightcore.config.FileConfig; +@Deprecated public class UserdataConfig { - private final long scheduledSaveInterval; - private final double scheduledSaveDelay; - private final int scheduledSaveSyncPause; + private final long cacheLifetime; - public UserdataConfig(long scheduledSaveInterval, double scheduledSaveDelay, int scheduledSaveSyncPause) { - this.scheduledSaveInterval = scheduledSaveInterval; - this.scheduledSaveDelay = scheduledSaveDelay; - this.scheduledSaveSyncPause = scheduledSaveSyncPause; + private final long saveInterval; + private final double saveDelay; + private final int saveSyncPause; + + public UserdataConfig(long cacheLifetime, long saveInterval, double saveDelay, int saveSyncPause) { + this.cacheLifetime = cacheLifetime; + this.saveInterval = saveInterval; + this.saveDelay = saveDelay; + this.saveSyncPause = saveSyncPause; } @NotNull public static UserdataConfig read(@NotNull NightPlugin plugin) { FileConfig config = plugin.getConfig(); - long scheduledSaveInterval = ConfigValue.create("Database.UserData.Scheduled_Save_Interval", + long cacheLifetime = ConfigValue.create("Database.UserData.Cache_LifeTime", + 300L, + "Sets cache lifetime for player's data.", + "Data loaded for offline players and data of previously online players will be cached in the memory for that time.", + "When cache is expired, data have to be loaded from the database again.", + "[*] Set to 0 to disable data cache for offline players.", + "[*] Set to -1 for permanent data cache for offline players.", + "[Default is 300 (5 minutes)]" + ).read(config); + + long saveInterval = ConfigValue.create("Database.UserData.Scheduled_Save_Interval", 20L, "Sets how often (in ticks) plugin will attempt to save data of users marked to be saved.", "This will save only users that are 'ready' to save (see 'Scheduled_Save_Delay').", @@ -30,7 +44,7 @@ public class UserdataConfig { "[Default is 20]" ).read(config); - double scheduledSaveDelay = ConfigValue.create("Database.UserData.Scheduled_Save_Delay", + double saveDelay = ConfigValue.create("Database.UserData.Scheduled_Save_Delay", 1D, "Sets scheduled save delay (in seconds) for a user when marked to be saved.", "This means that a user will be saved X seconds later after being marked.", @@ -46,7 +60,7 @@ public class UserdataConfig { "[Default is 1]" ).read(config); - int scheduledSaveSynchronizationPause = ConfigValue.create("Database.UserData.Scheduled_Save_Sync_Pause", + int saveSyncPause = ConfigValue.create("Database.UserData.Scheduled_Save_Sync_Pause", 3, "Sets synchronization delay (in seconds) before the plugin can continue syncing data for a user after its scheduled save.", "When a user marked for saving has been saved, their synchronization will be unlocked but delayed for this value.", @@ -55,27 +69,31 @@ public class UserdataConfig { ).read(config); - return new UserdataConfig(scheduledSaveInterval, scheduledSaveDelay, scheduledSaveSynchronizationPause); + return new UserdataConfig(cacheLifetime, saveInterval, saveDelay, saveSyncPause); } - public long getScheduledSaveInterval() { - return scheduledSaveInterval; + public long getCacheLifetime() { + return this.cacheLifetime; } - public double getScheduledSaveDelay() { - return scheduledSaveDelay; + public long getSaveInterval() { + return this.saveInterval; } - public int getScheduledSaveSyncPause() { - return scheduledSaveSyncPause; + public double getSaveDelay() { + return this.saveDelay; + } + + public int getSaveSyncPause() { + return this.saveSyncPause; } @Override public String toString() { return "UserdataConfig{" + - "scheduledSaveInterval=" + scheduledSaveInterval + - ", scheduledSaveDelay=" + scheduledSaveDelay + - ", scheduledSaveSyncPause=" + scheduledSaveSyncPause + + "scheduledSaveInterval=" + saveInterval + + ", scheduledSaveDelay=" + saveDelay + + ", scheduledSaveSyncPause=" + saveSyncPause + '}'; } } diff --git a/src/main/java/su/nightexpress/nightcore/database/connection/MySQLConnector.java b/src/main/java/su/nightexpress/nightcore/database/connection/MySQLConnector.java index 59782c1..f42f33c 100644 --- a/src/main/java/su/nightexpress/nightcore/database/connection/MySQLConnector.java +++ b/src/main/java/su/nightexpress/nightcore/database/connection/MySQLConnector.java @@ -5,6 +5,7 @@ import su.nightexpress.nightcore.NightCorePlugin; import su.nightexpress.nightcore.database.AbstractConnector; import su.nightexpress.nightcore.database.DatabaseConfig; +@Deprecated public class MySQLConnector extends AbstractConnector { public MySQLConnector(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) { diff --git a/src/main/java/su/nightexpress/nightcore/database/connection/SQLiteConnector.java b/src/main/java/su/nightexpress/nightcore/database/connection/SQLiteConnector.java index 6749698..4a4da56 100644 --- a/src/main/java/su/nightexpress/nightcore/database/connection/SQLiteConnector.java +++ b/src/main/java/su/nightexpress/nightcore/database/connection/SQLiteConnector.java @@ -5,6 +5,7 @@ import su.nightexpress.nightcore.NightCorePlugin; import su.nightexpress.nightcore.database.AbstractConnector; import su.nightexpress.nightcore.database.DatabaseConfig; +@Deprecated public class SQLiteConnector extends AbstractConnector { public SQLiteConnector(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) { diff --git a/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java b/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java index 4f1a13a..a5385d9 100644 --- a/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java +++ b/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java @@ -6,13 +6,13 @@ import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.NightDataPlugin; -import su.nightexpress.nightcore.core.CoreConfig; +import su.nightexpress.nightcore.database.AbstractUserManager; import su.nightexpress.nightcore.database.DataUser; import su.nightexpress.nightcore.manager.AbstractListener; -import su.nightexpress.nightcore.database.AbstractUserManager; import java.util.UUID; +@Deprecated public class UserListener

, U extends DataUser> extends AbstractListener

{ private final AbstractUserManager, U> userManager; @@ -31,9 +31,9 @@ public class UserListener

, U extends DataUser> exte if (!this.userManager.isCreated(uuid)) { user = this.userManager.createUserData(uuid, event.getName()); plugin.getData().addUser(user); - if (CoreConfig.USER_DEBUG_ENABLED.get()) { + //if (CoreConfig.USER_DEBUG_ENABLED.get()) { plugin.info("Created new data for: '" + uuid + "'"); - } + //} } else user = this.userManager.getUserData(uuid); diff --git a/src/main/java/su/nightexpress/nightcore/database/serialize/ItemStackSerializer.java b/src/main/java/su/nightexpress/nightcore/database/serialize/ItemStackSerializer.java index c514967..c17f23c 100644 --- a/src/main/java/su/nightexpress/nightcore/database/serialize/ItemStackSerializer.java +++ b/src/main/java/su/nightexpress/nightcore/database/serialize/ItemStackSerializer.java @@ -6,6 +6,7 @@ import su.nightexpress.nightcore.util.ItemNbt; import java.lang.reflect.Type; +@Deprecated public class ItemStackSerializer implements JsonSerializer, JsonDeserializer { @Override diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLColumn.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLColumn.java index b3a5b65..c0c316f 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLColumn.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLColumn.java @@ -4,6 +4,7 @@ import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.database.DatabaseType; import su.nightexpress.nightcore.database.sql.column.ColumnType; +@Deprecated public class SQLColumn { private final String name; @@ -33,6 +34,7 @@ public class SQLColumn { } @NotNull + @Deprecated public SQLColumn asLowerCase() { String name = "LOWER(" + this.getName() + ")"; @@ -49,6 +51,12 @@ public class SQLColumn { return this.nameEscaped; } + @NotNull + public String getNameLowercase() { + return "LOWER(" + this.getName() + ")"; + } + + @NotNull public ColumnType getType() { return type; diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLCondition.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLCondition.java index af832ad..508726c 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLCondition.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLCondition.java @@ -2,6 +2,7 @@ package su.nightexpress.nightcore.database.sql; import org.jetbrains.annotations.NotNull; +@Deprecated public class SQLCondition { private final SQLValue value; diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLExecutor.java index 586b25f..ad62d19 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLExecutor.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLExecutor.java @@ -3,6 +3,7 @@ package su.nightexpress.nightcore.database.sql; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.database.AbstractConnector; +@Deprecated public abstract class SQLExecutor { protected final String table; diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java index e92f459..b4eea43 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java @@ -9,6 +9,7 @@ import java.sql.*; import java.util.*; import java.util.function.Function; +@Deprecated public class SQLQueries { public static boolean hasTable(@NotNull AbstractConnector connector, @NotNull String table) { diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLUtils.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLUtils.java index 7b7d039..07e10b9 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLUtils.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLUtils.java @@ -1,7 +1,9 @@ package su.nightexpress.nightcore.database.sql; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.sql.util.WhereOperator; +@Deprecated public class SQLUtils { @NotNull @@ -11,4 +13,14 @@ public class SQLUtils { return "`" + string + "`"; } + + @NotNull + public static String forWhere(@NotNull SQLColumn column, @NotNull WhereOperator operator) { + return column.getNameEscaped() + " " + operator.getLiteral() + " ?"; + } + + @NotNull + public static String forWhereLowercase(@NotNull SQLColumn column, @NotNull WhereOperator operator) { + return column.getNameLowercase() + " " + operator.getLiteral() + " ?"; + } } diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLValue.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLValue.java index 3b8c9e5..dfa0d30 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLValue.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLValue.java @@ -2,6 +2,7 @@ package su.nightexpress.nightcore.database.sql; import org.jetbrains.annotations.NotNull; +@Deprecated public class SQLValue { private final SQLColumn column; diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnFormer.java b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnFormer.java index 976d99f..51842dd 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnFormer.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnFormer.java @@ -3,6 +3,7 @@ package su.nightexpress.nightcore.database.sql.column; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.database.DatabaseType; +@Deprecated public interface ColumnFormer { ColumnFormer STRING = (storageType, length) -> { diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnType.java b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnType.java index 0b8c0b7..6e02336 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnType.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnType.java @@ -2,6 +2,7 @@ package su.nightexpress.nightcore.database.sql.column; import org.jetbrains.annotations.NotNull; +@Deprecated public class ColumnType { public static final ColumnType INTEGER = new ColumnType(ColumnFormer.INTEGER); diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/AlterTableExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/AlterTableExecutor.java index 9348ccc..77c6e4d 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/AlterTableExecutor.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/AlterTableExecutor.java @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +@Deprecated public final class AlterTableExecutor extends SQLExecutor { private final DatabaseType databaseType; diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/CreateTableExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/CreateTableExecutor.java index 34066ec..c20c917 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/CreateTableExecutor.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/CreateTableExecutor.java @@ -13,6 +13,7 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +@Deprecated public final class CreateTableExecutor extends SQLExecutor { private final DatabaseType databaseType; diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java index 17d3502..42bca7e 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java @@ -12,6 +12,7 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +@Deprecated public final class DeleteQueryExecutor extends SQLExecutor { private final List wheres; diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/InsertQueryExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/InsertQueryExecutor.java index 8b47b7d..e71fd4e 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/InsertQueryExecutor.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/InsertQueryExecutor.java @@ -12,6 +12,7 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +@Deprecated public final class InsertQueryExecutor extends SQLExecutor { private final List values; diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/RenameTableExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/RenameTableExecutor.java index 6c4eb8e..5196c25 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/RenameTableExecutor.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/RenameTableExecutor.java @@ -6,6 +6,7 @@ import su.nightexpress.nightcore.database.AbstractConnector; import su.nightexpress.nightcore.database.sql.SQLExecutor; import su.nightexpress.nightcore.database.sql.SQLQueries; +@Deprecated public final class RenameTableExecutor extends SQLExecutor { private final DatabaseType databaseType; diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/SelectQueryExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/SelectQueryExecutor.java index a0cf8ad..21b828b 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/SelectQueryExecutor.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/SelectQueryExecutor.java @@ -11,6 +11,7 @@ import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; +@Deprecated public final class SelectQueryExecutor extends SQLExecutor> { private final List columns; diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/query/AbstractQuery.java b/src/main/java/su/nightexpress/nightcore/database/sql/query/AbstractQuery.java deleted file mode 100644 index 6f65951..0000000 --- a/src/main/java/su/nightexpress/nightcore/database/sql/query/AbstractQuery.java +++ /dev/null @@ -1,25 +0,0 @@ -package su.nightexpress.nightcore.database.sql.query; - -import org.jetbrains.annotations.NotNull; -import su.nightexpress.nightcore.database.sql.SQLUtils; - -public class AbstractQuery { - - protected final String table; - protected final String sql; - - protected AbstractQuery(@NotNull String table, @NotNull String sql) { - this.table = SQLUtils.escape(table); - this.sql = sql; - } - - @NotNull - public String getTable() { - return table; - } - - @NotNull - public String getSQL() { - return sql; - } -} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateEntity.java b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateEntity.java index f9565db..44a4dcb 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateEntity.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateEntity.java @@ -8,6 +8,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +@Deprecated public class UpdateEntity { private final List columnNames; diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java index 0c51bc6..09f44c4 100644 --- a/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java +++ b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java @@ -10,6 +10,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; +@Deprecated public class UpdateQuery /*extends AbstractQuery*/ { private final List entities; @@ -73,48 +74,4 @@ public class UpdateQuery /*extends AbstractQuery*/ { public List getEntities() { return entities; } - - /*@NotNull - public static UpdateQuery create(@NotNull String table, @NotNull List values) { - return create(table, values, Collections.emptyList()); - } - - @NotNull - public static UpdateQuery create(@NotNull String table, @NotNull List values, @NotNull List conditions) { - List columnNames = new ArrayList<>(); - List columnValues = new ArrayList<>(); - List whereColumns = new ArrayList<>(); - List whereValues = new ArrayList<>(); - - values.forEach(value -> { - columnNames.add(value.getColumn().getNameEscaped() + " = ?"); - columnValues.add(value.getValue()); - }); - - conditions.forEach(condition -> { - whereColumns.add(condition.getColumn().getNameEscaped() + " " + condition.getType().getOperator() + " ?"); - whereValues.add(condition.getValue().getValue()); - }); - - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE ").append(SQLUtils.escape(table)); - builder.append(" SET ").append(String.join(",", columnNames)); - if (!whereColumns.isEmpty()) { - builder.append(" WHERE ").append(String.join(" AND ", whereColumns)); - } - - String sql = builder.toString(); - - return new UpdateQuery(sql, columnValues, whereValues); - } - - @NotNull - public List getValues() { - return values; - } - - @NotNull - public List getWheres() { - return wheres; - }*/ } diff --git a/src/main/java/su/nightexpress/nightcore/db/AbstractDataManager.java b/src/main/java/su/nightexpress/nightcore/db/AbstractDataManager.java new file mode 100644 index 0000000..fce8da9 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/AbstractDataManager.java @@ -0,0 +1,217 @@ +package su.nightexpress.nightcore.db; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.NightPlugin; +import su.nightexpress.nightcore.db.config.DatabaseConfig; +import su.nightexpress.nightcore.db.config.DatabaseType; +import su.nightexpress.nightcore.db.connection.AbstractConnector; +import su.nightexpress.nightcore.db.sql.column.Column; +import su.nightexpress.nightcore.db.sql.query.SQLQueries; +import su.nightexpress.nightcore.db.sql.query.type.AbstractQuery; +import su.nightexpress.nightcore.db.sql.query.impl.DeleteQuery; +import su.nightexpress.nightcore.db.sql.query.impl.InsertQuery; +import su.nightexpress.nightcore.db.sql.query.impl.SelectQuery; +import su.nightexpress.nightcore.db.sql.query.impl.UpdateQuery; +import su.nightexpress.nightcore.manager.AbstractManager; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Function; + +public abstract class AbstractDataManager

extends AbstractManager

{ + + protected final DatabaseConfig config; + protected final AbstractConnector connector; + protected final Gson gson; + + public AbstractDataManager(@NotNull P plugin) { + this(plugin, getDataConfig(plugin)); + } + + public AbstractDataManager(@NotNull P plugin, @NotNull DatabaseConfig config) { + super(plugin); + this.config = config; + this.connector = AbstractConnector.create(plugin, config); + this.gson = this.registerAdapters(new GsonBuilder().setPrettyPrinting()).create(); + } + + @NotNull + protected static DatabaseConfig getDataConfig(@NotNull NightPlugin plugin) { +// DbConfig dataConfig = plugin.getDetails().getDatabaseConfig(); +// if (dataConfig == null) { +// plugin.warn("The plugin didn't have database configuration. Fixing it now..."); +// dataConfig = DbConfig.read(plugin); +// } +// return dataConfig; +// + return DatabaseConfig.read(plugin); + } + + @Override + protected void onLoad() { + if (this.config.getSyncInterval() > 0 && this.getStorageType() != DatabaseType.SQLITE) { + this.addAsyncTask(this::onSynchronize, this.config.getSyncInterval()); + this.plugin.info("Enabled data synchronization with " + config.getSyncInterval() + " seconds interval."); + } + + this.onInitialize(); + + if (this.config.isPurgeEnabled() && this.config.getPurgePeriod() > 0) { + this.onPurge(); + } + } + + @Override + protected void onShutdown() { + this.onClose(); + this.connector.close(); + } + + @NotNull + protected abstract GsonBuilder registerAdapters(@NotNull GsonBuilder builder); + + protected abstract void onInitialize(); + + protected abstract void onClose(); + + public abstract void onSynchronize(); + + public abstract void onPurge(); + + @NotNull + public DatabaseConfig getConfig() { + return this.config; + } + + @NotNull + public DatabaseType getStorageType() { + return this.config.getStorageType(); + } + + @NotNull + public String getTablePrefix() { + return this.config.getTablePrefix(); + } + + @NotNull + public AbstractConnector getConnector() { + return this.connector; + } + + @NotNull + protected final Connection getConnection() throws SQLException { + return this.getConnector().getConnection(); + } + + public void createTable(@NotNull String table, @NotNull List columns) { + SQLQueries.createTable(this.connector, this.getStorageType(), table, columns); + } + + public void renameTable(@NotNull String table, @NotNull String toName) { + SQLQueries.renameTable(this.connector, this.getStorageType(), toName, toName); + } + + public void addColumn(@NotNull String table, @NotNull Column column, @NotNull String defaultValue) { + SQLQueries.addColumn(this.connector, this.getStorageType(), table, column, defaultValue); + } + + public void renameColumn(@NotNull String table, @NotNull Column column, @NotNull String toName) { + SQLQueries.renameColumn(this.connector, table, column, toName); + } + + public void renameColumn(@NotNull String table, @NotNull String column, @NotNull String toName) { + SQLQueries.renameColumn(this.connector, table, column, toName); + } + + public void dropColumn(@NotNull String table, @NotNull Column... columns) { + for (Column column : columns) { + SQLQueries.dropColumn(this.connector, table, column); + } + } + + public void dropColumn(@NotNull String table, @NotNull String... columns) { + for (String column : columns) { + SQLQueries.dropColumn(this.connector, table, column); + } + } + + public boolean hasColumn(@NotNull String table, @NotNull Column column) { + return SQLQueries.hasColumn(this.connector, table, column); + } + + + + public void insert(@NotNull String table, @NotNull InsertQuery query, @NotNull T entity) { + this.executeUpdate(table, query, entity); + } + + public void insert(@NotNull String table, @NotNull InsertQuery query, @NotNull Collection entities) { + this.executeUpdate(table, query, entities); + } + + public void update(@NotNull String table, @NotNull UpdateQuery query, @NotNull T entity) { + this.executeUpdate(table, query, entity); + } + + public void update(@NotNull String table, @NotNull UpdateQuery query, @NotNull Collection entities) { + this.executeUpdate(table, query, entities); + } + + public void delete(@NotNull String table, @NotNull DeleteQuery query, @NotNull T entity) { + this.executeUpdate(table, query, entity); + } + + public void delete(@NotNull String table, @NotNull DeleteQuery query, @NotNull Collection entities) { + this.executeUpdate(table, query, entities); + } + + public void executeUpdate(@NotNull String table, @NotNull AbstractQuery query, @NotNull T entity) { + SQLQueries.executeQuery(this.connector, table, query, entity); + } + + public void executeUpdate(@NotNull String table, @NotNull AbstractQuery query, @NotNull Collection entities) { + SQLQueries.executeQuery(this.connector, table, query, entities); + } + + + + public boolean contains(@NotNull String table, @NotNull Consumer> consumer) { + return this.selectFirst(table, resultSet -> true, consumer) != null; + } + + @Nullable + public T selectFirst(@NotNull String table, @NotNull Function function, @NotNull Consumer> consumer) { + SelectQuery query = new SelectQuery<>(function); + + consumer.accept(query); + + return this.selectFirst(table, query); + } + + @NotNull + public List select(@NotNull String table, @NotNull Function function, @NotNull Consumer> consumer) { + SelectQuery query = new SelectQuery<>(function); + + consumer.accept(query); + + return this.select(table, query); + } + + @Nullable + public T selectFirst(@NotNull String table, @NotNull SelectQuery query) { + List list = this.select(table, query); + return list.isEmpty() ? null : list.get(0); + } + + @NotNull + public List select(@NotNull String table, @NotNull SelectQuery query) { + return SQLQueries.executeSelect(this.connector, table, query); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/AbstractUser.java b/src/main/java/su/nightexpress/nightcore/db/AbstractUser.java new file mode 100644 index 0000000..f430730 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/AbstractUser.java @@ -0,0 +1,147 @@ +package su.nightexpress.nightcore.db; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.TimeUtil; + +import java.util.UUID; + +public abstract class AbstractUser { + + protected final UUID uuid; + + protected String name; + protected long dateCreated; + protected long lastOnline; + protected long cacheExpireTime; + protected long autoSaveTime; + protected long autoSyncTime; + + public AbstractUser(@NotNull UUID uuid, @NotNull String name, long dateCreated, long lastOnline) { + this.uuid = uuid; + this.name = name; + this.setDateCreated(dateCreated); + this.setLastOnline(lastOnline); + + this.setPermanentCache(); + this.disableAutoSave(); + } + + public abstract void onLoad(); + + public abstract void onUnload(); + + + public boolean isCacheExpired() { + return TimeUtil.isPassed(this.cacheExpireTime); + } + + public boolean isAutoSaveReady() { + return TimeUtil.isPassed(this.autoSaveTime); + } + + public boolean isAutoSyncReady() { + return TimeUtil.isPassed(this.autoSyncTime); + } + + + public void setPermanentCache() { + this.setCacheFor(-1); + } + + public void disableAutoSave() { + this.setAutoSaveIn(-1); + } + + public void disableAutoSync() { + this.setAutoSyncIn(-1); + } + + + public long getCacheExpireTime() { + return this.cacheExpireTime; + } + + public void setCacheFor(long seconds) { + this.cacheExpireTime = TimeUtil.createFutureTimestamp(seconds); + } + + + public boolean isAutoSavePlanned() { + return this.autoSaveTime > 0; + } + + public long getAutoSaveTime() { + return this.autoSaveTime; + } + + public void setAutoSaveIn(double seconds) { + this.autoSaveTime = TimeUtil.createFutureTimestamp(seconds); + } + + + public boolean isAutoSyncPlanned() { + return this.autoSyncTime > 0; + } + + public long getAutoSyncTime() { + return this.autoSyncTime; + } + + public void setAutoSyncIn(int seconds) { + this.autoSyncTime = TimeUtil.createFutureTimestamp(seconds); + } + + + @NotNull + public final UUID getId() { + return this.uuid; + } + + @NotNull + public final String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public final long getDateCreated() { + return dateCreated; + } + + public final void setDateCreated(long dateCreated) { + this.dateCreated = dateCreated; + } + + public final long getLastOnline() { + return this.lastOnline; + } + + public final void setLastOnline(long lastOnline) { + this.lastOnline = lastOnline; + } + + public final boolean isOnline() { + return this.getPlayer() != null; + } + + @NotNull + public final OfflinePlayer getOfflinePlayer() { + return Bukkit.getOfflinePlayer(this.getId()); + } + + @Nullable + public final Player getPlayer() { + return Bukkit.getPlayer(this.getId()); + } + + @Override + public String toString() { + return "AbstractUser [uuid=" + this.uuid + ", name=" + this.name + ", lastOnline=" + this.lastOnline + "]"; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/AbstractUserDataManager.java b/src/main/java/su/nightexpress/nightcore/db/AbstractUserDataManager.java new file mode 100644 index 0000000..5126fee --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/AbstractUserDataManager.java @@ -0,0 +1,161 @@ +package su.nightexpress.nightcore.db; + +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.NightPlugin; +import su.nightexpress.nightcore.db.config.DatabaseConfig; +import su.nightexpress.nightcore.db.sql.query.UserQueries; +import su.nightexpress.nightcore.db.sql.column.Column; +import su.nightexpress.nightcore.db.sql.column.ColumnType; +import su.nightexpress.nightcore.db.sql.query.type.ValuedQuery; +import su.nightexpress.nightcore.db.sql.util.WhereOperator; +import su.nightexpress.nightcore.db.sql.query.impl.InsertQuery; +import su.nightexpress.nightcore.db.sql.query.impl.SelectQuery; +import su.nightexpress.nightcore.db.sql.query.impl.UpdateQuery; +import su.nightexpress.nightcore.util.Lists; +import su.nightexpress.nightcore.util.TimeUtil; + +import java.sql.ResultSet; +import java.time.LocalDateTime; +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Function; + +public abstract class AbstractUserDataManager

extends AbstractDataManager

{ + + public static final Column COLUMN_USER_ID = Column.of("uuid", ColumnType.STRING); + public static final Column COLUMN_USER_NAME = Column.of("name", ColumnType.STRING); + public static final Column COLUMN_USER_DATE_CREATED = Column.of("dateCreated", ColumnType.LONG); + public static final Column COLUMN_USER_LAST_ONLINE = Column.of("last_online", ColumnType.LONG); + + protected final String tableUsers; + + protected final Function userFunction; + + public AbstractUserDataManager(@NotNull P plugin) { + this(plugin, getDataConfig(plugin)); + } + + public AbstractUserDataManager(@NotNull P plugin, @NotNull DatabaseConfig config) { + super(plugin, config); + this.tableUsers = this.getTablePrefix() + "_users"; + + this.userFunction = this.createUserFunction(); + } + + @Override + protected void onInitialize() { + this.createUserTable(); + } + + @Override + protected void onClose() { + + } + + @Override + public void onPurge() { + LocalDateTime deadline = LocalDateTime.now().minusDays(this.getConfig().getPurgePeriod()); + long deadlineMs = TimeUtil.toEpochMillis(deadline); + + this.delete(this.tableUsers, UserQueries.deleteByLastOnline(), deadlineMs); + } + + @NotNull + protected abstract Function createUserFunction(); + + protected void createUserTable() { + List columns = new ArrayList<>(); + columns.add(COLUMN_USER_ID); + columns.add(COLUMN_USER_NAME); + columns.add(COLUMN_USER_DATE_CREATED); + columns.add(COLUMN_USER_LAST_ONLINE); + this.addTableColumns(columns); + + this.createTable(this.tableUsers, columns); + } + + protected abstract void addUpsertQueryData(@NotNull ValuedQuery query); + + //protected abstract void addInsertQueryData(@NotNull InsertQuery query); + + //protected abstract void addUpdateQueryData(@NotNull UpdateQuery query); + + protected abstract void addSelectQueryData(@NotNull SelectQuery query); + + protected abstract void addTableColumns(@NotNull List columns); + + @NotNull + public List getUsers() { + return this.select(this.tableUsers, this.userFunction, SelectQuery::all); + } + + @Nullable + public U getUser(@NotNull Player player) { + return this.getUser(player.getUniqueId()); + } + + @Nullable + public final U getUser(@NotNull String name) { + return this.selectUser(query -> query.whereIgnoreCase(COLUMN_USER_NAME, WhereOperator.EQUAL, name.toLowerCase())); + } + + @Nullable + public final U getUser(@NotNull UUID uuid) { + return this.selectUser(query -> query.where(COLUMN_USER_ID, WhereOperator.EQUAL, uuid.toString())); + } + + private U selectUser(@NotNull Consumer> consumer) { + SelectQuery query = new SelectQuery<>(this.userFunction); + query.column(COLUMN_USER_ID); + query.column(COLUMN_USER_NAME); + query.column(COLUMN_USER_LAST_ONLINE); + query.column(COLUMN_USER_DATE_CREATED); + this.addSelectQueryData(query); + + consumer.accept(query); + + return this.selectFirst(this.tableUsers, query); + } + + public boolean isUserExists(@NotNull String name) { + return this.contains(this.tableUsers, query -> query + .column(COLUMN_USER_NAME) + .whereIgnoreCase(COLUMN_USER_NAME, WhereOperator.EQUAL, name.toLowerCase()) + ); + } + + public boolean isUserExists(@NotNull UUID uuid) { + return this.contains(this.tableUsers, query -> query + .column(COLUMN_USER_ID) + .where(COLUMN_USER_ID, WhereOperator.EQUAL, uuid.toString()) + ); + } + + public void saveUser(@NotNull U user) { + this.saveUsers(Lists.newList(user)); + } + + public void saveUsers(@NotNull Collection users) { + UpdateQuery query = UserQueries.update(); + this.addUpsertQueryData(query); + + this.update(this.tableUsers, query, users); + } + + public void insertUser(@NotNull U user) { + InsertQuery query = UserQueries.insert(); + this.addUpsertQueryData(query); + + this.insert(this.tableUsers, query, user); + } + + public void deleteUser(@NotNull U user) { + this.deleteUser(user.getId()); + } + + public void deleteUser(@NotNull UUID userId) { + this.delete(this.tableUsers, UserQueries.deleteByUUID(), userId); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/AbstractUserManager.java b/src/main/java/su/nightexpress/nightcore/db/AbstractUserManager.java new file mode 100644 index 0000000..cf4c1da --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/AbstractUserManager.java @@ -0,0 +1,332 @@ +package su.nightexpress.nightcore.db; + +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.NightPlugin; +import su.nightexpress.nightcore.db.config.UserdataConfig; +import su.nightexpress.nightcore.db.listener.UserListener; +import su.nightexpress.nightcore.manager.AbstractManager; +import su.nightexpress.nightcore.util.Players; + +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +public abstract class AbstractUserManager

extends AbstractManager

{ + + private final UserdataConfig config; + private final AbstractUserDataManager dataManager; + + private final Map loadedByIdMap; + private final Map loadedByNameMap; + + public AbstractUserManager(@NotNull P plugin, @NotNull AbstractUserDataManager dataManager) { + super(plugin); + this.config = UserdataConfig.read(plugin); + this.dataManager = dataManager; + this.loadedByIdMap = new ConcurrentHashMap<>(); + this.loadedByNameMap = new ConcurrentHashMap<>(); + } + + @Override + protected void onLoad() { + this.addListener(new UserListener<>(this.plugin, this)); + this.addAsyncTask(this::saveScheduled, this.config.getSaveInterval()); + this.addAsyncTask(this::unloadExpired, this.config.getCacheCleanupInterval()); + + this.plugin.onPostLoad(this::loadOnline); + } + + @Override + protected void onShutdown() { + this.saveLoaded(); + this.loadedByIdMap.clear(); + this.loadedByNameMap.clear(); + } + + public void loadOnline() { + //plugin.debug("Load data for online players"); + Players.getOnline().forEach(player -> { + U user = this.getOrFetch(player.getUniqueId()); + if (user != null) this.cachePermanent(user); + }); + } + + public void unloadExpired() { + this.getLoaded().forEach(user -> { + if (user.isCacheExpired() && !user.isOnline()) { + this.unload(user); + //plugin.debug("Unloaded expired cached: " + user.getName()); + } + }); + } + + public final void handleJoin(@NotNull Player player) { + U user = this.getLoaded(player); + if (user == null) return; + + this.cachePermanent(user); + } + + public final void handleQuit(@NotNull Player player) { + U user = this.getLoaded(player.getUniqueId()); + if (user == null) return; + + user.setName(player.getName()); + user.setLastOnline(System.currentTimeMillis()); + + this.plugin.runTaskAsync(task -> this.saveInDatabase(user)); + this.cacheTemporary(user); + } + + public void saveScheduled() { + Set users = this.getLoaded().stream().filter(AbstractUser::isAutoSaveReady).collect(Collectors.toCollection(HashSet::new)); + if (users.isEmpty()) return; + + this.dataManager.saveUsers(users); + //this.plugin.debug("Saved " + users.size() + " users"); + + users.forEach(user -> { + user.disableAutoSave(); // Reset autosave timestamp. + user.setAutoSyncIn(this.config.getSaveSyncPause()); // Unlock synchronization only when all data was pushed to the database. + }); + } + + public void saveLoaded() { + this.dataManager.saveUsers(this.getLoaded()); + } + + public void save(@NotNull Player player) { + U user = this.getLoaded(player.getUniqueId()); + if (user == null) return; + + this.save(user); + } + + public void save(@NotNull U user) { + user.setAutoSaveIn(this.config.getSaveDelay()); + user.disableAutoSync(); + } + + private void load(@NotNull U user) { + user.onLoad(); + this.cacheTemporary(user); + } + + private void unload(@NotNull U user) { + user.onUnload(); + + this.loadedByIdMap.remove(user.getId()); + this.loadedByNameMap.remove(user.getName().toLowerCase()); + } + + @NotNull + public abstract U create(@NotNull UUID uuid, @NotNull String name); + + public void cacheTemporary(@NotNull U user) { + user.setCacheFor(this.config.getCacheLifetime()); + this.cache(user); + //this.plugin.debug("Temp user cache: " + user.getName()); + } + + public void cachePermanent(@NotNull U user) { + user.setPermanentCache(); + this.cache(user); + //this.plugin.debug("Permanent user cache: " + user.getName()); + } + + private void cache(@NotNull U user) { + this.loadedByIdMap.putIfAbsent(user.getId(), user); + this.loadedByNameMap.putIfAbsent(user.getName().toLowerCase(), user); + } + + public boolean isInDatabase(@NotNull String name) { + return this.dataManager.isUserExists(name); + } + + public boolean isInDatabase(@NotNull UUID uuid) { + return this.dataManager.isUserExists(uuid); + } + + public void addInDatabase(@NotNull U user) { + this.dataManager.insertUser(user); + } + + public void saveInDatabase(@NotNull U user) { + this.dataManager.saveUser(user); + } + + @Nullable + public U getFromDatabase(@NotNull String name) { + return this.dataManager.getUser(name); + } + + @Nullable + public U getFromDatabase(@NotNull UUID uuid) { + return this.dataManager.getUser(uuid); + } + + @NotNull + public final U getOrFetch(@NotNull Player player) { + UUID uuid = player.getUniqueId(); + + U user = this.getLoaded(uuid); + if (user != null) return user; + + if (Players.isReal(player)) { + user = this.getOrFetch(uuid); + if (user != null) { + //new Throwable().printStackTrace(); + this.plugin.warn("Main thread user data load for '" + uuid + "' aka '" + player.getName() + "'."); + return user; + } + } + + return this.create(uuid, player.getName()); + } + + @Nullable + public final U getOrFetch(@NotNull String name) { + U user = this.getLoaded(name); + if (user != null) return user; + + user = this.getFromDatabase(name); + if (user != null) { + //this.plugin.debug("Loaded from DB by Name: " + user.getName()); + this.load(user); + } + + return user; + } + + @Nullable + public final U getOrFetch(@NotNull UUID uuid) { + U user = this.getLoaded(uuid); + if (user != null) return user; + + user = this.getFromDatabase(uuid); + if (user != null) { + //this.plugin.debug("Loaded from DB by UUID: " + user.getName()); + this.load(user); + } + + return user; + } + + public final CompletableFuture getUserDataAsync(@NotNull String name) { + return CompletableFuture.supplyAsync(() -> this.getOrFetch(name)); + } + + public final CompletableFuture getUserDataAsync(@NotNull UUID uuid) { + return CompletableFuture.supplyAsync(() -> this.getOrFetch(uuid)); + } + + /** + * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation in async CompletableFuture thread. + * @param name Name of a player. + */ + public void manageUser(@NotNull String name, Consumer consumer) { + this.manageUser(() -> this.getLoaded(name), () -> this.getUserDataAsync(name), consumer); + } + + /** + * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation in async CompletableFuture thread. + * @param playerId UUID of a player. + */ + public void manageUser(@NotNull UUID playerId, Consumer consumer) { + this.manageUser(() -> this.getLoaded(playerId), () -> this.getUserDataAsync(playerId), consumer); + } + + /** + * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation next tick in the main thread. + * @param name Name of a player. + */ + public void manageUserSynchronized(@NotNull String name, Consumer consumer) { + this.manageUserSynchronized(() -> this.getLoaded(name), () -> this.getUserDataAsync(name), consumer); + } + + /** + * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation next tick in the main thread. + * @param playerId UUID of a player. + */ + public void manageUserSynchronized(@NotNull UUID playerId, Consumer consumer) { + this.manageUserSynchronized(() -> this.getLoaded(playerId), () -> this.getUserDataAsync(playerId), consumer); + } + + private void manageUser(@NotNull Supplier loadedSupplier, @NotNull Supplier> fetchSupplier, @NotNull Consumer consumer) { + U user = loadedSupplier.get(); + if (user != null) { + consumer.accept(user); + } + else fetchSupplier.get().thenAccept(consumer); + } + + private void manageUserSynchronized(@NotNull Supplier loadedSupplier, @NotNull Supplier> fetchSupplier, @NotNull Consumer consumer) { + this.manageUser(loadedSupplier, fetchSupplier, user -> this.plugin.runTask(task -> consumer.accept(user))); + } + + /** + * @return Fetches all users from the database and returns them in as a single set.
+ * Users that are already loaded won't be replaced by ones from the database, however they will be fetched anyway. + */ + @NotNull + public Set getAll() { + Set users = this.getLoaded(); + this.dataManager.getUsers().stream().filter(user -> !this.isLoaded(user.getId())).forEach(users::add); + return users; + } + + @NotNull + public Set getLoaded() { + return new HashSet<>(this.loadedByIdMap.values()); + } + + @NotNull + public Map getLoadedByIdMap() { + return this.loadedByIdMap; + } + + @NotNull + public Map getLoadedByNameMap() { + return this.loadedByNameMap; + } + + @Nullable + public U getLoaded(@NotNull Player player) { + return this.getLoaded(player.getUniqueId()); + } + + @Nullable + public U getLoaded(@NotNull UUID uuid) { + return this.loadedByIdMap.get(uuid); + } + + @Nullable + public U getLoaded(@NotNull String name) { + return this.loadedByNameMap.get(name.toLowerCase()); + } + + public boolean isLoaded(@NotNull Player player) { + return this.isLoaded(player.getUniqueId()); + } + + public boolean isLoaded(@NotNull UUID id) { + return this.loadedByIdMap.containsKey(id); + } + + public boolean isLoaded(@NotNull String name) { + return this.loadedByNameMap.containsKey(name.toLowerCase()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/config/DatabaseConfig.java b/src/main/java/su/nightexpress/nightcore/db/config/DatabaseConfig.java new file mode 100644 index 0000000..36eee5a --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/config/DatabaseConfig.java @@ -0,0 +1,187 @@ +package su.nightexpress.nightcore.db.config; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightPlugin; +import su.nightexpress.nightcore.config.ConfigValue; +import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.util.StringUtil; + +import java.util.stream.Stream; + +public class DatabaseConfig { + + private final int syncInterval; + private final DatabaseType databaseType; + private final String tablePrefix; + private final boolean purgeEnabled; + private final int purgePeriod; + + private final String username; + private final String password; + private final String host; + private final String database; + private final String urlOptions; + + private final String filename; + + public DatabaseConfig( + int syncInterval, + @NotNull DatabaseType databaseType, + @NotNull String tablePrefix, + boolean purgeEnabled, + int purgePeriod, + + @NotNull String username, + @NotNull String password, + @NotNull String host, + @NotNull String database, + @NotNull String urlOptions, + + @NotNull String filename + ) { + this.syncInterval = syncInterval; + this.databaseType = databaseType; + this.tablePrefix = tablePrefix; + this.purgeEnabled = purgeEnabled; + this.purgePeriod = purgePeriod; + + this.username = username; + this.password = password; + this.host = host; + this.database = database; + this.urlOptions = urlOptions; + + this.filename = filename; + } + + @NotNull + public static DatabaseConfig read(@NotNull NightPlugin plugin) { + String defPrefix = StringUtil.lowerCaseUnderscore(plugin.getName()); + return read(plugin.getConfig(), defPrefix); + } + + @NotNull + public static DatabaseConfig read(@NotNull FileConfig config, @NotNull String defaultPrefix) { + return read(config, defaultPrefix, "data.db"); + } + + @NotNull + public static DatabaseConfig read(@NotNull FileConfig config, @NotNull String defaultPrefix, @NotNull String defFileName) { + String path = "Database."; + + DatabaseType databaseType = ConfigValue.create(path + "Type", DatabaseType.class, DatabaseType.SQLITE, + "Sets database type.", + "Available values: " + String.join(",", Stream.of(DatabaseType.values()).map(Enum::name).toList())) + .read(config); + + int syncInterval = ConfigValue.create(path + "Sync_Interval", -1, + "Sets how often (in seconds) plugin data will be fetched and loaded from the remote database.", + "Useless for " + DatabaseType.SQLITE.name() + ".", + "Set to '-1' to disable.") + .read(config); + + String tablePrefix = ConfigValue.create(path + "Table_Prefix", defaultPrefix, + "Custom prefix for plugin tables in database.") + .read(config); + + String mysqlUser = ConfigValue.create(path + "MySQL.Username", "root", + "Database user name.") + .read(config); + + String mysqlPassword = ConfigValue.create(path + "MySQL.Password", "root", + "Database password.") + .read(config); + + String mysqlHost = ConfigValue.create(path + "MySQL.Host", "localhost:3306", + "Database host. Example: localhost:3306, 127.0.0.1:3306") + .read(config); + + String mysqlBase = ConfigValue.create(path + "MySQL.Database", "minecraft", + "Name of the MySQL database where plugin will create tables.") + .read(config); + + String urlOptions = ConfigValue.create(path + "MySQL.Options", + "?allowPublicKeyRetrieval=true&useSSL=false", + "Connection options. Do not touch unless you know what you're doing." + ).read(config); + + String sqliteFilename = ConfigValue.create(path + "SQLite.FileName", defFileName, + "File name for the SQLite database file.", + "Actually it's a path to the file, so you can use directories here.") + .read(config); + + + path = "Database.Purge."; + boolean purgeEnabled = ConfigValue.create(path + "Enabled", false, + "Enables the purge feature.", + "Purge will remove all records from the plugin tables that are 'old' enough.") + .read(config); + + int purgePeriod = ConfigValue.create(path + "For_Period", 60, + "Sets maximal 'age' for the database records before they will be purged.", + "This option may have different behavior depends on the plugin.", + "By default it's days of inactivity for the plugin users.") + .read(config); + + return new DatabaseConfig(syncInterval, + databaseType, tablePrefix, + purgeEnabled, purgePeriod, + + mysqlUser, mysqlPassword, mysqlHost, mysqlBase, urlOptions, + + sqliteFilename + ); + } + + @NotNull + public DatabaseType getStorageType() { + return databaseType; + } + + @NotNull + public String getTablePrefix() { + return tablePrefix; + } + + public int getSyncInterval() { + return syncInterval; + } + + public boolean isPurgeEnabled() { + return purgeEnabled; + } + + public int getPurgePeriod() { + return purgePeriod; + } + + @NotNull + public String getUsername() { + return username; + } + + @NotNull + public String getPassword() { + return password; + } + + @NotNull + public String getHost() { + return host; + } + + @NotNull + public String getDatabase() { + return database; + } + + @NotNull + public String getUrlOptions() { + return urlOptions; + } + + @NotNull + public String getFilename() { + return filename; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/config/DatabaseType.java b/src/main/java/su/nightexpress/nightcore/db/config/DatabaseType.java new file mode 100644 index 0000000..0e7642a --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/config/DatabaseType.java @@ -0,0 +1,7 @@ +package su.nightexpress.nightcore.db.config; + +public enum DatabaseType { + + MYSQL, + SQLITE, +} diff --git a/src/main/java/su/nightexpress/nightcore/db/config/UserdataConfig.java b/src/main/java/su/nightexpress/nightcore/db/config/UserdataConfig.java new file mode 100644 index 0000000..66f6302 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/config/UserdataConfig.java @@ -0,0 +1,112 @@ +package su.nightexpress.nightcore.db.config; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightPlugin; +import su.nightexpress.nightcore.config.ConfigValue; +import su.nightexpress.nightcore.config.FileConfig; + +public class UserdataConfig { + + private final long cacheLifetime; + private final int cacheCleanupInterval; + + private final long saveInterval; + private final double saveDelay; + private final int saveSyncPause; + + public UserdataConfig(long cacheLifetime, int cacheCleanupInterval, long saveInterval, double saveDelay, int saveSyncPause) { + this.cacheLifetime = cacheLifetime; + this.cacheCleanupInterval = cacheCleanupInterval; + this.saveInterval = saveInterval; + this.saveDelay = saveDelay; + this.saveSyncPause = saveSyncPause; + } + + @NotNull + public static UserdataConfig read(@NotNull NightPlugin plugin) { + FileConfig config = plugin.getConfig(); + + long cacheLifetime = ConfigValue.create("Database.UserData.Cache.LifeTime", + 300L, + "Sets cache lifetime for player's data.", + "Data loaded for offline players and data of previously online players will be cached in the memory for that time.", + "When cache is expired, data have to be loaded from the database again.", + "[*] Set to 0 to disable data cache for offline players.", + "[*] Set to -1 for permanent data cache for offline players.", + "[Default is 300 (5 minutes)]" + ).read(config); + + int cacheCleanupInterval = ConfigValue.create("Database.UserData.Cache.CleanUp_Interval", + 300, + "Sets how often (in seconds) plugin will clean up user data cache.", + "Cache contains data loaded for offline players and data of previously online players", + "[*] Set to -1 to disable cache clean up and keep user data loaded until reboot.", + "[Default is 300 (5 minutes)]" + ).read(config); + + long saveInterval = ConfigValue.create("Database.UserData.Scheduled_Save_Interval", + 20L, + "Sets how often (in ticks) plugin will attempt to save data of users marked to be saved.", + "This will save only users that are 'ready' to save (see 'Scheduled_Save_Delay').", + "[DO NOT DISABLE UNDER ANY CIRCUMSTANCES!]", + "[20 ticks = 1 second]", + "[Default is 20]" + ).read(config); + + double saveDelay = ConfigValue.create("Database.UserData.Scheduled_Save_Delay", + 1D, + "Sets scheduled save delay (in seconds) for a user when marked to be saved.", + "This means that a user will be saved X seconds later after being marked.", + "Generally, you should keep this value less than 'Scheduled_Save_Interval' for best results,", + "and not setting it extremely high, otherwise you may result in user data never saved & synchronized.", + "", + "IMPORTANT NOTE #1: When a user is marked for saving, this will prevent them from syncing until saving occurs!", + "IMPORTANT NOTE #2: Every time a user is marked for saving, their save time will be updated with this value!", + "", + "Users marked for save when their data has been changed/affected in some way.", + "However this is higly depends on the plugin.", + "[Decimals allowed]", + "[Default is 1]" + ).read(config); + + int saveSyncPause = ConfigValue.create("Database.UserData.Scheduled_Save_Sync_Pause", + 3, + "Sets synchronization delay (in seconds) before the plugin can continue syncing data for a user after its scheduled save.", + "When a user marked for saving has been saved, their synchronization will be unlocked but delayed for this value.", + "This might be helpful to prevent possible issues when synchronization process access the database before user data was fully saved.", + "[Default is 3]" + ).read(config); + + + return new UserdataConfig(cacheLifetime, cacheCleanupInterval, saveInterval, saveDelay, saveSyncPause); + } + + public long getCacheLifetime() { + return this.cacheLifetime; + } + + public int getCacheCleanupInterval() { + return this.cacheCleanupInterval; + } + + public long getSaveInterval() { + return this.saveInterval; + } + + public double getSaveDelay() { + return this.saveDelay; + } + + public int getSaveSyncPause() { + return this.saveSyncPause; + } + + @Override + public String toString() { + return "UserdataConfig{" + + "scheduledSaveInterval=" + saveInterval + + ", scheduledSaveDelay=" + saveDelay + + ", scheduledSaveSyncPause=" + saveSyncPause + + '}'; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/connection/AbstractConnector.java b/src/main/java/su/nightexpress/nightcore/db/connection/AbstractConnector.java new file mode 100644 index 0000000..7b9841b --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/connection/AbstractConnector.java @@ -0,0 +1,50 @@ +package su.nightexpress.nightcore.db.connection; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightPlugin; +import su.nightexpress.nightcore.db.config.DatabaseConfig; +import su.nightexpress.nightcore.db.config.DatabaseType; +import su.nightexpress.nightcore.db.connection.impl.MySQLConnector; +import su.nightexpress.nightcore.db.connection.impl.SQLiteConnector; + +import java.sql.Connection; +import java.sql.SQLException; + +public abstract class AbstractConnector { + + protected final NightPlugin plugin; + protected final HikariConfig config; + protected final HikariDataSource dataSource; + + public AbstractConnector(@NotNull NightPlugin plugin, @NotNull DatabaseConfig config) { + this.plugin = plugin; + + this.config = new HikariConfig(); + this.config.setJdbcUrl(this.getURL(config)); + this.setupConfig(config); + this.config.addDataSourceProperty("cachePrepStmts", "true"); + this.config.addDataSourceProperty("prepStmtCacheSize", "250"); + this.config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + this.dataSource = new HikariDataSource(this.config); + } + + @NotNull + public static AbstractConnector create(@NotNull NightPlugin plugin, @NotNull DatabaseConfig config) { + return config.getStorageType() == DatabaseType.SQLITE ? new SQLiteConnector(plugin, config) : new MySQLConnector(plugin, config); + } + + protected abstract String getURL(@NotNull DatabaseConfig config); + + protected abstract void setupConfig(@NotNull DatabaseConfig config); + + public void close() { + this.dataSource.close(); + } + + @NotNull + public final Connection getConnection() throws SQLException { + return this.dataSource.getConnection(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/connection/impl/MySQLConnector.java b/src/main/java/su/nightexpress/nightcore/db/connection/impl/MySQLConnector.java new file mode 100644 index 0000000..5774455 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/connection/impl/MySQLConnector.java @@ -0,0 +1,28 @@ +package su.nightexpress.nightcore.db.connection.impl; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightPlugin; +import su.nightexpress.nightcore.db.config.DatabaseConfig; +import su.nightexpress.nightcore.db.connection.AbstractConnector; + +public class MySQLConnector extends AbstractConnector { + + public MySQLConnector(@NotNull NightPlugin plugin, @NotNull DatabaseConfig config) { + super(plugin, config); + } + + @Override + protected String getURL(@NotNull DatabaseConfig config) { + String host = config.getHost(); + String database = config.getDatabase(); + String options = config.getUrlOptions(); + + return "jdbc:mysql://" + host + "/" + database + options; + } + + @Override + protected void setupConfig(@NotNull DatabaseConfig config) { + this.config.setUsername(config.getUsername()); + this.config.setPassword(config.getPassword()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/connection/impl/SQLiteConnector.java b/src/main/java/su/nightexpress/nightcore/db/connection/impl/SQLiteConnector.java new file mode 100644 index 0000000..781d002 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/connection/impl/SQLiteConnector.java @@ -0,0 +1,24 @@ +package su.nightexpress.nightcore.db.connection.impl; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightPlugin; +import su.nightexpress.nightcore.db.config.DatabaseConfig; +import su.nightexpress.nightcore.db.connection.AbstractConnector; + +public class SQLiteConnector extends AbstractConnector { + + public SQLiteConnector(@NotNull NightPlugin plugin, @NotNull DatabaseConfig config) { + super(plugin, config); + } + + @Override + protected String getURL(@NotNull DatabaseConfig config) { + String filePath = plugin.getDataFolder().getAbsolutePath() + "/" + config.getFilename(); + return "jdbc:sqlite:" + filePath; + } + + @Override + protected void setupConfig(@NotNull DatabaseConfig config) { + this.config.setMaximumPoolSize(1); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/listener/UserListener.java b/src/main/java/su/nightexpress/nightcore/db/listener/UserListener.java new file mode 100644 index 0000000..d4e4155 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/listener/UserListener.java @@ -0,0 +1,50 @@ +package su.nightexpress.nightcore.db.listener; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.player.AsyncPlayerPreLoginEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightPlugin; +import su.nightexpress.nightcore.db.AbstractUser; +import su.nightexpress.nightcore.db.AbstractUserManager; +import su.nightexpress.nightcore.manager.AbstractListener; + +import java.util.UUID; + +public class UserListener

extends AbstractListener

{ + + private final AbstractUserManager manager; + + public UserListener(@NotNull P plugin, @NotNull AbstractUserManager manager) { + super(plugin); + this.manager = manager; + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onUserLogin(AsyncPlayerPreLoginEvent event) { + if (event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) return; + + UUID uuid = event.getUniqueId(); + if (!this.manager.isInDatabase(uuid)) { + U user = this.manager.create(uuid, event.getName()); + this.manager.addInDatabase(user); + this.manager.cacheTemporary(user); + //this.plugin.debug("Created new data for: '" + uuid + "'"); + return; + } + + this.manager.getOrFetch(uuid); // Fetch and cache temporary. + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onUserQuit(PlayerJoinEvent event) { + this.manager.handleJoin(event.getPlayer()); // Get loaded and cache permanent. + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onUserQuit(PlayerQuitEvent event) { + this.manager.handleQuit(event.getPlayer()); // Get loaded and cache temporary. + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/column/Column.java b/src/main/java/su/nightexpress/nightcore/db/sql/column/Column.java new file mode 100644 index 0000000..cec6be3 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/column/Column.java @@ -0,0 +1,57 @@ +package su.nightexpress.nightcore.db.sql.column; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.config.DatabaseType; +import su.nightexpress.nightcore.db.sql.util.SQLUtils; + +public class Column { + + private final String name; + private final ColumnType type; + private final int length; + + public Column(@NotNull String name, @NotNull ColumnType type, int length) { + this.name = name; + this.type = type; + this.length = length; + } + + @NotNull + public String formatType(@NotNull DatabaseType databaseType) { + return this.type.build(databaseType, this.length); + } + + @NotNull + public static Column of(@NotNull String name, @NotNull ColumnType type) { + return Column.of(name, type, -1); + } + + @NotNull + public static Column of(@NotNull String name, @NotNull ColumnType type, int length) { + return new Column(name, type, length); + } + + @NotNull + public String getName() { + return this.name; + } + + @NotNull + public String getNameEscaped() { + return SQLUtils.escape(this.name); + } + + @NotNull + public String getNameLowercase() { + return "LOWER(" + this.name + ")"; + } + + @NotNull + public ColumnType getType() { + return this.type; + } + + public int getLength() { + return this.length; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/column/ColumnType.java b/src/main/java/su/nightexpress/nightcore/db/sql/column/ColumnType.java new file mode 100644 index 0000000..e468216 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/column/ColumnType.java @@ -0,0 +1,35 @@ +package su.nightexpress.nightcore.db.sql.column; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.config.DatabaseType; + +public interface ColumnType { + + ColumnType STRING = (type, length) -> { + if (length < 1 || type == DatabaseType.SQLITE) { + return type == DatabaseType.SQLITE ? "TEXT NOT NULL" : "MEDIUMTEXT NOT NULL"; + } + return "varchar(" + length + ") CHARACTER SET utf8 NOT NULL"; + }; + + ColumnType INTEGER = (type, length) -> { + if (length < 1 || type == DatabaseType.SQLITE) { + return "INTEGER NOT NULL"; + } + return "int(" + length + ") NOT NULL"; + }; + + ColumnType DOUBLE = (type, length) -> { + return type == DatabaseType.SQLITE ? "REAL NOT NULL" : "double NOT NULL"; + }; + + ColumnType LONG = (type, length) -> { + return length < 1 || type == DatabaseType.SQLITE ? "BIGINT NOT NULL" : "bigint(" + length + ") NOT NULL"; + }; + + ColumnType BOOLEAN = (type, length) -> { + return type == DatabaseType.SQLITE ? "INTEGER NOT NULL" : "tinyint(1) NOT NULL"; + }; + + @NotNull String build(@NotNull DatabaseType type, int length); +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/QueryValue.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/QueryValue.java new file mode 100644 index 0000000..dc16c86 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/QueryValue.java @@ -0,0 +1,31 @@ +package su.nightexpress.nightcore.db.sql.query; + +import org.jetbrains.annotations.NotNull; + +import java.util.function.Function; + +public class QueryValue { + + private final String sqlPart; + private final Function statementPart; + + public QueryValue(String sqlPart, Function statementPart) { + this.sqlPart = sqlPart; + this.statementPart = statementPart; + } + + @NotNull + public String getSQLPart() { + return this.sqlPart; + } + + @NotNull + public String getStatementPart(T entity) { + return this.statementPart.apply(entity); + } + + @NotNull + public Function getStatementPart() { + return this.statementPart; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/SQLQueries.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/SQLQueries.java new file mode 100644 index 0000000..ea499b5 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/SQLQueries.java @@ -0,0 +1,200 @@ +package su.nightexpress.nightcore.db.sql.query; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.config.DatabaseType; +import su.nightexpress.nightcore.db.connection.AbstractConnector; +import su.nightexpress.nightcore.db.connection.impl.SQLiteConnector; +import su.nightexpress.nightcore.db.sql.column.Column; +import su.nightexpress.nightcore.db.sql.column.ColumnType; +import su.nightexpress.nightcore.db.sql.query.type.AbstractQuery; +import su.nightexpress.nightcore.db.sql.query.impl.SelectQuery; +import su.nightexpress.nightcore.db.sql.util.SQLUtils; +import su.nightexpress.nightcore.util.Lists; + +import java.sql.*; +import java.util.*; +import java.util.stream.Collectors; + +public class SQLQueries { + + public static boolean hasTable(@NotNull AbstractConnector connector, @NotNull String table) { + try (Connection connection = connector.getConnection()) { + + boolean has; + DatabaseMetaData metaData = connection.getMetaData(); + ResultSet tables = metaData.getTables(null, null, table, null); + has = tables.next(); + tables.close(); + return has; + } + catch (SQLException exception) { + exception.printStackTrace(); + return false; + } + } + + public static boolean hasColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull Column column) { + return hasColumn(connector, table, column.getName()); + } + + public static boolean hasColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull String columnName) { + String sql = "SELECT * FROM " + table; + try (Connection connection = connector.getConnection(); + Statement statement = connection.createStatement()) { + + ResultSet resultSet = statement.executeQuery(sql); + ResultSetMetaData metaData = resultSet.getMetaData(); + int columns = metaData.getColumnCount(); + for (int index = 1; index <= columns; index++) { + if (columnName.equals(metaData.getColumnName(index))) { + return true; + } + } + return false; + } + catch (SQLException exception) { + exception.printStackTrace(); + return false; + } + } + + public static void addColumn(@NotNull AbstractConnector connector, + @NotNull DatabaseType type, + @NotNull String table, + @NotNull Column column, + @NotNull String defVal) { + if (SQLQueries.hasColumn(connector, table, column)) return; + + StringBuilder builder = new StringBuilder() + .append("ALTER TABLE ").append(table).append(" ADD ") + .append(column.getName()).append(" ").append(column.formatType(type)); + + if (connector instanceof SQLiteConnector || column.getType() != ColumnType.STRING) { + builder.append(" DEFAULT ").append("'").append(defVal).append("'"); + } + + SQLQueries.executeSimpleQuery(connector, builder.toString()); + } + + public static void renameColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull Column column, @NotNull String toName) { + renameColumn(connector, table, column.getName(), toName); + } + + public static void renameColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull String columnName, @NotNull String toName) { + if (!SQLQueries.hasColumn(connector, table, columnName)) return; + + String sql = "ALTER TABLE " + table + " RENAME COLUMN " + columnName + " TO " + toName; + + SQLQueries.executeSimpleQuery(connector, sql); + } + + public static void dropColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull Column column) { + dropColumn(connector, table, column.getName()); + } + + public static void dropColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull String columnName) { + if (!SQLQueries.hasColumn(connector, table, columnName)) return; + + String sql = "ALTER TABLE " + table + " DROP COLUMN " + columnName; + + SQLQueries.executeSimpleQuery(connector, sql); + } + + public static void createTable(@NotNull AbstractConnector connector, @NotNull DatabaseType type, @NotNull String table, @NotNull List columns) { + if (columns.isEmpty()) return; + + StringBuilder idBuilder = new StringBuilder(SQLUtils.escape("id")).append(" ").append(ColumnType.INTEGER.build(type, 11)); + + if (type == DatabaseType.SQLITE) { + idBuilder.append(" PRIMARY KEY AUTOINCREMENT"); + } + else { + idBuilder.append(" PRIMARY KEY AUTO_INCREMENT"); + } + + String columnNames = columns.stream() + .map(column -> column.getNameEscaped() + " " + column.formatType(type)).collect(Collectors.joining(", ")); + + String allColumns = idBuilder + ", " + columnNames; + + String sql = "CREATE TABLE IF NOT EXISTS " + table + "(" + allColumns + ");"; + + SQLQueries.executeSimpleQuery(connector, sql); + } + + public static void renameTable(@NotNull AbstractConnector connector, @NotNull DatabaseType type, @NotNull String table, @NotNull String toName) { + if (!SQLQueries.hasTable(connector, table)) return; + + StringBuilder sql = new StringBuilder(); + if (type == DatabaseType.MYSQL) { + sql.append("RENAME TABLE ").append(table).append(" TO ").append(toName).append(";"); + } + else { + sql.append("ALTER TABLE ").append(table).append(" RENAME TO ").append(toName); + } + SQLQueries.executeSimpleQuery(connector, sql.toString()); + } + + public static void executeSimpleQuery(@NotNull AbstractConnector connector, @NotNull String sql) { + try (Connection connection = connector.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql)) { + + //System.out.println("simpleQuery: " + statement.toString()); + + statement.executeUpdate(); + } + catch (SQLException exception) { + exception.printStackTrace(); + } + } + + public static void executeQuery(@NotNull AbstractConnector connector, @NotNull String table, @NotNull AbstractQuery query, @NotNull T entity) { + executeQuery(connector, table, query, Lists.newList(entity)); + } + + public static void executeQuery(@NotNull AbstractConnector connector, @NotNull String table, @NotNull AbstractQuery query, @NotNull Collection entities) { + if (query.isEmpty()) return; + + String sql = query.createSQL(table); + + try (Connection connection = connector.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql)) { + + int entityCount = 0; + for (T entity : entities) { + query.onExecute(statement, entity); + //System.out.println("myQuery: " + statement); + statement.addBatch(); + entityCount++; + + if (entityCount % 500 == 0 || entityCount == entities.size()) { + statement.executeBatch(); + } + } + } + catch (SQLException exception) { + exception.printStackTrace(); + } + } + + @NotNull + public static List executeSelect(@NotNull AbstractConnector connector, @NotNull String table, @NotNull SelectQuery query) { + ArrayList list = new ArrayList<>(); + + if (query.isEmpty()) return list; + + String sql = query.createSQL(table); + + try (Connection connection = connector.getConnection(); + PreparedStatement statement = connection.prepareStatement(sql)) { + + query.onExecute(statement, list); + //System.out.println("selectQuery: " + statement); + } + catch (SQLException exception) { + exception.printStackTrace(); + } + + return list; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/UserQueries.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/UserQueries.java new file mode 100644 index 0000000..edec5ee --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/UserQueries.java @@ -0,0 +1,42 @@ +package su.nightexpress.nightcore.db.sql.query; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.AbstractUser; +import su.nightexpress.nightcore.db.AbstractUserDataManager; +import su.nightexpress.nightcore.db.sql.util.WhereOperator; +import su.nightexpress.nightcore.db.sql.query.impl.DeleteQuery; +import su.nightexpress.nightcore.db.sql.query.impl.InsertQuery; +import su.nightexpress.nightcore.db.sql.query.impl.UpdateQuery; + +import java.util.UUID; + +public class UserQueries { + + @NotNull + public static DeleteQuery deleteByLastOnline() { + return new DeleteQuery().where(AbstractUserDataManager.COLUMN_USER_LAST_ONLINE, WhereOperator.SMALLER, String::valueOf); + } + + @NotNull + public static DeleteQuery deleteByUUID() { + return new DeleteQuery().where(AbstractUserDataManager.COLUMN_USER_ID, WhereOperator.EQUAL, String::valueOf); + } + + @NotNull + public static UpdateQuery update() { + return new UpdateQuery() + .setValue(AbstractUserDataManager.COLUMN_USER_NAME, AbstractUser::getName) + .setValue(AbstractUserDataManager.COLUMN_USER_DATE_CREATED, user -> String.valueOf(user.getDateCreated())) + .setValue(AbstractUserDataManager.COLUMN_USER_LAST_ONLINE, user -> String.valueOf(user.getLastOnline())) + .where(AbstractUserDataManager.COLUMN_USER_ID, WhereOperator.EQUAL, user -> user.getId().toString()); + } + + @NotNull + public static InsertQuery insert() { + return new InsertQuery() + .setValue(AbstractUserDataManager.COLUMN_USER_ID, user -> user.getId().toString()) + .setValue(AbstractUserDataManager.COLUMN_USER_NAME, AbstractUser::getName) + .setValue(AbstractUserDataManager.COLUMN_USER_DATE_CREATED, user -> String.valueOf(user.getDateCreated())) + .setValue(AbstractUserDataManager.COLUMN_USER_LAST_ONLINE, user -> String.valueOf(user.getLastOnline())); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/DeleteQuery.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/DeleteQuery.java new file mode 100644 index 0000000..df4b244 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/DeleteQuery.java @@ -0,0 +1,46 @@ +package su.nightexpress.nightcore.db.sql.query.impl; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.sql.query.type.ConditionalQuery; + +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public class DeleteQuery extends ConditionalQuery, T> { + + public DeleteQuery() { + + } + + @Override + protected DeleteQuery getThis() { + return this; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + @NotNull + protected String buildSQL(@NotNull String table) { + StringBuilder builder = new StringBuilder().append("DELETE FROM ").append(table); + + String wheres = this.buildWhereSQLPart(); + if (!wheres.isBlank()) { + builder.append(" WHERE ").append(wheres); + } + + return builder.toString(); + } + + @Override + public void onExecute(@NotNull PreparedStatement statement, @NotNull T entity) throws SQLException { + int paramCount = 1; + + for (int index = 0; index < this.countWhereColumns(); index++) { + statement.setString(paramCount++, this.getWhereValue(entity, index)); + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/InsertQuery.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/InsertQuery.java new file mode 100644 index 0000000..46afc89 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/InsertQuery.java @@ -0,0 +1,62 @@ +package su.nightexpress.nightcore.db.sql.query.impl; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.sql.column.Column; +import su.nightexpress.nightcore.db.sql.query.type.AbstractQuery; +import su.nightexpress.nightcore.db.sql.query.QueryValue; +import su.nightexpress.nightcore.db.sql.query.type.ValuedQuery; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class InsertQuery extends AbstractQuery implements ValuedQuery, T> { + + private final List> columns; + + public InsertQuery() { + this.columns = new ArrayList<>(); + } + + @Override + public boolean isEmpty() { + return this.columns.isEmpty(); + } + + @Override + public void onExecute(@NotNull PreparedStatement statement, @NotNull T entity) throws SQLException { + int paramCount = 1; + + for (int index = 0; index < this.countValues(); index++) { + statement.setString(paramCount++, this.getValue(entity, index)); + } + } + + @Override + @NotNull + protected String buildSQL(@NotNull String table) { + String columns = this.columns.stream().map(QueryValue::getSQLPart).collect(Collectors.joining(",")); + String values = this.columns.stream().map(value -> "?").collect(Collectors.joining(",")); + + return "INSERT INTO " + table + " (" + columns + ")" + " VALUES(" + values + ")"; + } + + @Override + @NotNull + public InsertQuery setValue(@NotNull Column column, @NotNull Function function) { + this.columns.add(new QueryValue<>(column.getNameEscaped(), function)); + return this; + } + + public int countValues() { + return this.columns.size(); + } + + @NotNull + public String getValue(@NotNull T entity, int index) { + return this.columns.get(index).getStatementPart(entity); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/SelectQuery.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/SelectQuery.java new file mode 100644 index 0000000..ef71ca5 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/SelectQuery.java @@ -0,0 +1,99 @@ +package su.nightexpress.nightcore.db.sql.query.impl; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.sql.column.Column; +import su.nightexpress.nightcore.db.sql.query.type.ConditionalQuery; +import su.nightexpress.nightcore.db.sql.util.WhereOperator; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +public class SelectQuery extends ConditionalQuery, ArrayList> { + + private final List columns; + private final Function dataFunction; + + private int amount; + + public SelectQuery(@NotNull Function dataFunction) { + this.columns = new ArrayList<>(); + this.dataFunction = dataFunction; + this.amount = -1; + } + + @Override + protected SelectQuery getThis() { + return this; + } + + @Override + public boolean isEmpty() { + return this.columns.isEmpty(); + } + + @Override + @NotNull + protected String buildSQL(@NotNull String table) { + String columns = String.join(",", this.columns); + String wheres = this.buildWhereSQLPart(); + + return "SELECT " + columns + " FROM " + table + (wheres.isEmpty() ? "" : " WHERE " + wheres); + } + + @Override + public void onExecute(@NotNull PreparedStatement statement, @NotNull ArrayList list) throws SQLException { + int paramCount = 1; + + for (int index = 0; index < this.countWhereColumns(); index++) { + statement.setString(paramCount++, this.getWhereValue(index)); + } + + ResultSet resultSet = statement.executeQuery(); + while (resultSet.next() && (this.amount < 0 || list.size() < this.amount)) { + T object = this.dataFunction.apply(resultSet); + if (object == null) continue; + + list.add(object); + } + + resultSet.close(); + } + + @NotNull + public SelectQuery limit(int amount) { + this.amount = Math.abs(amount); + return this; + } + + @NotNull + public SelectQuery all() { + this.columns.clear(); + this.columns.add("*"); + return this; + } + + @NotNull + public SelectQuery column(@NotNull Column column) { + this.columns.add(column.getNameEscaped()); + return this; + } + + @NotNull + public SelectQuery where(@NotNull Column column, @NotNull WhereOperator operator, @NotNull String value) { + return super.where(column, operator, obj -> value); + } + + @NotNull + public SelectQuery whereIgnoreCase(@NotNull Column column, @NotNull WhereOperator operator, @NotNull String value) { + return super.whereIgnoreCase(column, operator, obj -> value); + } + + @NotNull + public String getWhereValue(int index) { + return this.whereColumns.get(index).getStatementPart(null); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/UpdateQuery.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/UpdateQuery.java new file mode 100644 index 0000000..be2ca2d --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/impl/UpdateQuery.java @@ -0,0 +1,77 @@ +package su.nightexpress.nightcore.db.sql.query.impl; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.sql.column.Column; +import su.nightexpress.nightcore.db.sql.query.type.ConditionalQuery; +import su.nightexpress.nightcore.db.sql.query.QueryValue; +import su.nightexpress.nightcore.db.sql.query.type.ValuedQuery; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class UpdateQuery extends ConditionalQuery, T> implements ValuedQuery, T> { + + private final List> dataColumns; + + public UpdateQuery() { + this.dataColumns = new ArrayList<>(); + } + + @Override + protected UpdateQuery getThis() { + return this; + } + + @Override + public boolean isEmpty() { + return this.dataColumns.isEmpty(); + } + + @Override + public void onExecute(@NotNull PreparedStatement statement, @NotNull T entity) throws SQLException { + int paramCount = 1; + + for (int index = 0; index < this.countDataColumns(); index++) { + statement.setString(paramCount++, this.getColumnValue(entity, index)); + } + + for (int index = 0; index < this.countWhereColumns(); index++) { + statement.setString(paramCount++, this.getWhereValue(entity, index)); + } + } + + @Override + @NotNull + protected String buildSQL(@NotNull String table) { + String columns = this.dataColumns.stream().map(QueryValue::getSQLPart).collect(Collectors.joining(",")); + String wheres = this.buildWhereSQLPart(); + + StringBuilder builder = new StringBuilder(); + builder.append("UPDATE ").append(table); + builder.append(" SET ").append(columns); + if (!wheres.isBlank()) { + builder.append(" WHERE ").append(wheres); + } + return builder.toString(); + } + + @Override + @NotNull + public UpdateQuery setValue(@NotNull Column column, @NotNull Function function) { + this.dataColumns.add(new QueryValue<>(column.getNameEscaped() + " = ?", function)); + return this; + } + + public int countDataColumns() { + return this.dataColumns.size(); + } + + @NotNull + public String getColumnValue(@NotNull T entity, int index) { + return this.dataColumns.get(index).getStatementPart(entity); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/type/AbstractQuery.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/type/AbstractQuery.java new file mode 100644 index 0000000..c9a4f92 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/type/AbstractQuery.java @@ -0,0 +1,22 @@ +package su.nightexpress.nightcore.db.sql.query.type; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.sql.util.SQLUtils; + +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public abstract class AbstractQuery { + + @NotNull + public String createSQL(@NotNull String table) { + return this.buildSQL(SQLUtils.escape(table)); + } + + public abstract boolean isEmpty(); + + public abstract void onExecute(@NotNull PreparedStatement statement, @NotNull T entity) throws SQLException; + + @NotNull + protected abstract String buildSQL(@NotNull String table); +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/type/ConditionalQuery.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/type/ConditionalQuery.java new file mode 100644 index 0000000..aa78c3a --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/type/ConditionalQuery.java @@ -0,0 +1,49 @@ +package su.nightexpress.nightcore.db.sql.query.type; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.sql.util.SQLUtils; +import su.nightexpress.nightcore.db.sql.column.Column; +import su.nightexpress.nightcore.db.sql.query.QueryValue; +import su.nightexpress.nightcore.db.sql.util.WhereOperator; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; + +public abstract class ConditionalQuery, T> extends AbstractQuery { + + protected final List> whereColumns; + + public ConditionalQuery() { + this.whereColumns = new ArrayList<>(); + } + + protected abstract Q getThis(); + + @NotNull + protected String buildWhereSQLPart() { + return this.whereColumns.stream().map(QueryValue::getSQLPart).collect(Collectors.joining(" AND ")); + } + + @NotNull + public Q where(@NotNull Column column, @NotNull WhereOperator operator, @NotNull Function function) { + this.whereColumns.add(new QueryValue<>(SQLUtils.forWhere(column, operator), function)); + return this.getThis(); + } + + @NotNull + public Q whereIgnoreCase(@NotNull Column column, @NotNull WhereOperator operator, @NotNull Function function) { + this.whereColumns.add(new QueryValue<>(SQLUtils.forWhereLowercase(column, operator), function.andThen(String::toLowerCase))); + return this.getThis(); + } + + public int countWhereColumns() { + return this.whereColumns.size(); + } + + @NotNull + public String getWhereValue(@NotNull T entity, int index) { + return this.whereColumns.get(index).getStatementPart(entity); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/type/ValuedQuery.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/type/ValuedQuery.java new file mode 100644 index 0000000..14db42d --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/type/ValuedQuery.java @@ -0,0 +1,11 @@ +package su.nightexpress.nightcore.db.sql.query.type; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.sql.column.Column; + +import java.util.function.Function; + +public interface ValuedQuery, T> { + + @NotNull Q setValue(@NotNull Column column, @NotNull Function function); +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/util/SQLUtils.java b/src/main/java/su/nightexpress/nightcore/db/sql/util/SQLUtils.java new file mode 100644 index 0000000..7ff1b94 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/util/SQLUtils.java @@ -0,0 +1,25 @@ +package su.nightexpress.nightcore.db.sql.util; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.db.sql.column.Column; + +public class SQLUtils { + + @NotNull + public static String escape(@NotNull String string) { + if (string.isBlank()) return string; + if (string.charAt(0) == '`') return string; + + return "`" + string + "`"; + } + + @NotNull + public static String forWhere(@NotNull Column column, @NotNull WhereOperator operator) { + return column.getNameEscaped() + " " + operator.getLiteral() + " ?"; + } + + @NotNull + public static String forWhereLowercase(@NotNull Column column, @NotNull WhereOperator operator) { + return column.getNameLowercase() + " " + operator.getLiteral() + " ?"; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/util/WhereOperator.java b/src/main/java/su/nightexpress/nightcore/db/sql/util/WhereOperator.java new file mode 100644 index 0000000..9bb1e47 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/db/sql/util/WhereOperator.java @@ -0,0 +1,24 @@ +package su.nightexpress.nightcore.db.sql.util; + +import org.jetbrains.annotations.NotNull; + +public enum WhereOperator { + + GREATER(">"), + GREATER_OR_EQUAL(">="), + SMALLER("<"), + SMALLER_OR_EQUAL("<="), + EQUAL("="), + NOT_EQUAL("!="); + + private final String literal; + + WhereOperator(@NotNull String literal) { + this.literal = literal; + } + + @NotNull + public String getLiteral() { + return literal; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/dialog/DialogListener.java b/src/main/java/su/nightexpress/nightcore/dialog/DialogListener.java index f7199a3..781b853 100644 --- a/src/main/java/su/nightexpress/nightcore/dialog/DialogListener.java +++ b/src/main/java/su/nightexpress/nightcore/dialog/DialogListener.java @@ -54,7 +54,7 @@ public class DialogListener extends AbstractListener { String text = raw.substring(1); if (text.startsWith(Dialog.VALUES)) { String[] split = text.split(" "); - int page = split.length >= 2 ? NumberUtil.getInteger(split[1], 0) : 0; + int page = split.length >= 2 ? NumberUtil.getIntegerAbs(split[1]) : 0; boolean auto = split.length >= 3 && Boolean.parseBoolean(split[2]); dialog.displaySuggestions(auto, page); return; diff --git a/src/main/java/su/nightexpress/nightcore/dialog/WrappedInput.java b/src/main/java/su/nightexpress/nightcore/dialog/WrappedInput.java index b2fc097..5a466ed 100644 --- a/src/main/java/su/nightexpress/nightcore/dialog/WrappedInput.java +++ b/src/main/java/su/nightexpress/nightcore/dialog/WrappedInput.java @@ -30,7 +30,7 @@ public class WrappedInput { } public int asInt(int def) { - return NumberUtil.getInteger(this.getTextRaw(), def); + return NumberUtil.getIntegerAbs(this.getTextRaw(), def); } public int asAnyInt(int def) { @@ -42,7 +42,7 @@ public class WrappedInput { } public double asDouble(double def) { - return NumberUtil.getDouble(this.getTextRaw(), def); + return NumberUtil.getDoubleAbs(this.getTextRaw(), def); } @NotNull @@ -53,7 +53,7 @@ public class WrappedInput { @NotNull public UniDouble asUniDouble(double min, double max) { String[] split = this.getTextRaw().split(" "); - return UniDouble.of(NumberUtil.getDouble(split[0], min), NumberUtil.getDouble(split.length >= 2 ? split[1] : split[0], max)); + return UniDouble.of(NumberUtil.getDoubleAbs(split[0], min), NumberUtil.getDoubleAbs(split.length >= 2 ? split[1] : split[0], max)); } @NotNull diff --git a/src/main/java/su/nightexpress/nightcore/integration/VaultHook.java b/src/main/java/su/nightexpress/nightcore/integration/VaultHook.java index b6055ef..3dcada1 100644 --- a/src/main/java/su/nightexpress/nightcore/integration/VaultHook.java +++ b/src/main/java/su/nightexpress/nightcore/integration/VaultHook.java @@ -3,14 +3,13 @@ package su.nightexpress.nightcore.integration; import net.milkbowl.vault.chat.Chat; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.permission.Permission; -import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.event.server.ServiceRegisterEvent; import org.bukkit.plugin.RegisteredServiceProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import su.nightexpress.nightcore.util.Plugins; +import su.nightexpress.nightcore.NightCore; import java.util.Collections; import java.util.Set; @@ -19,11 +18,14 @@ import java.util.stream.Stream; public class VaultHook { + private static NightCore core; private static Economy economy; private static Permission permission; private static Chat chat; - public static void setup() { + public static void load(@NotNull NightCore core) { + VaultHook.core = core; + setPermission(); setEconomy(); setChat(); @@ -33,32 +35,33 @@ public class VaultHook { economy = null; permission = null; chat = null; + core = null; } @Nullable private static T getProvider(@NotNull Class clazz) { - RegisteredServiceProvider provider = Bukkit.getServer().getServicesManager().getRegistration(clazz); + RegisteredServiceProvider provider = core.getServer().getServicesManager().getRegistration(clazz); return provider == null ? null : provider.getProvider(); } private static void setPermission() { permission = getProvider(Permission.class); if (permission != null) { - Plugins.CORE.info("Found permissions provider: " + permission.getName()); + core.info("Found permissions provider: " + permission.getName()); } } private static void setEconomy() { economy = getProvider(Economy.class); if (economy != null) { - Plugins.CORE.info("Found economy provider: " + economy.getName()); + core.info("Found economy provider: " + economy.getName()); } } private static void setChat() { chat = getProvider(Chat.class); if (chat != null) { - Plugins.CORE.info("Found chat provider: " + chat.getName()); + core.info("Found chat provider: " + chat.getName()); } } @@ -77,7 +80,7 @@ public class VaultHook { } public static boolean hasPermissions() { - return getPermissions() != null; + return permission != null; } @Nullable @@ -86,7 +89,7 @@ public class VaultHook { } public static boolean hasChat() { - return getChat() != null; + return chat != null; } @Nullable @@ -95,7 +98,7 @@ public class VaultHook { } public static boolean hasEconomy() { - return getEconomy() != null; + return economy != null; } @Nullable @@ -137,26 +140,46 @@ public class VaultHook { } public static double getBalance(@NotNull Player player) { - return economy.getBalance(player); + return getBalance((OfflinePlayer) player); } public static double getBalance(@NotNull OfflinePlayer player) { return economy.getBalance(player); } + @Deprecated public static boolean addMoney(@NotNull Player player, double amount) { - return addMoney((OfflinePlayer) player, amount); + return deposit((OfflinePlayer) player, amount); } + @Deprecated public static boolean addMoney(@NotNull OfflinePlayer player, double amount) { - return economy.depositPlayer(player, amount).transactionSuccess(); + return deposit(player, amount); } + public static boolean deposit(@NotNull Player player, double amount) { + return deposit((OfflinePlayer) player, amount); + } + + public static boolean deposit(@NotNull OfflinePlayer player, double amount) { + return economy.depositPlayer(player, Math.abs(amount)).transactionSuccess(); + } + + @Deprecated public static boolean takeMoney(@NotNull Player player, double amount) { - return takeMoney((OfflinePlayer) player, amount); + return withdraw((OfflinePlayer) player, amount); } + @Deprecated public static boolean takeMoney(@NotNull OfflinePlayer player, double amount) { + return withdraw(player, Math.abs(amount)); + } + + public static boolean withdraw(@NotNull Player player, double amount) { + return withdraw((OfflinePlayer) player, amount); + } + + public static boolean withdraw(@NotNull OfflinePlayer player, double amount) { return economy.withdrawPlayer(player, Math.abs(amount)).transactionSuccess(); } } diff --git a/src/main/java/su/nightexpress/nightcore/language/LangAssets.java b/src/main/java/su/nightexpress/nightcore/language/LangAssets.java index b49b7b0..8930b6c 100644 --- a/src/main/java/su/nightexpress/nightcore/language/LangAssets.java +++ b/src/main/java/su/nightexpress/nightcore/language/LangAssets.java @@ -24,14 +24,15 @@ public class LangAssets { private static FileConfig config; - public static void load() { - NightCore core = Plugins.CORE; + public static void load(@NotNull NightCore core) { String langCode = core.getLanguage(); String assetsCode = downloadAssets(core, langCode); config = FileConfig.loadOrExtract(core, LangManager.DIR_LANG, getFileName(assetsCode)); - loadDamageTypes(); + if (Version.isAtLeast(Version.MC_1_21)) { + loadDamageTypes(); + } } public static void shutdown() { diff --git a/src/main/java/su/nightexpress/nightcore/language/LangManager.java b/src/main/java/su/nightexpress/nightcore/language/LangManager.java index b5c9603..f4a95dc 100644 --- a/src/main/java/su/nightexpress/nightcore/language/LangManager.java +++ b/src/main/java/su/nightexpress/nightcore/language/LangManager.java @@ -90,8 +90,8 @@ public class LangManager extends SimpleManager { public String getEnum(@NotNull Enum entry) { String path = entry.getDeclaringClass().getSimpleName() + "." + entry.name(); String locEnum = this.config.getString(path); - if (locEnum == null && !this.plugin.isEngine()) { - return Plugins.CORE.getLangManager().getEnum(entry); + if (locEnum == null && Plugins.getCore() != plugin) { + return Plugins.getCore().getLangManager().getEnum(entry); } return locEnum == null ? StringUtil.capitalizeFully(entry.name()) : locEnum; } diff --git a/src/main/java/su/nightexpress/nightcore/language/entry/LangEntry.java b/src/main/java/su/nightexpress/nightcore/language/entry/LangEntry.java index fba687c..73494ad 100644 --- a/src/main/java/su/nightexpress/nightcore/language/entry/LangEntry.java +++ b/src/main/java/su/nightexpress/nightcore/language/entry/LangEntry.java @@ -4,7 +4,7 @@ import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.NightCorePlugin; import su.nightexpress.nightcore.config.FileConfig; -public abstract class LangEntry { +public abstract class LangEntry/**/ { protected final String path; protected final String defaultText; @@ -16,8 +16,8 @@ public abstract class LangEntry { public abstract boolean write(@NotNull FileConfig config); - @NotNull - public abstract T load(@NotNull NightCorePlugin plugin); + //@NotNull + public abstract /*T*/ void load(@NotNull NightCorePlugin plugin); @NotNull public String getPath() { diff --git a/src/main/java/su/nightexpress/nightcore/language/entry/LangItem.java b/src/main/java/su/nightexpress/nightcore/language/entry/LangItem.java index b0a8c09..0303017 100644 --- a/src/main/java/su/nightexpress/nightcore/language/entry/LangItem.java +++ b/src/main/java/su/nightexpress/nightcore/language/entry/LangItem.java @@ -5,7 +5,6 @@ import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.NightCorePlugin; import su.nightexpress.nightcore.config.FileConfig; import su.nightexpress.nightcore.util.ItemUtil; -import su.nightexpress.nightcore.util.Pair; import su.nightexpress.nightcore.util.text.NightMessage; import su.nightexpress.nightcore.util.text.TextRoot; @@ -16,7 +15,7 @@ import java.util.List; import static su.nightexpress.nightcore.util.text.tag.Tags.*; -public class LangItem extends LangEntry>> { +public class LangItem extends LangEntry/*>>*/ { private final List defaultLore; @@ -47,8 +46,7 @@ public class LangItem extends LangEntry>> { } @Override - @NotNull - public Pair> load(@NotNull NightCorePlugin plugin) { + public void load(@NotNull NightCorePlugin plugin) { FileConfig config = plugin.getLang(); this.write(config); @@ -56,7 +54,7 @@ public class LangItem extends LangEntry>> { this.setLocalizedName(config.getString(this.getPath() + ".Name", this.getDefaultName())); this.setLocalizedLore(config.getStringList(this.getPath() + ".Lore")); - return Pair.of(this.getLocalizedName(), this.getLocalizedLore()); + //return Pair.of(this.getLocalizedName(), this.getLocalizedLore()); } public void apply(@NotNull ItemStack item) { diff --git a/src/main/java/su/nightexpress/nightcore/language/entry/LangString.java b/src/main/java/su/nightexpress/nightcore/language/entry/LangString.java index 9213ca7..55a2074 100644 --- a/src/main/java/su/nightexpress/nightcore/language/entry/LangString.java +++ b/src/main/java/su/nightexpress/nightcore/language/entry/LangString.java @@ -6,7 +6,7 @@ import su.nightexpress.nightcore.config.FileConfig; import su.nightexpress.nightcore.util.text.NightMessage; import su.nightexpress.nightcore.util.text.TextRoot; -public class LangString extends LangEntry { +public class LangString extends LangEntry { private String string; private TextRoot message; @@ -31,15 +31,14 @@ public class LangString extends LangEntry { } @Override - @NotNull - public String load(@NotNull NightCorePlugin plugin) { + public void load(@NotNull NightCorePlugin plugin) { FileConfig config = plugin.getLang(); this.write(config); String text = config.getString(this.getPath(), this.getPath()); this.setString(text); - return this.getString(); + //return this.getString(); } @NotNull diff --git a/src/main/java/su/nightexpress/nightcore/language/entry/LangText.java b/src/main/java/su/nightexpress/nightcore/language/entry/LangText.java index b94f762..7f86754 100644 --- a/src/main/java/su/nightexpress/nightcore/language/entry/LangText.java +++ b/src/main/java/su/nightexpress/nightcore/language/entry/LangText.java @@ -10,7 +10,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -public class LangText extends LangEntry { +public class LangText extends LangEntry { private LangMessage message; @@ -40,8 +40,7 @@ public class LangText extends LangEntry { } @Override - @NotNull - public LangMessage load(@NotNull NightCorePlugin plugin) { + public void load(@NotNull NightCorePlugin plugin) { FileConfig config = plugin.getLang(); this.write(config); @@ -53,7 +52,7 @@ public class LangText extends LangEntry { this.setMessage(LangMessage.parse(plugin, String.join(Placeholders.TAG_LINE_BREAK, text))); - return this.getMessage(); + //return this.getMessage(); } @NotNull diff --git a/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java b/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java index 03413e0..98989a1 100644 --- a/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java +++ b/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java @@ -14,6 +14,7 @@ import su.nightexpress.nightcore.util.NumberUtil; import su.nightexpress.nightcore.util.Placeholders; import su.nightexpress.nightcore.util.Players; import su.nightexpress.nightcore.util.StringUtil; +import su.nightexpress.nightcore.util.placeholder.Replacer; import su.nightexpress.nightcore.util.text.NightMessage; import su.nightexpress.nightcore.util.text.TextRoot; import su.nightexpress.nightcore.util.text.tag.Tags; @@ -46,6 +47,7 @@ public class LangMessage { } } + @Deprecated private LangMessage(@NotNull LangMessage from) { this.plugin = from.plugin; this.defaultText = from.defaultText; @@ -176,6 +178,12 @@ public class LangMessage { } @NotNull + public MessageOptions getOptions() { + return this.options; + } + + @NotNull + @Deprecated public TextRoot getMessage(@NotNull CommandSender sender) { if (!this.options.usePlaceholderAPI() || !(sender instanceof Player player)) return this.getMessage(); @@ -183,11 +191,13 @@ public class LangMessage { } @NotNull + @Deprecated public LangMessage replace(@NotNull String var, @NotNull Object replacer) { return this.replace(str -> str.replace(var, String.valueOf(replacer))); } @NotNull + @Deprecated public LangMessage replace(@NotNull String var, @NotNull Consumer> replacer) { List list = new ArrayList<>(); replacer.accept(list); @@ -196,11 +206,13 @@ public class LangMessage { } @NotNull + @Deprecated public LangMessage replace(@NotNull String var, @NotNull List replacer) { return this.replace(str -> str.replace(var, String.join(Placeholders.TAG_LINE_BREAK, replacer))); } @NotNull + @Deprecated public LangMessage replace(@NotNull UnaryOperator replacer) { if (this.isDisabled()) return this; @@ -222,23 +234,60 @@ public class LangMessage { } public void send(@NotNull CommandSender sender) { + this.send(sender, replacer -> {}); +// +// if (this.isDisabled()) return; +// +// if (this.options.getSound() != null && sender instanceof Player player) { +// UniSound.of(this.options.getSound()).play(player); +// } +// +// if (this.options.getOutputType() == OutputType.CHAT) { +// this.getMessage(sender).send(sender); +// return; +// } +// +// if (sender instanceof Player player) { +// if (this.options.getOutputType() == OutputType.ACTION_BAR) { +// Players.sendActionBar(player, this.getMessage(player)); +// } +// else if (this.options.getOutputType() == OutputType.TITLES) { +// String[] split = Tags.LINE_BREAK.split(this.getMessage(sender).getString()); +// +// String title = NightMessage.asLegacy(split[0]); +// String subtitle = split.length >= 2 ? NightMessage.asLegacy(split[1]) : ""; +// +// player.sendTitle(title, subtitle, this.options.getTitleTimes()[0], this.options.getTitleTimes()[1], this.options.getTitleTimes()[2]); +// } +// } + } + + public void send(@NotNull CommandSender sender, @NotNull Consumer consumer) { if (this.isDisabled()) return; if (this.options.getSound() != null && sender instanceof Player player) { UniSound.of(this.options.getSound()).play(player); } + Replacer replacer = new Replacer(); + consumer.accept(replacer); + if (this.options.usePlaceholderAPI() && sender instanceof Player player) { + replacer.replacePlaceholderAPI(player); + } + + TextRoot message = replacer.getReplaced(this.message); + if (this.options.getOutputType() == OutputType.CHAT) { - this.getMessage(sender).send(sender); + message.send(sender); return; } if (sender instanceof Player player) { if (this.options.getOutputType() == OutputType.ACTION_BAR) { - Players.sendActionBar(player, this.getMessage(player)); + Players.sendActionBar(player, message); } else if (this.options.getOutputType() == OutputType.TITLES) { - String[] split = Tags.LINE_BREAK.split(this.getMessage(sender).getString()); + String[] split = Tags.LINE_BREAK.split(message.getString()); String title = NightMessage.asLegacy(split[0]); String subtitle = split.length >= 2 ? NightMessage.asLegacy(split[1]) : ""; diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java index 1f8f3a6..6f9bc9a 100644 --- a/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java +++ b/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java @@ -40,9 +40,9 @@ public class OutputTag extends MessageTag { if (outputType == OutputType.TITLES) { int[] titleTimes = new int[3]; if (split.length >= 4) { - titleTimes[0] = NumberUtil.getInteger(split[1]); + titleTimes[0] = NumberUtil.getIntegerAbs(split[1]); titleTimes[1] = NumberUtil.getAnyInteger(split[2], -1); - titleTimes[2] = NumberUtil.getInteger(split[3]); + titleTimes[2] = NumberUtil.getIntegerAbs(split[3]); } if (titleTimes[1] < 0) titleTimes[1] = Short.MAX_VALUE; diff --git a/src/main/java/su/nightexpress/nightcore/manager/AbstractManager.java b/src/main/java/su/nightexpress/nightcore/manager/AbstractManager.java index a0213d5..d51c8f9 100644 --- a/src/main/java/su/nightexpress/nightcore/manager/AbstractManager.java +++ b/src/main/java/su/nightexpress/nightcore/manager/AbstractManager.java @@ -2,6 +2,7 @@ package su.nightexpress.nightcore.manager; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.NightCorePlugin; +import su.nightexpress.nightcore.util.bukkit.NightTask; import su.nightexpress.nightcore.util.wrapper.UniTask; import java.util.ArrayList; @@ -12,18 +13,22 @@ import java.util.Set; public abstract class AbstractManager

extends SimpleManager

{ protected final Set listeners; - protected final List tasks; + protected final List tasks; + protected final List taskList; public AbstractManager(@NotNull P plugin) { super(plugin); this.listeners = new HashSet<>(); this.tasks = new ArrayList<>(); + this.taskList = new ArrayList<>(); } @Override public void shutdown() { this.tasks.forEach(UniTask::stop); this.tasks.clear(); + this.taskList.forEach(NightTask::stop); + this.taskList.clear(); this.listeners.forEach(SimpeListener::unregisterListeners); this.listeners.clear(); super.shutdown(); @@ -35,8 +40,31 @@ public abstract class AbstractManager

extends SimpleM } } + protected void addTask(@NotNull Runnable runnable, int interval) { + this.addTask(NightTask.create(plugin, runnable, interval)); + } + + protected void addTask(@NotNull Runnable runnable, long interval) { + this.addTask(NightTask.create(plugin, runnable, interval)); + } + + protected void addAsyncTask(@NotNull Runnable runnable, int interval) { + this.addTask(NightTask.createAsync(plugin, runnable, interval)); + } + + protected void addAsyncTask(@NotNull Runnable runnable, long interval) { + this.addTask(NightTask.createAsync(plugin, runnable, interval)); + } + + @Deprecated protected void addTask(@NotNull UniTask task) { this.tasks.add(task); task.start(); } + + protected void addTask(@NotNull NightTask task) { + if (task.isValid()) { + this.taskList.add(task); + } + } } diff --git a/src/main/java/su/nightexpress/nightcore/menu/MenuViewer.java b/src/main/java/su/nightexpress/nightcore/menu/MenuViewer.java index d7575ba..b7a6c30 100644 --- a/src/main/java/su/nightexpress/nightcore/menu/MenuViewer.java +++ b/src/main/java/su/nightexpress/nightcore/menu/MenuViewer.java @@ -5,7 +5,6 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import su.nightexpress.nightcore.util.Version; public class MenuViewer { @@ -30,10 +29,7 @@ public class MenuViewer { public void flushInventory(@NotNull MenuOptions options) { this.inventory.clear(); - - if (Version.isAtLeast(Version.V1_19_R3)) { - this.view.setTitle(options.getTitleFormatted()); - } + //this.view.setTitle(options.getTitleFormatted()); } public boolean hasInventory() { diff --git a/src/main/java/su/nightexpress/nightcore/menu/impl/ConfigMenu.java b/src/main/java/su/nightexpress/nightcore/menu/impl/ConfigMenu.java index b03e62c..bcb7e6e 100644 --- a/src/main/java/su/nightexpress/nightcore/menu/impl/ConfigMenu.java +++ b/src/main/java/su/nightexpress/nightcore/menu/impl/ConfigMenu.java @@ -166,9 +166,10 @@ public abstract class ConfigMenu

extends AbstractMenu if (clickType == null) continue; List commands = cfg.getStringList(path + ".Click_Commands." + sType); + if (commands.isEmpty()) continue; + commandMap.put(clickType, commands); } - commandMap.values().removeIf(List::isEmpty); ClickAction clickCommands = (viewer, event) -> { List commands = commandMap.getOrDefault(ClickType.from(event), Collections.emptyList()); diff --git a/src/main/java/su/nightexpress/nightcore/menu/item/ItemOptions.java b/src/main/java/su/nightexpress/nightcore/menu/item/ItemOptions.java index 448dee6..d61a645 100644 --- a/src/main/java/su/nightexpress/nightcore/menu/item/ItemOptions.java +++ b/src/main/java/su/nightexpress/nightcore/menu/item/ItemOptions.java @@ -11,8 +11,8 @@ import java.util.function.Predicate; public class ItemOptions { - private Predicate visibilityPolicy; - private Predicate weakPolicy; + private Predicate visibilityPolicy; + private Predicate weakPolicy; private BiConsumer displayModifier; public ItemOptions() { diff --git a/src/main/java/su/nightexpress/nightcore/util/BukkitThing.java b/src/main/java/su/nightexpress/nightcore/util/BukkitThing.java index c28a4b3..4d40ae6 100644 --- a/src/main/java/su/nightexpress/nightcore/util/BukkitThing.java +++ b/src/main/java/su/nightexpress/nightcore/util/BukkitThing.java @@ -4,6 +4,7 @@ import org.bukkit.*; import org.bukkit.attribute.Attribute; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.EntityType; +import org.bukkit.generator.WorldInfo; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -16,12 +17,22 @@ import java.util.stream.StreamSupport; public class BukkitThing { + @NotNull + public static List worldNames() { + return Bukkit.getServer().getWorlds().stream().map(WorldInfo::getName).toList(); + } + @Nullable public static T fromRegistry(@NotNull Registry registry, @NotNull String key) { - key = StringUtil.lowerCaseUnderscoreStrict(key); + key = StringUtil.lowerCaseUnderscore(key); - NamespacedKey namespacedKey = NamespacedKey.minecraft(key); - return registry.get(namespacedKey); + try { + NamespacedKey namespacedKey = NamespacedKey.minecraft(key); + return registry.get(namespacedKey); + } + catch (IllegalArgumentException exception) { + return null; + } } @NotNull @@ -70,9 +81,6 @@ public class BukkitThing { @Nullable public static Enchantment getEnchantment(@NotNull String name) { - if (Version.isBehind(Version.V1_19_R3)) { - return Enchantment.getByKey(NamespacedKey.minecraft(StringUtil.lowerCaseUnderscoreStrict(name))); - } return fromRegistry(Registry.ENCHANTMENT, name); } diff --git a/src/main/java/su/nightexpress/nightcore/util/CommandUtil.java b/src/main/java/su/nightexpress/nightcore/util/CommandUtil.java index a06f4f7..962235e 100644 --- a/src/main/java/su/nightexpress/nightcore/util/CommandUtil.java +++ b/src/main/java/su/nightexpress/nightcore/util/CommandUtil.java @@ -25,6 +25,7 @@ public class CommandUtil { return (SimpleCommandMap) Reflex.getFieldValue(Bukkit.getServer(), FIELD_COMMAND_MAP); } + @Deprecated public static void register(@NotNull Plugin plugin, @NotNull NightPluginCommand command) { WrappedCommand wrappedCommand = new WrappedCommand(plugin, command); if (COMMAND_MAP.register(plugin.getName(), wrappedCommand)) { diff --git a/src/main/java/su/nightexpress/nightcore/util/EntityUtil.java b/src/main/java/su/nightexpress/nightcore/util/EntityUtil.java index 112aa9d..3792173 100644 --- a/src/main/java/su/nightexpress/nightcore/util/EntityUtil.java +++ b/src/main/java/su/nightexpress/nightcore/util/EntityUtil.java @@ -11,7 +11,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.NightCore; -import su.nightexpress.nightcore.util.random.Rnd; import java.util.Collections; import java.util.HashMap; @@ -20,11 +19,13 @@ import java.util.concurrent.atomic.AtomicInteger; public class EntityUtil { - public static final EquipmentSlot[] EQUIPMENT_SLOTS = {EquipmentSlot.HAND, EquipmentSlot.OFF_HAND, EquipmentSlot.HEAD, EquipmentSlot.CHEST, EquipmentSlot.LEGS, EquipmentSlot.FEET}; + public static final EquipmentSlot[] EQUIPMENT_SLOTS = { + EquipmentSlot.HAND, EquipmentSlot.OFF_HAND, EquipmentSlot.HEAD, EquipmentSlot.CHEST, EquipmentSlot.LEGS, EquipmentSlot.FEET + }; private static AtomicInteger entityCounter; - public static boolean setupEntityCounter(@NotNull NightCore core) { + public static boolean loadEntityCounter(@NotNull NightCore core) { Class entityClass = Reflex.getClass("net.minecraft.world.entity", "Entity"); if (entityClass == null) { core.error("Could not find NMS Entity class!"); @@ -54,7 +55,7 @@ public class EntityUtil { } public static int nextEntityId() { - return entityCounter == null ? Rnd.nextInt(9999) : entityCounter.incrementAndGet(); + return entityCounter.incrementAndGet(); } public static double getAttribute(@NotNull LivingEntity entity, @NotNull Attribute attribute) { diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java b/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java index 1c8b875..669f67e 100644 --- a/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java +++ b/src/main/java/su/nightexpress/nightcore/util/ItemNbt.java @@ -5,6 +5,8 @@ import com.mojang.datafixers.DataFixer; import com.mojang.serialization.Dynamic; import com.mojang.serialization.DynamicOps; import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -85,7 +87,7 @@ public class ItemNbt { private static boolean useRegistry; private static Object registryAccess; - public static boolean setup(@NotNull NightCore core) { + public static boolean load(@NotNull NightCore core) { if (Version.isBehind(Version.MC_1_20_6)) return true; useRegistry = true; @@ -114,6 +116,21 @@ public class ItemNbt { } } + public static boolean test() { + ItemStack testItem = new ItemStack(Material.DIAMOND_SWORD); + ItemUtil.editMeta(testItem, meta -> { + meta.setDisplayName("Test Item"); + meta.setLore(Lists.newList("Test Lore 1", "Test Lore 2", "Test Lore 3")); + meta.addEnchant(Enchantment.FIRE_ASPECT, 10, true); + }); + + String nbt = ItemNbt.compress(testItem); + if (nbt == null) return false; + + ItemStack decompressed = ItemNbt.decompress(nbt); + return decompressed != null && decompressed.isSimilar(testItem); + } + @Nullable public static String compress(@NotNull ItemStack item) { if (CRAFT_ITEM_STACK_AS_NMS_COPY == null || NBT_IO_WRITE == null) { diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java b/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java index 3321e66..936f37b 100644 --- a/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java +++ b/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java @@ -1,6 +1,5 @@ package su.nightexpress.nightcore.util; -import com.google.common.base.Splitter; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -8,13 +7,15 @@ import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import su.nightexpress.nightcore.language.entry.LangItem; -import su.nightexpress.nightcore.util.placeholder.Placeholder; +import su.nightexpress.nightcore.util.placeholder.PlaceholderList; import su.nightexpress.nightcore.util.placeholder.PlaceholderMap; +import su.nightexpress.nightcore.util.placeholder.Replacer; import su.nightexpress.nightcore.util.text.NightMessage; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.function.Consumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; @@ -23,15 +24,16 @@ public class ItemReplacer { private final ItemStack item; private final ItemMeta meta; - private final PlaceholderMap placeholderCache; - private final List> operatorCache; + //private final PlaceholderMap placeholderCache; + //private final List> operatorCache; + + private final Replacer replacer; private String displayName; private List lore; - private boolean trimLore; + @Deprecated private boolean trimLore; private boolean hideFlags; - //private Player papi; public ItemReplacer(@NotNull ItemStack item) { this(item, item.getItemMeta()); @@ -44,8 +46,9 @@ public class ItemReplacer { public ItemReplacer(@Nullable ItemStack item, @Nullable ItemMeta meta) { this.item = item; this.meta = meta; - this.placeholderCache = new PlaceholderMap(); - this.operatorCache = new ArrayList<>(); + this.replacer = new Replacer(); + //this.placeholderCache = new PlaceholderMap(); + //this.operatorCache = new ArrayList<>(); } @NotNull @@ -79,19 +82,24 @@ public class ItemReplacer { public void writeMeta() { if (!this.hasMeta()) return; - List> operators = new ArrayList<>(this.operatorCache); - operators.add(this.placeholderCache.replacer()); + //List> operators = new ArrayList<>(this.operatorCache); + //operators.add(this.placeholderCache.replacer()); - boolean hasDisplayName = this.displayName != null; + //boolean hasDisplayName = this.displayName != null; //boolean hasLore = this.lore != null; - operators.forEach(operator -> { - if (hasDisplayName) this.setDisplayName(operator.apply(this.displayName)); - this.replaceLore(operator); - //if (hasLore) this.setLore(operator.apply(this.lore)); - }); +// operators.forEach(operator -> { +// if (hasDisplayName) this.setDisplayName(operator.apply(this.displayName)); +// this.replaceLore(operator); +// //if (hasLore) this.setLore(operator.apply(this.lore)); +// }); - this.meta.setDisplayName(this.getDisplayName() == null ? null : NightMessage.asLegacy(this.getDisplayName())); + if (this.displayName != null) { + this.meta.setDisplayName(this.replacer.getReplaced(this.displayName).toLegacy()); + } + this.replacer.getReplacers().forEach(this::replaceLore); + + //this.meta.setDisplayName(this.getDisplayName() == null ? null : NightMessage.asLegacy(this.getDisplayName())); this.meta.setLore(this.packTrimmedLore()); if (this.isHideFlags()) { @@ -102,12 +110,9 @@ public class ItemReplacer { this.item.setItemMeta(this.meta); } - this.placeholderCache.clear(); - this.operatorCache.clear(); - } - - public static void replace(@NotNull ItemStack item, @NotNull UnaryOperator replacer) { - create(item).trimmed().readMeta().replace(replacer).writeMeta(); + //this.placeholderCache.clear(); + //this.operatorCache.clear(); + this.replacer.clear(); } @Deprecated @@ -115,6 +120,7 @@ public class ItemReplacer { create(meta).trimmed().readMeta().replace(replacer).writeMeta(); } + @Deprecated public static void replace(@NotNull ItemStack item, @NotNull PlaceholderMap replacer) { create(item).trimmed().readMeta().replace(replacer).writeMeta(); } @@ -124,15 +130,29 @@ public class ItemReplacer { create(meta).trimmed().readMeta().replace(replacer).writeMeta(); } - public static void replacePlaceholderAPI(@NotNull ItemStack item, @NotNull Player player) { - create(item).trimmed().readMeta().replacePlaceholderAPI(player).writeMeta(); - } - @Deprecated public static void replacePlaceholderAPI(@NotNull ItemMeta meta, @NotNull Player player) { create(meta).trimmed().readMeta().replacePlaceholderAPI(player).writeMeta(); } + public static void replace(@NotNull ItemStack itemStack, @NotNull UnaryOperator operator) { + //create(itemStack).trimmed().readMeta().replace(replacer).writeMeta(); + + create(itemStack).readMeta().replacement(replacer -> replacer.replace(operator)).writeMeta(); + } + + public static void replace(@NotNull ItemStack itemStack, @NotNull PlaceholderList placeholderList, @NotNull T source) { + //create(itemStack).trimmed().readMeta().replace(placeholderList.replacer(source)).writeMeta(); + + create(itemStack).readMeta().replacement(replacer -> replacer.replace(source, placeholderList)).writeMeta(); + } + + public static void replacePlaceholderAPI(@NotNull ItemStack item, @NotNull Player player) { + create(item).readMeta().replacement(replacer -> replacer.replacePlaceholderAPI(player)).writeMeta(); + + //create(item).trimmed().readMeta().replacePlaceholderAPI(player).writeMeta(); + } + public boolean hasMeta() { return this.meta != null; } @@ -141,6 +161,7 @@ public class ItemReplacer { return this.item != null; } + @Deprecated public boolean isTrimLore() { return trimLore; } @@ -150,6 +171,7 @@ public class ItemReplacer { } @NotNull + @Deprecated public ItemReplacer trimmed() { this.setTrimLore(true); return this; @@ -157,63 +179,95 @@ public class ItemReplacer { @NotNull public ItemReplacer hideFlags() { - this.setHideFlags(true); + this.hideFlags = true; return this; } @NotNull + @Deprecated public ItemReplacer setHideFlags(boolean hideFlags) { this.hideFlags = hideFlags; return this; } @NotNull + @Deprecated public ItemReplacer setTrimLore(boolean trimLore) { this.trimLore = trimLore; return this; } @NotNull + @Deprecated private ItemReplacer cachePlaceholder(@NotNull String placeholder, @NotNull Supplier value) { - this.placeholderCache.add(placeholder, value); + this.replacer.replace(placeholder, value); + //this.placeholderCache.add(placeholder, value); return this; } @NotNull + @Deprecated + private ItemReplacer cachePlaceholder(@NotNull String placeholder, @NotNull String value) { + this.replacer.replace(placeholder, value); + //this.placeholderCache.add(placeholder, value); + return this; + } + + @NotNull + @Deprecated private ItemReplacer cacheOperator(@NotNull UnaryOperator operator) { - this.operatorCache.add(operator); + this.replacer.replace(operator); + //this.operatorCache.add(operator); return this; } @NotNull + @Deprecated public ItemReplacer replace(@NotNull String placeholder, @NotNull String value) { - return this.cachePlaceholder(placeholder, () -> value); + return this.cachePlaceholder(placeholder, value); } @NotNull + @Deprecated public ItemReplacer replace(@NotNull String placeholder, @NotNull Supplier value) { return this.cachePlaceholder(placeholder, value); } @NotNull + @Deprecated public ItemReplacer replace(@NotNull String placeholder, @NotNull List replacer) { return this.cacheOperator(str -> str.replace(placeholder, String.join("\n", replacer))); } @NotNull + @Deprecated + public ItemReplacer replace(@NotNull String placeholder, @NotNull PlaceholderList placeholderList, @NotNull T source) { + return this.cacheOperator(placeholderList.replacer(source)); + } + + public ItemReplacer replacement(@NotNull Consumer consumer) { + consumer.accept(this.replacer); + return this; + } + + @NotNull + @Deprecated public ItemReplacer replace(@NotNull PlaceholderMap... placeholderMaps) { for (PlaceholderMap placeholder : placeholderMaps) { - this.placeholderCache.add(placeholder); + //this.placeholderCache.add(placeholder); + this.replacer.replace(placeholder.replacer()); } return this; } @NotNull + @Deprecated public ItemReplacer replace(@NotNull UnaryOperator replacer) { return cacheOperator(replacer); } @NotNull + @Deprecated public ItemReplacer replacePlaceholderAPI(@NotNull Player player) { if (Plugins.hasPlaceholderAPI()) { this.cacheOperator(str -> PlaceholderAPI.setPlaceholders(player, str)); @@ -295,38 +349,38 @@ public class ItemReplacer { lore = Lists.stripEmpty(lore); } - List fixed = fixLore(lore); + List fixed = addEmptyLines(lore); return NightMessage.asLegacy(fixed); } @NotNull - private List fixLore(@NotNull List lore) { + private List addEmptyLines(@NotNull List lore) { for (int index = 0; index < lore.size(); index++) { String line = lore.get(index); if (line.equalsIgnoreCase(Placeholders.EMPTY_IF_ABOVE)) { - if (index == 0 || !this.isNotEmpty(lore.get(index - 1))) { + if (index == 0 || this.isEmpty(lore.get(index - 1))) { lore.remove(index); } else lore.set(index, ""); - return fixLore(lore); + return addEmptyLines(lore); } else if (line.equalsIgnoreCase(Placeholders.EMPTY_IF_BELOW)) { - if (index == lore.size() - 1 || !this.isNotEmpty(lore.get(index + 1))) { + if (index == lore.size() - 1 || this.isEmpty(lore.get(index + 1))) { lore.remove(index); } else lore.set(index, ""); - return fixLore(lore); + return addEmptyLines(lore); } } return lore; } - private boolean isNotEmpty(@NotNull String line) { - return !line.isBlank() && !line.equalsIgnoreCase(Placeholders.EMPTY_IF_ABOVE) && !line.equalsIgnoreCase(Placeholders.EMPTY_IF_BELOW); + private boolean isEmpty(@NotNull String line) { + return line.isBlank() || line.equalsIgnoreCase(Placeholders.EMPTY_IF_ABOVE) || line.equalsIgnoreCase(Placeholders.EMPTY_IF_BELOW); } @Nullable diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java b/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java index 02836c3..56c8f0d 100644 --- a/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java +++ b/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java @@ -2,8 +2,6 @@ package su.nightexpress.nightcore.util; import com.google.gson.JsonElement; import com.google.gson.JsonParser; -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.properties.Property; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Tag; @@ -48,8 +46,11 @@ public class ItemUtil { public static void hideAttributes(@NotNull ItemMeta meta, @NotNull Material material) { if (Version.isAtLeast(Version.MC_1_20_6)) { EquipmentSlot slot = material.getEquipmentSlot(); - material.getDefaultAttributeModifiers(slot).forEach((meta::addAttributeModifier)); - //meta.addAttributeModifier(Attribute.GENERIC_MAX_HEALTH, new AttributeModifier("veryNiceItemChanges", 1, AttributeModifier.Operation.ADD_NUMBER)); + material.getDefaultAttributeModifiers(slot).forEach((attribute, modifier) -> { + if (meta.getAttributeModifiers(attribute) == null) { + meta.addAttributeModifier(attribute, modifier); + } + }); } meta.addItemFlags(ItemFlag.values()); @@ -95,6 +96,7 @@ public class ItemUtil { PlayerProfile profile = Bukkit.createPlayerProfile(uuid, name); URL url = new URL(urlData); PlayerTextures textures = profile.getTextures(); + textures.setSkin(url); profile.setTextures(textures); meta.setOwnerProfile(profile); @@ -123,7 +125,6 @@ public class ItemUtil { @Deprecated public static void setSkullTexture(@NotNull ItemStack item, @NotNull String value) { if (item.getType() != Material.PLAYER_HEAD) return; - //if (!(item.getItemMeta() instanceof SkullMeta meta)) return; try { byte[] decoded = Base64.getDecoder().decode(value); @@ -138,53 +139,6 @@ public class ItemUtil { catch (Exception exception) { exception.printStackTrace(); } - -// UUID uuid = UUID.nameUUIDFromBytes(value.getBytes()); -// GameProfile profile = new GameProfile(uuid, "null"); -// profile.getProperties().put("textures", new Property("textures", value)); -// -// Method method = Reflex.getMethod(meta.getClass(), "setProfile", GameProfile.class); -// if (method != null) { -// Reflex.invokeMethod(method, meta, profile); -// } -// else { -// Reflex.setFieldValue(meta, "profile", profile); -// } -// -// item.setItemMeta(meta); - } - - @Nullable - @Deprecated - public static String getSkullTexture(@NotNull ItemStack item) { - if (item.getType() != Material.PLAYER_HEAD) return null; - - SkullMeta meta = (SkullMeta) item.getItemMeta(); - if (meta == null) return null; - - GameProfile profile = (GameProfile) Reflex.getFieldValue(meta, "profile"); - if (profile == null) return null; - - Collection properties = profile.getProperties().get("textures"); - Optional opt = properties.stream().filter(prop -> { - String name; - if (Version.isAtLeast(Version.V1_20_R2)) { - name = prop.name(); - } - else { - name = (String) Reflex.getFieldValue(profile, "name"); - } - return name != null && name.equalsIgnoreCase("textures"); - }).findFirst(); - - if (opt.isEmpty()) return null; - - if (Version.isAtLeast(Version.V1_20_R2)) { - return opt.get().value(); - } - else { - return (String) Reflex.getFieldValue(opt.get(), "value"); - } } public static boolean isTool(@NotNull ItemStack item) { @@ -200,25 +154,11 @@ public class ItemUtil { } public static boolean isSword(@NotNull ItemStack item) { - if (Version.isAtLeast(Version.V1_19_R3)) { - return Tag.ITEMS_SWORDS.isTagged(item.getType()); - } - - Material material = item.getType(); - return material == Material.DIAMOND_SWORD || material == Material.GOLDEN_SWORD - || material == Material.IRON_SWORD || material == Material.NETHERITE_SWORD - || material == Material.STONE_SWORD || material == Material.WOODEN_SWORD; + return Tag.ITEMS_SWORDS.isTagged(item.getType()); } public static boolean isAxe(@NotNull ItemStack item) { - if (Version.isAtLeast(Version.V1_19_R3)) { - return Tag.ITEMS_AXES.isTagged(item.getType()); - } - - Material material = item.getType(); - return material == Material.DIAMOND_AXE || material == Material.GOLDEN_AXE - || material == Material.IRON_AXE || material == Material.NETHERITE_AXE - || material == Material.STONE_AXE || material == Material.WOODEN_AXE; + return Tag.ITEMS_AXES.isTagged(item.getType()); } public static boolean isTrident(@NotNull ItemStack item) { @@ -226,36 +166,15 @@ public class ItemUtil { } public static boolean isPickaxe(@NotNull ItemStack item) { - if (Version.isAtLeast(Version.V1_19_R3)) { - return Tag.ITEMS_PICKAXES.isTagged(item.getType()); - } - - Material material = item.getType(); - return material == Material.DIAMOND_PICKAXE || material == Material.GOLDEN_PICKAXE - || material == Material.IRON_PICKAXE || material == Material.NETHERITE_PICKAXE - || material == Material.STONE_PICKAXE || material == Material.WOODEN_PICKAXE; + return Tag.ITEMS_PICKAXES.isTagged(item.getType()); } public static boolean isShovel(@NotNull ItemStack item) { - if (Version.isAtLeast(Version.V1_19_R3)) { - return Tag.ITEMS_SHOVELS.isTagged(item.getType()); - } - - Material material = item.getType(); - return material == Material.DIAMOND_SHOVEL || material == Material.GOLDEN_SHOVEL - || material == Material.IRON_SHOVEL || material == Material.NETHERITE_SHOVEL - || material == Material.STONE_SHOVEL || material == Material.WOODEN_SHOVEL; + return Tag.ITEMS_SHOVELS.isTagged(item.getType()); } public static boolean isHoe(@NotNull ItemStack item) { - if (Version.isAtLeast(Version.V1_19_R3)) { - return Tag.ITEMS_HOES.isTagged(item.getType()); - } - - Material material = item.getType(); - return material == Material.DIAMOND_HOE || material == Material.GOLDEN_HOE - || material == Material.IRON_HOE || material == Material.NETHERITE_HOE - || material == Material.STONE_HOE || material == Material.WOODEN_HOE; + return Tag.ITEMS_HOES.isTagged(item.getType()); } public static boolean isElytra(@NotNull ItemStack item) { diff --git a/src/main/java/su/nightexpress/nightcore/util/Lists.java b/src/main/java/su/nightexpress/nightcore/util/Lists.java index bbcd5a6..5081a69 100644 --- a/src/main/java/su/nightexpress/nightcore/util/Lists.java +++ b/src/main/java/su/nightexpress/nightcore/util/Lists.java @@ -1,7 +1,5 @@ package su.nightexpress.nightcore.util; -import org.bukkit.Bukkit; -import org.bukkit.generator.WorldInfo; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -14,8 +12,9 @@ import java.util.stream.Stream; public class Lists { @NotNull + @Deprecated public static List worldNames() { - return Bukkit.getServer().getWorlds().stream().map(WorldInfo::getName).toList(); + return BukkitThing.worldNames(); } public static int indexOf(Object[] array, @NotNull Object objectToFind) { @@ -107,6 +106,7 @@ public class Lists { * @return A list with no multiple empty lines in a row. */ @NotNull + @Deprecated public static List stripEmpty(@NotNull List original) { List stripped = new ArrayList<>(); diff --git a/src/main/java/su/nightexpress/nightcore/util/LocationUtil.java b/src/main/java/su/nightexpress/nightcore/util/LocationUtil.java index 9ca01fe..0eaa858 100644 --- a/src/main/java/su/nightexpress/nightcore/util/LocationUtil.java +++ b/src/main/java/su/nightexpress/nightcore/util/LocationUtil.java @@ -15,6 +15,7 @@ import java.util.Objects; public class LocationUtil { @Nullable + @Deprecated public static String serialize(@NotNull Location location) { World world = location.getWorld(); if (world == null) return null; @@ -23,18 +24,20 @@ public class LocationUtil { } @NotNull + @Deprecated public static List serialize(@NotNull Collection list) { return new ArrayList<>(list.stream().map(LocationUtil::serialize).filter(Objects::nonNull).toList()); } @Nullable + @Deprecated public static Location deserialize(@NotNull String raw) { String[] split = raw.split(","); if (split.length != 6) return null; World world = Bukkit.getWorld(split[5]); if (world == null) { - Plugins.CORE.error("Invalid/Unloaded world for: '" + raw + "' location!"); + Plugins.getCore().error("Invalid/Unloaded world for: '" + raw + "' location!"); return null; } @@ -48,6 +51,7 @@ public class LocationUtil { } @NotNull + @Deprecated public static List deserialize(@NotNull Collection list) { return new ArrayList<>(list.stream().map(LocationUtil::deserialize).filter(Objects::nonNull).toList()); } diff --git a/src/main/java/su/nightexpress/nightcore/util/NumberUtil.java b/src/main/java/su/nightexpress/nightcore/util/NumberUtil.java index 66d03f6..aa69f04 100644 --- a/src/main/java/su/nightexpress/nightcore/util/NumberUtil.java +++ b/src/main/java/su/nightexpress/nightcore/util/NumberUtil.java @@ -2,25 +2,25 @@ package su.nightexpress.nightcore.util; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.core.CoreConfig; -import su.nightexpress.nightcore.core.CoreLang; +import su.nightexpress.nightcore.util.number.CompactNumber; +import su.nightexpress.nightcore.util.number.NumberShortcut; +import su.nightexpress.nightcore.util.wrapper.UniFormatter; import java.math.BigDecimal; -import java.util.Optional; -import java.util.TreeMap; -import java.util.function.Supplier; +import java.util.*; public class NumberUtil { private final static TreeMap ROMAN_MAP = new TreeMap<>(); - private final static TreeMap> NUMERIC_MAP = new TreeMap<>(); + //private final static TreeMap> NUMERIC_MAP = new TreeMap<>(); static { - NUMERIC_MAP.put(0, () -> ""); - NUMERIC_MAP.put(1, CoreLang.NUMBER_SHORT_THOUSAND::getString); - NUMERIC_MAP.put(2, CoreLang.NUMBER_SHORT_MILLION::getString); - NUMERIC_MAP.put(3, CoreLang.NUMBER_SHORT_BILLION::getString); - NUMERIC_MAP.put(4, CoreLang.NUMBER_SHORT_TRILLION::getString); - NUMERIC_MAP.put(5, CoreLang.NUMBER_SHORT_QUADRILLION::getString); +// NUMERIC_MAP.put(0, () -> ""); +// NUMERIC_MAP.put(1, CoreLang.NUMBER_SHORT_THOUSAND::getString); +// NUMERIC_MAP.put(2, CoreLang.NUMBER_SHORT_MILLION::getString); +// NUMERIC_MAP.put(3, CoreLang.NUMBER_SHORT_BILLION::getString); +// NUMERIC_MAP.put(4, CoreLang.NUMBER_SHORT_TRILLION::getString); +// NUMERIC_MAP.put(5, CoreLang.NUMBER_SHORT_QUADRILLION::getString); ROMAN_MAP.put(1000, "M"); ROMAN_MAP.put(900, "CM"); @@ -38,34 +38,128 @@ public class NumberUtil { } @NotNull - public static String format(double value) { - return CoreConfig.NUMBER_FORMAT.get().format(value); + public static UniFormatter getNumberFormat() { + return CoreConfig.NUMBER_FORMAT.get(); } @NotNull - public static String compact(double value) { - Pair pair = formatCompact(value); - return pair.getFirst() + pair.getSecond(); - } - - @NotNull - public static Pair formatCompact(double value) { - boolean negative = false; - if (value < 0) { - value = Math.abs(value); - negative = true; - } - int index = 0; - while ((value / 1000) >= 1 && index < NUMERIC_MAP.size() - 1) { - value = value / 1000; - index++; - } - - return Pair.of(CoreConfig.NUMBER_FORMAT.get().format(negative ? -value : value), NUMERIC_MAP.get(NUMERIC_MAP.floorKey(index)).get()); + public static List getNumberShortcuts() { + return CoreConfig.NUMBER_SHORTCUT_LIST.get().values().stream().sorted(Comparator.comparing(NumberShortcut::getMagnitude)).toList(); } public static double round(double value) { - return new BigDecimal(value).setScale(2, CoreConfig.NUMBER_FORMAT.get().getRounding()).doubleValue(); + return round(value, 2); + } + + public static double round(double value, int scale) { + return new BigDecimal(value).setScale(scale, getNumberFormat().getRounding()).doubleValue(); + } + + @NotNull + public static String format(double value) { + return getNumberFormat().format(value); + } + + @NotNull + @Deprecated + public static String compact(double value) { +// Pair pair = formatCompact(value); +// return pair.getFirst() + pair.getSecond(); + return formatCompact(value); + } + + @NotNull + public static String formatCompact(double value) { + return asCompact(value).format(); + } + +// @NotNull +// public static Pair formatCompact(double value) { +// var compact = getCompact(value); +// return Pair.of(format(compact.getValue()), compact.getShortcut() == null ? "" : compact.getShortcut().getSymbol()); +// boolean negative = false; +// if (value < 0) { +// value = Math.abs(value); +// negative = true; +// } +// +// List shortcuts = getNumberShortcuts(); +// int step = CoreConfig.NUMBER_STEP.get(); +// int index = 0; +// int maxIndex = shortcuts.size() - 1; +// +// while ((value / step) >= 1 && index < maxIndex) { +// value = value / step; +// index++; +// } +// +// return Pair.of(CoreConfig.NUMBER_FORMAT.get().format(negative ? -value : value), NUMERIC_MAP.get(NUMERIC_MAP.floorKey(index)).get()); +// } + + @NotNull + public static CompactNumber asCompact(double value) { + boolean negative = value < 0; + value = Math.abs(value); + + List shortcuts = getNumberShortcuts(); + int step = CoreConfig.NUMBER_SHORTCUT_STEP.get(); + int index = -1; + int maxIndex = shortcuts.size() - 1; + + while ((value / step) >= 1 && index < maxIndex) { + value = value / step; + index++; + } + + double result = negative ? -value : value; + NumberShortcut shortcut = index < 0 ? null : shortcuts.get(index); + + return new CompactNumber(result, shortcut); + } + + public static double getDoubleCompact(@NotNull String input) { + return parseCompact(input).orElse(0D); + } + + public static double getDoubleCompactAbs(@NotNull String input) { + return Math.abs(getDoubleCompact(input)); + } + + public static double getIntCompact(@NotNull String input) { + return parseIntCompact(input).orElse(0); + } + + public static double getIntCompactAbs(@NotNull String input) { + return Math.abs(getIntCompact(input)); + } + + public static Optional parseIntCompact(@NotNull String input) { + return parseCompact(input).map(Double::intValue); + } + + @NotNull + public static Optional parseCompact(@NotNull String input) { + input = input.toLowerCase(); + double multiplier = 1D; + + List shortcuts = getNumberShortcuts(); + + for (NumberShortcut shortcut : shortcuts) { + int index = input.indexOf(shortcut.getSymbol()); + if (index < 0) continue; + + input = input.substring(0, index); + multiplier = shortcut.getMultiplier(); + break; + } + + var optional = parseDouble(input); + if (optional.isEmpty()) return Optional.empty(); + + double value = optional.get() * multiplier; + if (Double.isInfinite(value) || Double.isNaN(value)) return Optional.empty(); + + return Optional.of(value); } @NotNull @@ -79,6 +173,18 @@ public class NumberUtil { return ROMAN_MAP.get(key) + toRoman(number - key); } + public static float clamp(float value, float min, float max) { + return Math.max(min, Math.min(max, value)); + } + + public static int clamp(int value, int min, int max) { + return Math.max(min, Math.min(max, value)); + } + + public static double clamp(double value, double min, double max) { + return Math.max(min, Math.min(max, value)); + } + public static int[] splitIntoParts(int whole, int parts) { int[] arr = new int[parts]; int remain = whole; @@ -92,11 +198,21 @@ public class NumberUtil { return arr; } + @Deprecated public static double getDouble(@NotNull String input) { - return getDouble(input, 0D); + return getDoubleAbs(input); } + @Deprecated public static double getDouble(@NotNull String input, double defaultValue) { + return getDoubleAbs(input, defaultValue); + } + + public static double getDoubleAbs(@NotNull String input) { + return getDoubleAbs(input, 0D); + } + + public static double getDoubleAbs(@NotNull String input, double defaultValue) { return Math.abs(getAnyDouble(input, defaultValue)); } @@ -104,11 +220,21 @@ public class NumberUtil { return parseDouble(input).orElse(defaultValue); } + @Deprecated public static int getInteger(@NotNull String input) { - return getInteger(input, 0); + return getIntegerAbs(input); } + @Deprecated public static int getInteger(@NotNull String input, int defaultValue) { + return getIntegerAbs(input, defaultValue); + } + + public static int getIntegerAbs(@NotNull String input) { + return getIntegerAbs(input, 0); + } + + public static int getIntegerAbs(@NotNull String input, int defaultValue) { return Math.abs(getAnyInteger(input, defaultValue)); } @@ -146,7 +272,8 @@ public class NumberUtil { for (int index = 0; index < split.length; index++) { try { array[index] = Integer.parseInt(split[index].trim()); - } catch (NumberFormatException e) { + } + catch (NumberFormatException exception) { array[index] = 0; } } diff --git a/src/main/java/su/nightexpress/nightcore/util/Pair.java b/src/main/java/su/nightexpress/nightcore/util/Pair.java index 1701b06..d6601a1 100644 --- a/src/main/java/su/nightexpress/nightcore/util/Pair.java +++ b/src/main/java/su/nightexpress/nightcore/util/Pair.java @@ -4,6 +4,7 @@ import org.jetbrains.annotations.NotNull; import java.util.Objects; +@Deprecated public class Pair { private final F first; diff --git a/src/main/java/su/nightexpress/nightcore/util/Placeholders.java b/src/main/java/su/nightexpress/nightcore/util/Placeholders.java index 99ee700..87e6799 100644 --- a/src/main/java/su/nightexpress/nightcore/util/Placeholders.java +++ b/src/main/java/su/nightexpress/nightcore/util/Placeholders.java @@ -1,11 +1,12 @@ package su.nightexpress.nightcore.util; +import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.language.tag.MessageTags; -import su.nightexpress.nightcore.util.placeholder.PlaceholderMap; +import su.nightexpress.nightcore.util.placeholder.PlaceholderList; import su.nightexpress.nightcore.util.text.tag.Tags; import java.util.function.UnaryOperator; @@ -55,31 +56,71 @@ public class Placeholders { public static final String COMMAND_DESCRIPTION = "%command_description%"; public static final String COMMAND_LABEL = "%command_label%"; + public static final PlaceholderList PLAYER = new PlaceholderList() + .add(PLAYER_NAME, Player::getName) + .add(PLAYER_DISPLAY_NAME, Player::getDisplayName); + + public static final PlaceholderList LOCATION = new PlaceholderList() + .add(LOCATION_X, location -> String.valueOf(location.getBlockX())) + .add(LOCATION_Y, location -> String.valueOf(location.getBlockY())) + .add(LOCATION_Z, location -> String.valueOf(location.getBlockZ())) + .add(LOCATION_WORLD, LocationUtil::getWorldName) + ; + + public static final PlaceholderList SENDER = new PlaceholderList() + .add(PLAYER_NAME, CommandSender::getName) + .add(PLAYER_DISPLAY_NAME, CommandSender::getName); + @NotNull public static UnaryOperator forLocation(@NotNull Location location) { - return new PlaceholderMap() - .add(LOCATION_X, () -> String.valueOf(location.getBlockX())) - .add(LOCATION_Y, () -> String.valueOf(location.getBlockY())) - .add(LOCATION_Z, () -> String.valueOf(location.getBlockZ())) - .add(LOCATION_WORLD, () -> LocationUtil.getWorldName(location)) - .replacer(); + return LOCATION.replacer(location); +// +// return new PlaceholderMap() +// .add(LOCATION_X, () -> String.valueOf(location.getBlockX())) +// .add(LOCATION_Y, () -> String.valueOf(location.getBlockY())) +// .add(LOCATION_Z, () -> String.valueOf(location.getBlockZ())) +// .add(LOCATION_WORLD, () -> LocationUtil.getWorldName(location)) +// .replacer(); } @NotNull public static UnaryOperator forPlayer(@NotNull Player player) { - return new PlaceholderMap() - .add(PLAYER_NAME, player::getName) - .add(PLAYER_DISPLAY_NAME, player::getDisplayName) - .replacer(); + return PLAYER.replacer(player); +// return new PlaceholderMap() +// .add(PLAYER_NAME, player::getName) +// .add(PLAYER_DISPLAY_NAME, player::getDisplayName) +// .replacer(); + } + + @NotNull + public static UnaryOperator forPlayerWithPAPI(@NotNull Player player) { + return str -> setPlaceholderAPI(forPlayer(player).apply(str), player); } @NotNull public static UnaryOperator forSender(@NotNull CommandSender sender) { if (sender instanceof Player player) return forPlayer(player); - return new PlaceholderMap() - .add(PLAYER_NAME, sender::getName) - .add(PLAYER_DISPLAY_NAME, sender::getName) - .replacer(); + return SENDER.replacer(sender); +// +// return new PlaceholderMap() +// .add(PLAYER_NAME, sender::getName) +// .add(PLAYER_DISPLAY_NAME, sender::getName) +// .replacer(); + } + + @NotNull + public static UnaryOperator forPlaceholderAPI(@NotNull Player player) { + return str -> { + if (Plugins.hasPlaceholderAPI()) { + return PlaceholderAPI.setPlaceholders(player, str); + } + return str; + }; + } + + @NotNull + public static String setPlaceholderAPI(@NotNull String str, @NotNull Player player) { + return forPlaceholderAPI(player).apply(str); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/Players.java b/src/main/java/su/nightexpress/nightcore/util/Players.java index b2e3255..023f273 100644 --- a/src/main/java/su/nightexpress/nightcore/util/Players.java +++ b/src/main/java/su/nightexpress/nightcore/util/Players.java @@ -1,6 +1,5 @@ package su.nightexpress.nightcore.util; -import me.clip.placeholderapi.PlaceholderAPI; import net.md_5.bungee.api.ChatMessageType; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -12,7 +11,6 @@ import org.bukkit.inventory.ItemStack; import org.geysermc.floodgate.api.FloodgateApi; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import su.nightexpress.nightcore.core.CoreConfig; import su.nightexpress.nightcore.integration.VaultHook; import su.nightexpress.nightcore.util.text.NightMessage; import su.nightexpress.nightcore.util.text.TextRoot; @@ -25,6 +23,11 @@ public class Players { public static final String PLAYER_COMMAND_PREFIX = "player:"; + @NotNull + public static Set getOnline() { + return new HashSet<>(Bukkit.getServer().getOnlinePlayers()); + } + @NotNull public static List playerNames() { return playerNames(null); @@ -32,31 +35,37 @@ public class Players { @NotNull public static List playerNames(@Nullable Player viewer) { - return playerNames(viewer, true); + return getOnline().stream().filter(player -> viewer == null || viewer.canSee(player)).map(Player::getName).sorted(String::compareTo).toList(); + //return playerNames(viewer, true); } @NotNull + @Deprecated public static List realPlayerNames() { return realPlayerNames(null); } @NotNull + @Deprecated public static List realPlayerNames(@Nullable Player viewer) { return playerNames(viewer, false); } @NotNull + @Deprecated public static List playerNames(@Nullable Player viewer, boolean includeCustom) { - Set names = new HashSet<>(); - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - if (viewer != null && !viewer.canSee(player)) continue; - - names.add(player.getName()); - if (includeCustom && CoreConfig.RESPECT_PLAYER_DISPLAYNAME.get()) { - names.add(Colorizer.strip(player.getDisplayName())); - } - } - return names.stream().sorted(String::compareTo).toList(); + return playerNames(viewer); +// +// Set names = new HashSet<>(); +// for (Player player : Bukkit.getServer().getOnlinePlayers()) { +// if (viewer != null && !viewer.canSee(player)) continue; +// +// names.add(player.getName()); +// if (includeCustom && CoreConfig.RESPECT_PLAYER_DISPLAYNAME.get()) { +// names.add(Colorizer.strip(player.getDisplayName())); +// } +// } +// return names.stream().sorted(String::compareTo).toList(); } @NotNull @@ -65,43 +74,45 @@ public class Players { } @Nullable - public static Player getPlayer(@NotNull String nameOrNick) { - if (!CoreConfig.RESPECT_PLAYER_DISPLAYNAME.get()) { - return Bukkit.getServer().getPlayer(nameOrNick); - } - - Player found = Bukkit.getServer().getPlayerExact(nameOrNick); - if (found != null) { - return found; - } - - String lowerName = nameOrNick.toLowerCase(); - int lowerLength = lowerName.length(); - int delta = Integer.MAX_VALUE; - - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - String nameReal = player.getName().toLowerCase(Locale.ENGLISH); - String nameCustom = player.getDisplayName().toLowerCase(); - - int length; - if (nameReal.startsWith(lowerName)) { - length = player.getName().length(); - } - else if (nameCustom.startsWith(lowerName)) { - length = player.getDisplayName().length(); - } - else continue; - - int curDelta = Math.abs(length - lowerLength); - if (curDelta < delta) { - found = player; - delta = curDelta; - } - - if (curDelta == 0) break; - } - - return found; + public static Player getPlayer(@NotNull String name) { + return Bukkit.getServer().getPlayer(name); +// +// if (!CoreConfig.RESPECT_PLAYER_DISPLAYNAME.get()) { +// return Bukkit.getServer().getPlayer(nameOrNick); +// } +// +// Player found = Bukkit.getServer().getPlayerExact(nameOrNick); +// if (found != null) { +// return found; +// } +// +// String lowerName = nameOrNick.toLowerCase(); +// int lowerLength = lowerName.length(); +// int delta = Integer.MAX_VALUE; +// +// for (Player player : Bukkit.getServer().getOnlinePlayers()) { +// String nameReal = player.getName().toLowerCase(Locale.ENGLISH); +// String nameCustom = player.getDisplayName().toLowerCase(); +// +// int length; +// if (nameReal.startsWith(lowerName)) { +// length = player.getName().length(); +// } +// else if (nameCustom.startsWith(lowerName)) { +// length = player.getDisplayName().length(); +// } +// else continue; +// +// int curDelta = Math.abs(length - lowerLength); +// if (curDelta < delta) { +// found = player; +// delta = curDelta; +// } +// +// if (curDelta == 0) break; +// } +// +// return found; } public static boolean isBedrock(@NotNull Player player) { @@ -163,11 +174,11 @@ public class Players { sender = player; } - command = Placeholders.forPlayer(player).apply(command).trim(); + command = Placeholders.forPlayerWithPAPI(player).apply(command).trim(); - if (Plugins.hasPlaceholderAPI()) { - command = PlaceholderAPI.setPlaceholders(player, command); - } +// if (Plugins.hasPlaceholderAPI()) { +// command = PlaceholderAPI.setPlaceholders(player, command); +// } Bukkit.dispatchCommand(sender, command); } @@ -258,19 +269,19 @@ public class Players { } } - public static void addItem(@NotNull Player player, @NotNull ItemStack item2, int amount) { - if (amount <= 0 || item2.getType().isAir()) return; + public static void addItem(@NotNull Player player, @NotNull ItemStack itemStack, int amount) { + if (amount <= 0 || itemStack.getType().isAir()) return; World world = player.getWorld(); - ItemStack item = new ItemStack(item2); + ItemStack split = new ItemStack(itemStack); - int realAmount = Math.min(item.getMaxStackSize(), amount); - item.setAmount(realAmount); - player.getInventory().addItem(item).values().forEach(left -> { + int realAmount = Math.min(split.getMaxStackSize(), amount); + split.setAmount(realAmount); + player.getInventory().addItem(split).values().forEach(left -> { world.dropItem(player.getLocation(), left); }); amount -= realAmount; - if (amount > 0) addItem(player, item2, amount); + if (amount > 0) addItem(player, itemStack, amount); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/Plugins.java b/src/main/java/su/nightexpress/nightcore/util/Plugins.java index 788c1a7..f5754b7 100644 --- a/src/main/java/su/nightexpress/nightcore/util/Plugins.java +++ b/src/main/java/su/nightexpress/nightcore/util/Plugins.java @@ -6,39 +6,55 @@ import su.nightexpress.nightcore.NightCore; public class Plugins { - public static final NightCore CORE = NightCore.getPlugin(NightCore.class); - public static final String VAULT = "Vault"; public static final String PLACEHOLDER_API = "PlaceholderAPI"; public static final String FLOODGATE = "floodgate"; - private static final boolean HAS_PLACEHOLDER_API = isInstalled(PLACEHOLDER_API); - private static final boolean HAS_VAULT = isInstalled(VAULT); - private static final boolean HAS_FLOODGATE = isInstalled(FLOODGATE); + private static boolean hasPlaceholderAPI; + private static boolean hasVault; + private static boolean hasFloodgate; + + private static NightCore core; + + public static void load(@NotNull NightCore nightCore) { + core = nightCore; + } + + public static void detectPlugins() { + hasPlaceholderAPI = isInstalled(PLACEHOLDER_API); + hasVault = isInstalled(VAULT); + hasFloodgate = isInstalled(FLOODGATE); + } + + @NotNull + public static NightCore getCore() { + return core; + } public static boolean isInstalled(@NotNull String pluginName) { - Plugin plugin = CORE.getPluginManager().getPlugin(pluginName); + Plugin plugin = core.getPluginManager().getPlugin(pluginName); return plugin != null; } public static boolean isLoaded(@NotNull String pluginName) { - Plugin plugin = CORE.getPluginManager().getPlugin(pluginName); + Plugin plugin = core.getPluginManager().getPlugin(pluginName); return plugin != null && plugin.isEnabled(); } + @Deprecated public static boolean isSpigot() { - return CORE.getServer().getVersion().contains("Spigot"); + return Version.isSpigot(); } public static boolean hasPlaceholderAPI() { - return HAS_PLACEHOLDER_API; + return hasPlaceholderAPI; } public static boolean hasVault() { - return HAS_VAULT; + return hasVault; } public static boolean hasFloodgate() { - return HAS_FLOODGATE; + return hasFloodgate; } } diff --git a/src/main/java/su/nightexpress/nightcore/util/RankMap.java b/src/main/java/su/nightexpress/nightcore/util/RankMap.java index 0edc2df..b4884a3 100644 --- a/src/main/java/su/nightexpress/nightcore/util/RankMap.java +++ b/src/main/java/su/nightexpress/nightcore/util/RankMap.java @@ -10,11 +10,12 @@ import java.util.Comparator; import java.util.HashMap; import java.util.Map; +@Deprecated public class RankMap { - private final Mode mode; - private final String permissionPrefix; - private final T defaultValue; + private final Mode mode; + private final String permissionPrefix; + private final T defaultValue; private final Map values; public enum Mode { @@ -44,28 +45,28 @@ public class RankMap { } @NotNull - public static RankMap read(@NotNull FileConfig cfg, @NotNull String path, @NotNull Class clazz, @NotNull T defaultValue) { + public static RankMap read(@NotNull FileConfig config, @NotNull String path, @NotNull Class clazz, @NotNull T defaultValue) { Map oldMap = new HashMap<>(); - if (!cfg.contains(path + ".Mode")) { - for (String rank : cfg.getSection(path)) { + if (!config.contains(path + ".Mode")) { + for (String rank : config.getSection(path)) { T number; if (clazz == Double.class) { - number = clazz.cast(cfg.getDouble(path + "." + rank)); + number = clazz.cast(config.getDouble(path + "." + rank)); } - else number = clazz.cast(cfg.getInt(path + "." + rank)); + else number = clazz.cast(config.getInt(path + "." + rank)); oldMap.put(rank.toLowerCase(), number); } - cfg.remove(path); + config.remove(path); } oldMap.forEach((rank, number) -> { if (rank.equalsIgnoreCase(Placeholders.DEFAULT)) { - cfg.set(path + ".Default_Value", number); + config.set(path + ".Default_Value", number); } else { - cfg.set(path + ".Values." + rank, number); + config.set(path + ".Values." + rank, number); } }); @@ -87,26 +88,26 @@ public class RankMap { " vip: 1 # -> Player must have 'example.prefix.vip' permission.", " gold: 2 # -> Player must have 'example.prefix.gold' permission.", " emerald: 3 # -> Player must have 'example.prefix.emerald' permission." - ).read(cfg); + ).read(config); String permissionPrefix = ConfigValue.create(path + ".Permission_Prefix", "example.prefix.", "Sets permission prefix for the '" + Mode.PERMISSION.name() + "' mode." - ).read(cfg); + ).read(config); T fallback; if (clazz == Double.class) { - fallback = clazz.cast(ConfigValue.create(path + ".Default_Value", defaultValue.doubleValue()).read(cfg)); + fallback = clazz.cast(ConfigValue.create(path + ".Default_Value", defaultValue.doubleValue()).read(config)); } - else fallback = clazz.cast(ConfigValue.create(path + ".Default_Value", defaultValue.intValue()).read(cfg)); + else fallback = clazz.cast(ConfigValue.create(path + ".Default_Value", defaultValue.intValue()).read(config)); Map values = new HashMap<>(); - for (String rank : cfg.getSection(path + ".Values")) { + for (String rank : config.getSection(path + ".Values")) { T number; if (clazz == Double.class) { - number = clazz.cast(cfg.getDouble(path + ".Values." + rank)); + number = clazz.cast(config.getDouble(path + ".Values." + rank)); } - else number = clazz.cast(cfg.getInt(path + ".Values." + rank)); + else number = clazz.cast(config.getInt(path + ".Values." + rank)); values.put(rank.toLowerCase(), number); } @@ -114,19 +115,19 @@ public class RankMap { return new RankMap<>(mode, permissionPrefix, fallback, values); } - public void write(@NotNull FileConfig cfg, @NotNull String path) { - cfg.set(path + ".Mode", this.getMode().name()); - cfg.set(path + ".Permission_Prefix", this.getPermissionPrefix()); - cfg.set(path + ".Default_Value", this.getDefaultValue()); + public void write(@NotNull FileConfig config, @NotNull String path) { + config.set(path + ".Mode", this.mode.name()); + config.set(path + ".Permission_Prefix", this.permissionPrefix); + config.set(path + ".Default_Value", this.defaultValue); this.values.forEach((rank, number) -> { - cfg.set(path + ".Values." + rank, number); + config.set(path + ".Values." + rank, number); }); } @NotNull public T getRankValue(@NotNull Player player) { String group = Players.getPermissionGroup(player); - return this.values.getOrDefault(group, this.values.getOrDefault(Placeholders.DEFAULT, this.getDefaultValue())); + return this.values.getOrDefault(group, this.defaultValue); } @NotNull @@ -139,24 +140,24 @@ public class RankMap { @NotNull public T getGreatest(@NotNull Player player) { - if (this.getMode() == Mode.RANK) { + if (this.mode == Mode.RANK) { return this.getRankValue(player); } return this.values.entrySet().stream() - .filter(entry -> player.hasPermission(this.getPermissionPrefix() + entry.getKey())) + .filter(entry -> player.hasPermission(this.permissionPrefix + entry.getKey())) .map(Map.Entry::getValue) - .max(Comparator.comparingDouble(Number::doubleValue)).orElse(this.getDefaultValue()); + .max(Comparator.comparingDouble(Number::doubleValue)).orElse(this.defaultValue); } @NotNull public T getSmallest(@NotNull Player player) { - if (this.getMode() == Mode.RANK) { + if (this.mode == Mode.RANK) { return this.getRankValue(player); } return this.values.entrySet().stream() - .filter(entry -> player.hasPermission(this.getPermissionPrefix() + entry.getKey())) + .filter(entry -> player.hasPermission(this.permissionPrefix + entry.getKey())) .map(Map.Entry::getValue) - .min(Comparator.comparingDouble(Number::doubleValue)).orElse(this.getDefaultValue()); + .min(Comparator.comparingDouble(Number::doubleValue)).orElse(this.defaultValue); } @NotNull diff --git a/src/main/java/su/nightexpress/nightcore/util/StringUtil.java b/src/main/java/su/nightexpress/nightcore/util/StringUtil.java index 1cc3fa9..a84af5c 100644 --- a/src/main/java/su/nightexpress/nightcore/util/StringUtil.java +++ b/src/main/java/su/nightexpress/nightcore/util/StringUtil.java @@ -3,6 +3,7 @@ package su.nightexpress.nightcore.util; import org.bukkit.Color; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.placeholder.PlaceholderEntry; import su.nightexpress.nightcore.util.random.Rnd; import su.nightexpress.nightcore.util.regex.TimedMatcher; @@ -30,6 +31,7 @@ public class StringUtil { } @NotNull + @Deprecated public static String replaceEach(@NotNull String text, @NotNull List>> replacements) { if (text.isEmpty() || replacements.isEmpty()) { return text; @@ -103,12 +105,86 @@ public class StringUtil { return buf.toString(); } + @NotNull + public static String replaceEach(@NotNull String text, @NotNull List> replacements, @NotNull T source) { + if (text.isEmpty() || replacements.isEmpty()) { + return text; + } + + final int searchLength = replacements.size(); + // keep track of which still have matches + final boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; + + // index on index that the match was found + int textIndex = -1; + int replaceIndex = -1; + int tempIndex; + + // index of replace array that will replace the search string found + for (int i = 0; i < searchLength; i++) { + if (noMoreMatchesForReplIndex[i]) { + continue; + } + tempIndex = text.indexOf(replacements.get(i).getKey()); + + // see if we need to keep searching for this + if (tempIndex == -1) { + noMoreMatchesForReplIndex[i] = true; + } + else if (textIndex == -1 || tempIndex < textIndex) { + textIndex = tempIndex; + replaceIndex = i; + } + } + + // no search strings found, we are done + if (textIndex == -1) { + return text; + } + + int start = 0; + final StringBuilder buf = new StringBuilder(); + while (textIndex != -1) { + for (int i = start; i < textIndex; i++) { + buf.append(text.charAt(i)); + } + buf.append(replacements.get(replaceIndex).get(source)); + + start = textIndex + replacements.get(replaceIndex).getKey().length(); + + textIndex = -1; + replaceIndex = -1; + // find the next earliest match + for (int i = 0; i < searchLength; i++) { + if (noMoreMatchesForReplIndex[i]) { + continue; + } + tempIndex = text.indexOf(replacements.get(i).getKey(), start); + + // see if we need to keep searching for this + if (tempIndex == -1) { + noMoreMatchesForReplIndex[i] = true; + } + else if (textIndex == -1 || tempIndex < textIndex) { + textIndex = tempIndex; + replaceIndex = i; + } + } + } + + final int textLength = text.length(); + for (int i = start; i < textLength; i++) { + buf.append(text.charAt(i)); + } + return buf.toString(); + } + public static String replacePlaceholders(@NotNull String string, @NotNull Map> placeholders) { if (string.isBlank()) return string; StringBuilder builder = new StringBuilder(); - char[] chars = string.toCharArray(); + //char[] chars = string.toCharArray(); int length = string.length(); //int index = 0; for (int index = 0; index < length; index++) { @@ -133,29 +209,6 @@ public class StringUtil { return builder.toString(); } - /*@Nullable - public static String parseQuotedContent(@NotNull String string) { - char quote = string.charAt(0); - if (quote != '\'' && quote != '"') return null; - if (string.length() < 3) return null; - - int indexEnd = -1; - for (int index = 1; index < string.length(); index++) { - char letter = string.charAt(index); - if (letter == '\\') { - index += 2; - continue; - } - if (letter == quote) { - indexEnd = index; - break; - } - } - if (indexEnd == -1) return null; - - return string.substring(1, indexEnd); - }*/ - @Nullable public static String parseQuotedContent(@NotNull String string) { char quote = string.charAt(0); @@ -197,13 +250,13 @@ public class StringUtil { @NotNull public static Color getColor(@NotNull String str) { String[] rgb = str.split(","); - int red = NumberUtil.getInteger(rgb[0], 0); + int red = NumberUtil.getIntegerAbs(rgb[0]); if (red < 0) red = Rnd.get(255); - int green = rgb.length >= 2 ? NumberUtil.getInteger(rgb[1], 0) : 0; + int green = rgb.length >= 2 ? NumberUtil.getIntegerAbs(rgb[1]) : 0; if (green < 0) green = Rnd.get(255); - int blue = rgb.length >= 3 ? NumberUtil.getInteger(rgb[2], 0) : 0; + int blue = rgb.length >= 3 ? NumberUtil.getIntegerAbs(rgb[2]) : 0; if (blue < 0) blue = Rnd.get(255); return Color.fromRGB(red, green, blue); diff --git a/src/main/java/su/nightexpress/nightcore/util/TimeUtil.java b/src/main/java/su/nightexpress/nightcore/util/TimeUtil.java index 6f246de..55b3b0b 100644 --- a/src/main/java/su/nightexpress/nightcore/util/TimeUtil.java +++ b/src/main/java/su/nightexpress/nightcore/util/TimeUtil.java @@ -43,7 +43,7 @@ public class TimeUtil { str.append(delimiter); } - boolean doDecimal = seconds < 5 && str.isEmpty(); + boolean doDecimal = seconds != 0 && seconds < 5 && str.isEmpty(); String secondsStr = doDecimal ? NumberUtil.format((double) time / 1000D) : String.valueOf(seconds); str.append(CoreLang.TIME_SECOND.getString().replace(Placeholders.GENERIC_AMOUNT, secondsStr)); @@ -52,6 +52,30 @@ public class TimeUtil { return str.toString(); } + public static boolean isPassed(long timestamp) { + return timestamp >= 0 && System.currentTimeMillis() > timestamp; + } + + public static long createFutureTimestamp(double seconds) { + return seconds < 0 ? -1L : createTimestamp(Math.abs(seconds)); + } + + public static long createPastTimestamp(double seconds) { + return createTimestamp(-Math.abs(seconds)); + } + + public static long createTimestamp(double seconds) { + return System.currentTimeMillis() + (long) (seconds * 1000D); + } + + public static long secondsToTicks(int seconds) { + return seconds * 20L; + } + + public static double ticksToSeconds(long ticks) { + return (double) ticks / 20D; + } + @NotNull public static String formatDuration(long from, long to) { long time = to - from; diff --git a/src/main/java/su/nightexpress/nightcore/util/TriFunction.java b/src/main/java/su/nightexpress/nightcore/util/TriFunction.java index 2a6a23c..b5f8ae6 100644 --- a/src/main/java/su/nightexpress/nightcore/util/TriFunction.java +++ b/src/main/java/su/nightexpress/nightcore/util/TriFunction.java @@ -3,6 +3,7 @@ package su.nightexpress.nightcore.util; import java.util.Objects; import java.util.function.Function; +@Deprecated public interface TriFunction { R apply(T t, U u, V v); diff --git a/src/main/java/su/nightexpress/nightcore/util/Version.java b/src/main/java/su/nightexpress/nightcore/util/Version.java index 05b9260..9580e55 100644 --- a/src/main/java/su/nightexpress/nightcore/util/Version.java +++ b/src/main/java/su/nightexpress/nightcore/util/Version.java @@ -2,29 +2,36 @@ package su.nightexpress.nightcore.util; import org.bukkit.Bukkit; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightCore; +import su.nightexpress.nightcore.NightCorePlugin; +import su.nightexpress.nightcore.util.version.VersionComponent; import java.util.Comparator; +import java.util.HashSet; +import java.util.Set; import java.util.stream.Stream; public enum Version { - V1_18_R2("1.18.2", Status.DROPPED), V1_19_R3("1.19.4"), V1_20_R1("1.20.1", Status.OUTDATED), V1_20_R2("1.20.2", Status.OUTDATED), V1_20_R3("1.20.4"), - MC_1_20_6("1.20.6", Status.DROPPED), + MC_1_20_6("1.20.6", Status.OUTDATED), MC_1_21_0("1.21", Status.OUTDATED), MC_1_21("1.21.1"), + MC_1_21_2("1.21.2"), UNKNOWN("Unknown"), ; - public static final String CRAFTBUKKIT_PACKAGE = Bukkit.getServer().getClass().getPackage().getName(); + public static final String CRAFTBUKKIT_PACKAGE = Bukkit.getServer().getClass().getPackage().getName(); + private static final Set LOADED_COMPONENTS = new HashSet<>(); private static Version current; + private static boolean spigot; private final Status status; - private final String localized; + private final String localized; Version(@NotNull String localized) { this(localized, Status.SUPPORTED); @@ -47,17 +54,74 @@ public enum Version { DROPPED } + public static void load(@NotNull NightCore core) { + String bukkitVersion = core.getServer().getBukkitVersion(); + String bukkitName = core.getServer().getName(); + String exact = bukkitVersion.split("-")[0]; + + current = Stream.of(values()).sorted(Comparator.reverseOrder()).filter(version -> exact.equalsIgnoreCase(version.getLocalized())).findFirst().orElse(UNKNOWN); + spigot = bukkitName.equalsIgnoreCase("Spigot"); + core.info("Server version detected as " + bukkitName + " " + current.getLocalized() + "."); + + loadComponents(core); + } + + private static void loadComponents(@NotNull NightCore core) { + LOADED_COMPONENTS.clear(); + + loadComponent(core, VersionComponent.ENTITY_ID_GENERATOR, EntityUtil.loadEntityCounter(core)); + loadComponent(core, VersionComponent.ITEM_NBT_COMPRESSOR, ItemNbt.load(core)); + + if (hasComponent(VersionComponent.ITEM_NBT_COMPRESSOR) && !ItemNbt.test()) { + core.error(VersionComponent.ITEM_NBT_COMPRESSOR.name() + ": Test failed."); + } + } + + private static void loadComponent(@NotNull NightCore core, @NotNull VersionComponent component, boolean state) { + if (state) { + LOADED_COMPONENTS.add(component); + core.info("[Core Components] " + component.name() + ": Loaded"); + } + else core.error("[Core Components] " + component.name() + ": Error"); + } + + public static void printCaution(@NotNull NightCorePlugin plugin) { + if (current != UNKNOWN && current.isSupported()) return; + + plugin.warn("=".repeat(35)); + + if (current == Version.UNKNOWN) { + plugin.warn("WARNING: This plugin is not supposed to run on this server version!"); + plugin.warn("If server version is newer than " + values()[values().length - 1] + ", then wait for an update please."); + plugin.warn("Otherwise this plugin will not work properly or even load."); + } + else if (current.isDeprecated()) { + plugin.warn("WARNING: You're running an outdated server version (" + current.getLocalized() + ")!"); + plugin.warn("This version will no longer be supported in future relases."); + plugin.warn("Please upgrade your server to " + Lists.next(current, (Version::isSupported)).getLocalized() + "."); + } + else if (current.isDropped()) { + plugin.error("ERROR: You're running an unsupported server version (" + current.getLocalized() + ")!"); + plugin.error("Please upgrade your server to " + Lists.next(current, (Version::isSupported)).getLocalized() + "."); + } + + plugin.warn("ABSOLUTELY NO DISCORD SUPPORT WILL BE PROVIDED"); + plugin.warn("=".repeat(35)); + } + @NotNull public static Version getCurrent() { - if (current == null) { - String protocol = Bukkit.getServer().getBukkitVersion(); - String exact = protocol.split("-")[0]; - - current = Stream.of(values()).sorted(Comparator.reverseOrder()).filter(version -> exact.equalsIgnoreCase(version.getLocalized())).findFirst().orElse(UNKNOWN); - } return current; } + public static boolean isSpigot() { + return spigot; + } + + public static boolean hasComponent(@NotNull VersionComponent component) { + return LOADED_COMPONENTS.contains(component); + } + public boolean isDeprecated() { return this.status == Status.OUTDATED; } diff --git a/src/main/java/su/nightexpress/nightcore/util/blocktracker/PlayerBlockTracker.java b/src/main/java/su/nightexpress/nightcore/util/blocktracker/PlayerBlockTracker.java index ca6b0ec..8b3a84b 100644 --- a/src/main/java/su/nightexpress/nightcore/util/blocktracker/PlayerBlockTracker.java +++ b/src/main/java/su/nightexpress/nightcore/util/blocktracker/PlayerBlockTracker.java @@ -25,7 +25,7 @@ public final class PlayerBlockTracker { public static void initialize() { if (listener == null) { initCurrentlyLoadedWorlds(); - (listener = new TrackListener<>(Plugins.CORE)).registerListeners(); + (listener = new TrackListener<>(Plugins.getCore())).registerListeners(); } } diff --git a/src/main/java/su/nightexpress/nightcore/util/bukkit/NightSound.java b/src/main/java/su/nightexpress/nightcore/util/bukkit/NightSound.java new file mode 100644 index 0000000..1c268c6 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/bukkit/NightSound.java @@ -0,0 +1,124 @@ +package su.nightexpress.nightcore.util.bukkit; + +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.config.ConfigValue; +import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.config.Writeable; +import su.nightexpress.nightcore.util.BukkitThing; +import su.nightexpress.nightcore.util.NumberUtil; + +public class NightSound implements Writeable { + + private static final float MIN_PITCH = 0.5f; + private static final float MAX_PITCH = 2.0f; + private static final float MIN_VOLUME = 0f; + private static final float MAX_VOLUME = 1.0f; + + private final String name; + private final Sound bukkit; + private final float volume; + private final float pitch; + + public NightSound(@NotNull String name, @Nullable Sound bukkit, float volume, float pitch) { + this.name = name; + this.bukkit = bukkit; + + this.volume = NumberUtil.clamp(volume, MIN_VOLUME, MAX_VOLUME); + this.pitch = NumberUtil.clamp(pitch, MIN_PITCH, MAX_PITCH); + } + + @NotNull + public static NightSound of(@NotNull Sound sound) { + return of(sound, MAX_VOLUME); + } + + @NotNull + public static NightSound of(@NotNull Sound sound, float volume) { + return of(sound, volume, 1F); + } + + @NotNull + public static NightSound of(@NotNull Sound sound, float volume, float pitch) { + return new NightSound(BukkitThing.toString(sound), sound, volume, pitch); + } + + @NotNull + public static NightSound read(@NotNull FileConfig config, @NotNull String path) { + String name = ConfigValue.create(path + ".Name", "null", + "Sound name. Use vanilla sound names or custom ones from your resource pack(s).", + "All vanilla sound names: https://minecraft.wiki/w/Sounds.json#Sound_events -> 'Java Edition values' -> 'Sound Event' column." + ).read(config); + + float volume = ConfigValue.create(path + ".Volume", MAX_VOLUME, + "Sound volume. [" + MIN_VOLUME + " to " + MAX_VOLUME + "]" + ).read(config).floatValue(); + + float pitch = ConfigValue.create(path + ".Pitch", 1D, + "Sound speed. [" + MIN_PITCH + " to " + MAX_PITCH + "]" + ).read(config).floatValue(); + + Sound bukkit = BukkitThing.getSound(name); + + return new NightSound(name, bukkit, volume, pitch); + } + + @Override + public void write(@NotNull FileConfig config, @NotNull String path) { + config.set(path + ".Name", this.name); + config.set(path + ".Volume", this.volume); + config.set(path + ".Pitch", this.pitch); + } + + public boolean isEmpty() { + return this.volume <= 0F || this.name.isEmpty(); + } + + public void play(@NotNull Player player) { + if (this.isEmpty()) return; + + Location location = player.getLocation(); + if (this.bukkit == null) { + player.playSound(location, this.name, this.volume, this.pitch); + } + else { + player.playSound(location, this.bukkit, this.volume, this.pitch); + } + } + + public void play(@NotNull Location location) { + if (this.isEmpty()) return; + + World world = location.getWorld(); + if (world == null) return; + + if (this.bukkit == null) { + world.playSound(location, this.name, this.volume, this.pitch); + } + else { + world.playSound(location, this.bukkit, this.volume, this.pitch); + } + } + + @NotNull + public String getName() { + return this.name; + } + + @Nullable + public Sound getBukkit() { + return this.bukkit; + } + + public float getVolume() { + return this.volume; + } + + public float getPitch() { + return this.pitch; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/bukkit/NightTask.java b/src/main/java/su/nightexpress/nightcore/util/bukkit/NightTask.java new file mode 100644 index 0000000..2edfe05 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/bukkit/NightTask.java @@ -0,0 +1,67 @@ +package su.nightexpress.nightcore.util.bukkit; + +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.NightCorePlugin; +import su.nightexpress.nightcore.util.TimeUtil; + +import java.util.function.Function; + +public class NightTask { + + private final NightCorePlugin plugin; + private final BukkitTask bukkitTask; + + public NightTask(@NotNull NightCorePlugin plugin, @Nullable BukkitTask bukkitTask) { + this.plugin = plugin; + this.bukkitTask = bukkitTask; + } + + @NotNull + public static NightTask create(@NotNull NightCorePlugin plugin, @NotNull Runnable runnable, int interval) { + return create(plugin, runnable, TimeUtil.secondsToTicks(interval)); + } + + @NotNull + public static NightTask create(@NotNull NightCorePlugin plugin, @NotNull Runnable runnable, long interval) { + return createTask(plugin, scheduler -> interval <= 0 ? null : scheduler.runTaskTimer(plugin, runnable, 0L, interval)); + } + + @NotNull + public static NightTask createAsync(@NotNull NightCorePlugin plugin, @NotNull Runnable runnable, int interval) { + return createAsync(plugin, runnable, TimeUtil.secondsToTicks(interval)); + } + + @NotNull + public static NightTask createAsync(@NotNull NightCorePlugin plugin, @NotNull Runnable runnable, long interval) { + return createTask(plugin, scheduler -> interval <= 0 ? null : scheduler.runTaskTimerAsynchronously(plugin, runnable, 0L, interval)); + } + + @NotNull + private static NightTask createTask(@NotNull NightCorePlugin plugin, @NotNull Function function) { + BukkitTask bukkitTask = function.apply(plugin.getScheduler()); + return new NightTask(plugin, bukkitTask); + } + + @Nullable + public BukkitTask getBukkitTask() { + return this.bukkitTask; + } + + public boolean isValid() { + return this.bukkitTask != null; + } + + public boolean isRunning() { + return this.bukkitTask != null && this.plugin.getScheduler().isCurrentlyRunning(this.bukkitTask.getTaskId()); + } + + public boolean stop() { + if (!this.isRunning() || this.bukkitTask == null) return false; + + this.plugin.getScheduler().cancelTask(this.bukkitTask.getTaskId()); + return true; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/number/CompactNumber.java b/src/main/java/su/nightexpress/nightcore/util/number/CompactNumber.java new file mode 100644 index 0000000..db3b465 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/number/CompactNumber.java @@ -0,0 +1,33 @@ +package su.nightexpress.nightcore.util.number; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.NumberUtil; + +public class CompactNumber { + + private final double value; + private final NumberShortcut shortcut; + + public CompactNumber(double value, @Nullable NumberShortcut shortcut) { + this.value = value; + this.shortcut = shortcut; + } + + @NotNull + public String format() { + String num = String.valueOf(NumberUtil.round(this.value, 1)); + if (this.shortcut != null) num += this.shortcut.getSymbol(); + + return num; + } + + public double getValue() { + return this.value; + } + + @Nullable + public NumberShortcut getShortcut() { + return this.shortcut; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/number/NumberShortcut.java b/src/main/java/su/nightexpress/nightcore/util/number/NumberShortcut.java new file mode 100644 index 0000000..9f7eec6 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/number/NumberShortcut.java @@ -0,0 +1,52 @@ +package su.nightexpress.nightcore.util.number; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.config.Writeable; +import su.nightexpress.nightcore.core.CoreConfig; + +public class NumberShortcut implements Writeable { + + private final int magnitude; + private final String symbol; + + public NumberShortcut(int magnitude, @NotNull String symbol) { + this.magnitude = magnitude; + this.symbol = symbol; + } + + @NotNull + public static NumberShortcut read(@NotNull FileConfig config, @NotNull String path) { + int magnitude = config.getInt(path + ".Magnitude"); + String name = config.getString(path + ".Name", String.valueOf(magnitude)); + + return new NumberShortcut(magnitude, name); + } + + @Override + public void write(@NotNull FileConfig config, @NotNull String path) { + config.set(path + ".Magnitude", this.magnitude); + config.set(path + ".Name", this.symbol); + } + + public int getMagnitude() { + return this.magnitude; + } + + public double getMultiplier() { + return Math.pow(CoreConfig.NUMBER_SHORTCUT_STEP.get(), this.magnitude); + } + + @NotNull + public String getSymbol() { + return this.symbol; + } + + @Override + public String toString() { + return "NumberShortcut{" + + "magnitude=" + magnitude + + ", symbol='" + symbol + '\'' + + '}'; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/placeholder/Placeholder.java b/src/main/java/su/nightexpress/nightcore/util/placeholder/Placeholder.java index 416074b..d184217 100644 --- a/src/main/java/su/nightexpress/nightcore/util/placeholder/Placeholder.java +++ b/src/main/java/su/nightexpress/nightcore/util/placeholder/Placeholder.java @@ -4,6 +4,7 @@ import org.jetbrains.annotations.NotNull; import java.util.function.UnaryOperator; +@Deprecated public interface Placeholder { @NotNull PlaceholderMap getPlaceholders(); diff --git a/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderEntry.java b/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderEntry.java new file mode 100644 index 0000000..c454800 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderEntry.java @@ -0,0 +1,31 @@ +package su.nightexpress.nightcore.util.placeholder; + +import org.jetbrains.annotations.NotNull; + +import java.util.function.Function; + +public class PlaceholderEntry { + + private final String key; + private final Function function; + + public PlaceholderEntry(@NotNull String key, @NotNull Function function) { + this.key = key; + this.function = function; + } + + @NotNull + public String get(@NotNull T source) { + return this.function.apply(source); + } + + @NotNull + public String getKey() { + return this.key; + } + + @NotNull + public Function getFunction() { + return this.function; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderList.java b/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderList.java new file mode 100644 index 0000000..c5cd174 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderList.java @@ -0,0 +1,69 @@ +package su.nightexpress.nightcore.util.placeholder; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.StringUtil; + +import java.util.*; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; + +public class PlaceholderList { + + private final List> entries; + + public PlaceholderList() { + this(new ArrayList<>()); + } + + public PlaceholderList(@NotNull PlaceholderList other) { + this(other.getEntries()); + } + + public PlaceholderList(@NotNull List> entries) { + this.entries = new ArrayList<>(entries); + } + + @NotNull + public List> getEntries() { + return this.entries; + } + + @NotNull + public PlaceholderList add(@NotNull PlaceholderList other) { + this.entries.addAll(other.getEntries()); + return this; + } + + @NotNull + public PlaceholderList add(@NotNull String key, @NotNull String replacer) { + this.add(key, source -> replacer); + return this; + } + + @NotNull + public PlaceholderList add(@NotNull String key, @NotNull Supplier replacer) { + this.add(key, source -> replacer.get()); + return this; + } + + @NotNull + public PlaceholderList add(@NotNull String key, @NotNull Function replacer) { + this.entries.add(new PlaceholderEntry<>(key, replacer)); + return this; + } + + public void clear() { + this.entries.clear(); + } + + @NotNull + public UnaryOperator replacer(@NotNull T source) { + return str -> StringUtil.replaceEach(str, this.entries, source); + } + + @NotNull + public String apply(@NotNull String str, @NotNull T source) { + return this.replacer(source).apply(str); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderMap.java b/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderMap.java index fc11e22..384b530 100644 --- a/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderMap.java +++ b/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderMap.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.function.Supplier; import java.util.function.UnaryOperator; +@Deprecated public class PlaceholderMap { private final List>> keys; diff --git a/src/main/java/su/nightexpress/nightcore/util/placeholder/Replacer.java b/src/main/java/su/nightexpress/nightcore/util/placeholder/Replacer.java new file mode 100644 index 0000000..afb5a95 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/placeholder/Replacer.java @@ -0,0 +1,95 @@ +package su.nightexpress.nightcore.util.placeholder; + +import me.clip.placeholderapi.PlaceholderAPI; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.Placeholders; +import su.nightexpress.nightcore.util.Plugins; +import su.nightexpress.nightcore.util.text.NightMessage; +import su.nightexpress.nightcore.util.text.TextRoot; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; + +public class Replacer { + + private final PlaceholderList placeholders; + private final List> replacers; + + public Replacer() { + this.placeholders = new PlaceholderList<>(); + this.replacers = new ArrayList<>(); + } + + public void clear() { + this.placeholders.clear(); + this.replacers.clear(); + } + + @NotNull + public List> getReplacers() { + List> replacers = new ArrayList<>(); + replacers.add(this.placeholders.replacer(this)); + replacers.addAll(this.replacers); + return replacers; + } + + @NotNull + public TextRoot getReplaced(@NotNull String source) { + return this.getReplaced(NightMessage.from(source)); + } + + @NotNull + public TextRoot getReplaced(@NotNull TextRoot source) { + TextRoot root = source.copy(); + this.getReplacers().forEach(root::replace); + return root; + } + + @NotNull + public Replacer replacePlaceholderAPI(@NotNull Player player) { + if (!Plugins.hasPlaceholderAPI()) return this; + + return this.replace(line -> PlaceholderAPI.setPlaceholders(player, line)); + } + + @NotNull + public Replacer replace(@NotNull String key, @NotNull Consumer> replacer) { + List list = new ArrayList<>(); + replacer.accept(list); + + return this.replace(key, list); + } + + @NotNull + public Replacer replace(@NotNull String key, @NotNull List replacer) { + this.placeholders.add(key, () -> String.join(Placeholders.TAG_LINE_BREAK, replacer)); + return this; + } + + @NotNull + public Replacer replace(@NotNull T source, @NotNull PlaceholderList placeholders) { + return this.replace(placeholders.replacer(source)); + } + + @NotNull + public Replacer replace(@NotNull String key, @NotNull Supplier value) { + this.placeholders.add(key, value); + return this; + } + + @NotNull + public Replacer replace(@NotNull String key, @NotNull Object value) { + this.placeholders.add(key, String.valueOf(value)); + return this; + } + + @NotNull + public Replacer replace(@NotNull UnaryOperator replacer) { + this.replacers.add(replacer); + return this; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/random/Rnd.java b/src/main/java/su/nightexpress/nightcore/util/random/Rnd.java index 9b3c241..de3ed0d 100644 --- a/src/main/java/su/nightexpress/nightcore/util/random/Rnd.java +++ b/src/main/java/su/nightexpress/nightcore/util/random/Rnd.java @@ -1,7 +1,6 @@ package su.nightexpress.nightcore.util.random; import org.jetbrains.annotations.NotNull; -import su.nightexpress.nightcore.util.Pair; import java.util.*; @@ -52,19 +51,36 @@ public class Rnd { @NotNull public static T getByWeight(@NotNull Map itemsMap) { - List> items = itemsMap.entrySet().stream() - .filter(entry -> entry.getValue() > 0D) - .map(entry -> Pair.of(entry.getKey(), entry.getValue())) - .sorted(Comparator.comparing(Pair::getSecond)) - .toList(); - double totalWeight = items.stream().mapToDouble(Pair::getSecond).sum(); +// List> items = itemsMap.entrySet().stream() +// .filter(entry -> entry.getValue() > 0D) +// .map(entry -> Pair.of(entry.getKey(), entry.getValue())) +// .sorted(Comparator.comparing(Pair::getSecond)) +// .toList(); +// double totalWeight = items.stream().mapToDouble(Pair::getSecond).sum(); +// +// int index = 0; +// for (double roll = nextDouble() * totalWeight; index < items.size() - 1; ++index) { +// roll -= items.get(index).getSecond(); +// if (roll <= 0D) break; +// } +// return items.get(index).getFirst(); + List> items = new ArrayList<>(); + itemsMap.forEach((item, weight) -> items.add(WeightedItem.of(item, weight))); + return getByWeight(items); + } + + @NotNull + public static T getByWeight(@NotNull List> items) { + items.sort(Comparator.comparing(WeightedItem::getWeight)); + double totalWeight = items.stream().mapToDouble(WeightedItem::getWeight).sum(); int index = 0; for (double roll = nextDouble() * totalWeight; index < items.size() - 1; ++index) { - roll -= items.get(index).getSecond(); + roll -= items.get(index).getWeight(); if (roll <= 0D) break; } - return items.get(index).getFirst(); + + return items.get(index).getItem(); } public static boolean chance(int chance) { diff --git a/src/main/java/su/nightexpress/nightcore/util/random/WeightedItem.java b/src/main/java/su/nightexpress/nightcore/util/random/WeightedItem.java new file mode 100644 index 0000000..fb2e2b5 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/random/WeightedItem.java @@ -0,0 +1,28 @@ +package su.nightexpress.nightcore.util.random; + +import org.jetbrains.annotations.NotNull; + +public class WeightedItem { + + private final T item; + private final double weight; + + public WeightedItem(@NotNull T item, double weight) { + this.item = item; + this.weight = weight; + } + + @NotNull + public static WeightedItem of(@NotNull T item, double weight) { + return new WeightedItem<>(item, weight); + } + + @NotNull + public T getItem() { + return this.item; + } + + public double getWeight() { + return this.weight; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/rankmap/DoubleRankMap.java b/src/main/java/su/nightexpress/nightcore/util/rankmap/DoubleRankMap.java new file mode 100644 index 0000000..f631b50 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/rankmap/DoubleRankMap.java @@ -0,0 +1,38 @@ +package su.nightexpress.nightcore.util.rankmap; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.config.ConfigValue; +import su.nightexpress.nightcore.config.FileConfig; + +import java.util.Map; +import java.util.function.Function; + +public class DoubleRankMap extends RankMap { + + public static final Creator CREATOR = DoubleRankMap::new; + public static final Function CONVERTER = Double::doubleValue; + + public DoubleRankMap(@NotNull RankMap.Mode mode, @NotNull String permissionPrefix, double defaultValue, @NotNull Map values) { + super(mode, permissionPrefix, defaultValue, values); + } + + @NotNull + public static DoubleRankMap ranked(double defaultValue) { + return ranked(CREATOR, defaultValue); + } + + @NotNull + public static DoubleRankMap permissioned(@NotNull String prefix, double defaultValue) { + return permissioned(CREATOR, prefix, defaultValue); + } + + @NotNull + public static ConfigValue asConfigValue(@NotNull String path, @NotNull DoubleRankMap defaultValue, @NotNull String... description) { + return asConfigValue(path, defaultValue, CREATOR, CONVERTER, description); + } + + @NotNull + public static DoubleRankMap read(@NotNull FileConfig config, @NotNull String path) { + return read(config, path, CREATOR, CONVERTER); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/rankmap/IntRankMap.java b/src/main/java/su/nightexpress/nightcore/util/rankmap/IntRankMap.java new file mode 100644 index 0000000..b975a9a --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/rankmap/IntRankMap.java @@ -0,0 +1,38 @@ +package su.nightexpress.nightcore.util.rankmap; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.config.ConfigValue; +import su.nightexpress.nightcore.config.FileConfig; + +import java.util.Map; +import java.util.function.Function; + +public class IntRankMap extends RankMap { + + public static final Creator CREATOR = IntRankMap::new; + public static final Function CONVERTER = Double::intValue; + + public IntRankMap(@NotNull Mode mode, @NotNull String permissionPrefix, int defaultValue, @NotNull Map values) { + super(mode, permissionPrefix, defaultValue, values); + } + + @NotNull + public static IntRankMap ranked(int defaultValue) { + return ranked(CREATOR, defaultValue); + } + + @NotNull + public static IntRankMap permissioned(@NotNull String prefix, int defaultValue) { + return permissioned(CREATOR, prefix, defaultValue); + } + + @NotNull + public static ConfigValue asConfigValue(@NotNull String path, @NotNull IntRankMap defaultValue, @NotNull String... description) { + return asConfigValue(path, defaultValue, CREATOR, CONVERTER, description); + } + + @NotNull + public static IntRankMap read(@NotNull FileConfig config, @NotNull String path) { + return read(config, path, CREATOR, CONVERTER); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/rankmap/LongRankMap.java b/src/main/java/su/nightexpress/nightcore/util/rankmap/LongRankMap.java new file mode 100644 index 0000000..187b058 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/rankmap/LongRankMap.java @@ -0,0 +1,38 @@ +package su.nightexpress.nightcore.util.rankmap; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.config.ConfigValue; +import su.nightexpress.nightcore.config.FileConfig; + +import java.util.Map; +import java.util.function.Function; + +public class LongRankMap extends RankMap { + + public static final Creator CREATOR = LongRankMap::new; + public static final Function CONVERTER = Double::longValue; + + public LongRankMap(@NotNull RankMap.Mode mode, @NotNull String permissionPrefix, long defaultValue, @NotNull Map values) { + super(mode, permissionPrefix, defaultValue, values); + } + + @NotNull + public static LongRankMap ranked(long defaultValue) { + return ranked(CREATOR, defaultValue); + } + + @NotNull + public static LongRankMap permissioned(@NotNull String prefix, long defaultValue) { + return permissioned(CREATOR, prefix, defaultValue); + } + + @NotNull + public static ConfigValue asConfigValue(@NotNull String path, @NotNull LongRankMap defaultValue, @NotNull String... description) { + return asConfigValue(path, defaultValue, CREATOR, CONVERTER, description); + } + + @NotNull + public static LongRankMap read(@NotNull FileConfig config, @NotNull String path) { + return read(config, path, CREATOR, CONVERTER); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/rankmap/RankMap.java b/src/main/java/su/nightexpress/nightcore/util/rankmap/RankMap.java new file mode 100644 index 0000000..8800613 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/rankmap/RankMap.java @@ -0,0 +1,166 @@ +package su.nightexpress.nightcore.util.rankmap; + +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.config.ConfigValue; +import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.util.Players; +import su.nightexpress.nightcore.util.StringUtil; + +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +public abstract class RankMap { + + private final Mode mode; + private final String permissionPrefix; + private final T defaultValue; + private final Map values; + + public enum Mode { + RANK, PERMISSION + } + + public interface Creator> { + @NotNull R create(@NotNull Mode mode, @NotNull String permissionPrefix, @NotNull T defaultValue, @NotNull Map values); + } + + public RankMap(@NotNull Mode mode, @NotNull String permissionPrefix, @NotNull T defaultValue, @NotNull Map values) { + this.mode = mode; + this.permissionPrefix = permissionPrefix; + this.defaultValue = defaultValue; + this.values = new HashMap<>(values); + } + + @NotNull + protected static > R ranked(@NotNull Creator creator, @NotNull T defaultValue) { + return creator.create(Mode.RANK, "", defaultValue, new HashMap<>()); + } + + @NotNull + protected static > R permissioned(@NotNull Creator creator, @NotNull String prefix, @NotNull T defaultValue) { + return creator.create(Mode.PERMISSION, prefix, defaultValue, new HashMap<>()); + } + + @NotNull + protected static > ConfigValue asConfigValue(@NotNull String path, + @NotNull R defaultValue, + @NotNull Creator creator, + @NotNull Function converter, + @NotNull String... description) { + ConfigValue.Reader reader = (config, path2, def) -> read(config, path2, creator, converter); + ConfigValue.Writer writer = (config, path2, obj) -> obj.write(config, path2); + + return ConfigValue.create(path, reader, writer, () -> defaultValue, description); + } + + @NotNull + protected static > R read(@NotNull FileConfig config, + @NotNull String path, + @NotNull Creator creator, + @NotNull Function converter) { + Mode mode = ConfigValue.create(path + ".Mode", Mode.class, Mode.RANK, + "Available values: " + StringUtil.inlineEnum(Mode.class, ", "), + "=".repeat(20) + " " + Mode.RANK.name() + " MODE " + "=".repeat(20), + "Get value by player's permission group. All keys in 'Values' list will represent permission group names.", + "If player has none of specified groups, the 'Default_Value' setting will be used then", + " Values:", + " vip: 1 # -> Player must be in 'vip' permission group.", + " gold: 2 # -> Player must be in 'gold' permission group.", + " emerald: 3 # -> Player must be in 'emerald' permission group.", + "", + "=".repeat(20) + " " + Mode.PERMISSION.name() + " MODE " + "=".repeat(20), + "Get value by player's permissions. All keys in 'Values' list will represent postfixes for the 'Permission_Prefix' setting (see below).", + "If player has none of specified permissions, the 'Default_Value' setting will be used then", + " Permission_Prefix: 'example.prefix.'", + " Values:", + " vip: 1 # -> Player must have 'example.prefix.vip' permission.", + " gold: 2 # -> Player must have 'example.prefix.gold' permission.", + " emerald: 3 # -> Player must have 'example.prefix.emerald' permission." + ).read(config); + + String permissionPrefix = ConfigValue.create(path + ".Permission_Prefix", + "example.prefix.", + "Sets permission prefix for the '" + Mode.PERMISSION.name() + "' mode." + ).read(config); + + T defaultValue = converter.apply(config.getDouble(path + ".Default_Value")); + + Map values = new HashMap<>(); + for (String rank : config.getSection(path + ".Values")) { + double number = config.getDouble(path + ".Values." + rank); + values.put(rank.toLowerCase(), converter.apply(number)); + } + + return creator.create(mode, permissionPrefix, defaultValue, values); + } + + public void write(@NotNull FileConfig config, @NotNull String path) { + config.set(path + ".Mode", this.mode.name()); + config.set(path + ".Permission_Prefix", this.permissionPrefix); + config.set(path + ".Default_Value", this.defaultValue); + this.values.forEach((rank, number) -> { + config.set(path + ".Values." + rank, number); + }); + } + + @NotNull + public RankMap addValue(@NotNull String key, @NotNull T value) { + this.values.put(key.toLowerCase(), value); + return this; + } + + @NotNull + public T getRankValue(@NotNull Player player) { + String group = Players.getPermissionGroup(player); + return this.values.getOrDefault(group, this.defaultValue); + } + + @NotNull + public T getGreatestOrNegative(@NotNull Player player) { + T best = this.getGreatest(player); + T lowest = this.getSmallest(player); + + return lowest.doubleValue() < 0D ? lowest : best; + } + + @NotNull + public T getGreatest(@NotNull Player player) { + if (this.mode == Mode.RANK) { + return this.getRankValue(player); + } + return this.values.entrySet().stream() + .filter(entry -> player.hasPermission(this.permissionPrefix + entry.getKey())) + .map(Map.Entry::getValue) + .max(Comparator.comparingDouble(Number::doubleValue)).orElse(this.defaultValue); + } + + @NotNull + public T getSmallest(@NotNull Player player) { + if (this.mode == Mode.RANK) { + return this.getRankValue(player); + } + return this.values.entrySet().stream() + .filter(entry -> player.hasPermission(this.permissionPrefix + entry.getKey())) + .map(Map.Entry::getValue) + .min(Comparator.comparingDouble(Number::doubleValue)).orElse(this.defaultValue); + } + + @NotNull + public Mode getMode() { + return mode; + } + + @Nullable + public String getPermissionPrefix() { + return permissionPrefix; + } + + @NotNull + public T getDefaultValue() { + return defaultValue; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/regex/TimedMatcher.java b/src/main/java/su/nightexpress/nightcore/util/regex/TimedMatcher.java index 79d92ff..83014cf 100644 --- a/src/main/java/su/nightexpress/nightcore/util/regex/TimedMatcher.java +++ b/src/main/java/su/nightexpress/nightcore/util/regex/TimedMatcher.java @@ -63,7 +63,7 @@ public class TimedMatcher { } catch (MatcherTimeoutException exception) { if (this.isDebug()) { - Plugins.CORE.warn("Matcher " + exception.getTimeout() + "ms timeout error for replaceAll: '" + matcher.pattern().pattern() + "'."); + Plugins.getCore().warn("Matcher " + exception.getTimeout() + "ms timeout error for replaceAll: '" + matcher.pattern().pattern() + "'."); } return ""; } @@ -75,7 +75,7 @@ public class TimedMatcher { } catch (MatcherTimeoutException exception) { if (this.isDebug()) { - Plugins.CORE.warn("Matcher " + exception.getTimeout() + "ms timeout error for: '" + matcher.pattern().pattern() + "'."); + Plugins.getCore().warn("Matcher " + exception.getTimeout() + "ms timeout error for: '" + matcher.pattern().pattern() + "'."); } return false; } @@ -87,7 +87,7 @@ public class TimedMatcher { } catch (MatcherTimeoutException exception) { if (this.isDebug()) { - Plugins.CORE.warn("Matcher " + exception.getTimeout() + "ms timeout error for: '" + matcher.pattern().pattern() + "'."); + Plugins.getCore().warn("Matcher " + exception.getTimeout() + "ms timeout error for: '" + matcher.pattern().pattern() + "'."); } return false; } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java b/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java index 58bd238..c7105c4 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/TextRoot.java @@ -103,6 +103,7 @@ public class TextRoot { } @NotNull + @Deprecated public TextRoot replace(@NotNull String what, @NotNull Object object) { return this.replace(str -> str.replace(what, String.valueOf(object))); } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/TagUtils.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/TagUtils.java new file mode 100644 index 0000000..f7afa7b --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/TagUtils.java @@ -0,0 +1,31 @@ +package su.nightexpress.nightcore.util.text.tag; + +import org.jetbrains.annotations.NotNull; + +import java.awt.*; + +public class TagUtils { + + @NotNull + public static Color colorFromHexString(@NotNull String string) { + return colorFromHexString(string, Color.WHITE); + } + + @NotNull + public static Color colorFromHexString(@NotNull String string, @NotNull Color fallback) { + if (string.charAt(0) != '#') string = "#" + string; + + try { + return Color.decode(string); + } + catch (NumberFormatException exception) { + exception.printStackTrace(); + return fallback; + } + } + + @NotNull + public static String colorToHexString(@NotNull Color color) { + return "#" + Integer.toHexString(color.getRGB()).substring(2); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java index 8553f46..87db0f8 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java @@ -2,15 +2,21 @@ package su.nightexpress.nightcore.util.text.tag; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.NightCore; +import su.nightexpress.nightcore.config.FileConfig; import su.nightexpress.nightcore.util.text.tag.api.Tag; import su.nightexpress.nightcore.util.text.tag.impl.*; +import java.awt.*; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class Tags { + public static final String FILE_NAME = "colors.yml"; + private static final String COLORS_PATH = "Colors"; + private static final Map REGISTRY = new HashMap<>(); public static final GradientTag GRADIENT = new GradientTag(); @@ -69,6 +75,30 @@ public class Tags { Tags.RESET, Tags.HEX_COLOR, Tags.HEX_COLOR_SHORT, Tags.TRANSLATE); } + public static void loadColorsFromFile(@NotNull NightCore core) { + FileConfig config = FileConfig.loadOrExtract(core, FILE_NAME); + + if (config.getSection(COLORS_PATH).isEmpty()) { + getTags().forEach(tag -> { + if (!(tag instanceof ColorTag colorTag)) return; + + for (String alias : colorTag.getAliases()) { + config.set(COLORS_PATH + "." + alias, colorTag.toHexString()); + } + }); + } + + config.getSection(COLORS_PATH).forEach(name -> { + String hex = config.getString(COLORS_PATH + "." + name); + if (hex == null) return; + + Color color = TagUtils.colorFromHexString(hex); + registerTag(new ColorTag(name, color)); + }); + + config.saveChanges(); + } + @NotNull public static Collection getTags() { return REGISTRY.values(); diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ContentTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ContentTag.java index fac0523..4bf0031 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ContentTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ContentTag.java @@ -6,6 +6,5 @@ import su.nightexpress.nightcore.util.text.tag.decorator.Decorator; public interface ContentTag { - @Nullable - Decorator parse(@NotNull String str); + @Nullable Decorator parse(@NotNull String str); } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java index 66dc434..35695f2 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java @@ -3,6 +3,7 @@ package su.nightexpress.nightcore.util.text.tag.impl; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.api.SimpleTag; import su.nightexpress.nightcore.util.text.tag.decorator.ColorDecorator; @@ -17,7 +18,7 @@ public class ColorTag extends SimpleTag implements ColorDecorator { } public ColorTag(@NotNull String name, @NotNull String[] aliases, @NotNull String hex) { - this(name, aliases, Color.decode(hex)); + this(name, aliases, TagUtils.colorFromHexString(hex)); } public ColorTag(@NotNull Color color) { @@ -25,7 +26,7 @@ public class ColorTag extends SimpleTag implements ColorDecorator { } public ColorTag(@NotNull Color color, @NotNull String[] aliases) { - this(Integer.toHexString(color.getRGB()).substring(2), aliases, color); + this(TagUtils.colorToHexString(color).substring(1), aliases, color); } public ColorTag(@NotNull String name, @NotNull Color color) { @@ -46,4 +47,9 @@ public class ColorTag extends SimpleTag implements ColorDecorator { public void decorate(@NotNull BaseComponent component) { component.setColor(ChatColor.of(this.getColor())); } + + @NotNull + public String toHexString() { + return TagUtils.colorToHexString(this.color); + } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java index 1652ea1..cc6fcc4 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java @@ -2,6 +2,7 @@ package su.nightexpress.nightcore.util.text.tag.impl; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.decorator.GradientColorDecorator; import su.nightexpress.nightcore.util.text.tag.api.ContentTag; import su.nightexpress.nightcore.util.text.tag.api.Tag; @@ -33,17 +34,17 @@ public class GradientTag extends Tag implements ContentTag { String code1 = split[0]; String code2 = split[1]; - Color from; - Color to; + Color from = TagUtils.colorFromHexString(code1); + Color to = TagUtils.colorFromHexString(code2); // TODO Support for named colors - try { - from = Color.decode(code1); - to = Color.decode(code2); - } - catch (NumberFormatException exception) { - return null; - } +// try { +// from = Color.decode(code1); +// to = Color.decode(code2); +// } +// catch (NumberFormatException exception) { +// return null; +// } return new GradientColorDecorator(from, to); } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java index 36cb0c3..9d04f93 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java @@ -2,6 +2,7 @@ package su.nightexpress.nightcore.util.text.tag.impl; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.decorator.BaseColorDecorator; import su.nightexpress.nightcore.util.text.tag.api.ContentTag; import su.nightexpress.nightcore.util.text.tag.api.Tag; @@ -21,12 +22,15 @@ public class HexColorTag extends Tag implements ContentTag { public BaseColorDecorator parse(@NotNull String tagContent) { if (tagContent.length() < 7) return null; - try { - Color color = Color.decode(tagContent); - return new BaseColorDecorator(color); - } - catch (NumberFormatException exception) { - return null; - } + Color color = TagUtils.colorFromHexString(tagContent); + return new BaseColorDecorator(color); + +// try { +// Color color = Color.decode(tagContent); +// return new BaseColorDecorator(color); +// } +// catch (NumberFormatException exception) { +// return null; +// } } } diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ShortHexColorTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ShortHexColorTag.java index 6acb2f7..962cd21 100644 --- a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ShortHexColorTag.java +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ShortHexColorTag.java @@ -2,6 +2,7 @@ package su.nightexpress.nightcore.util.text.tag.impl; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.text.tag.TagUtils; import su.nightexpress.nightcore.util.text.tag.decorator.BaseColorDecorator; import su.nightexpress.nightcore.util.text.tag.api.ContentTag; import su.nightexpress.nightcore.util.text.tag.api.Tag; @@ -21,12 +22,15 @@ public class ShortHexColorTag extends Tag implements ContentTag { public BaseColorDecorator parse(@NotNull String tagContent) { if (tagContent.length() < 7) return null; - try { - Color color = Color.decode(tagContent); - return new BaseColorDecorator(color); - } - catch (NumberFormatException exception) { - return null; - } + Color color = TagUtils.colorFromHexString(tagContent); + return new BaseColorDecorator(color); + +// try { +// Color color = Color.decode(tagContent); +// return new BaseColorDecorator(color); +// } +// catch (NumberFormatException exception) { +// return null; +// } } } diff --git a/src/main/java/su/nightexpress/nightcore/util/version/VersionComponent.java b/src/main/java/su/nightexpress/nightcore/util/version/VersionComponent.java new file mode 100644 index 0000000..a179d4b --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/version/VersionComponent.java @@ -0,0 +1,6 @@ +package su.nightexpress.nightcore.util.version; + +public enum VersionComponent { + ENTITY_ID_GENERATOR, + ITEM_NBT_COMPRESSOR +} diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniSound.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniSound.java index 3ed9b99..c58e4cb 100644 --- a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniSound.java +++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniSound.java @@ -10,6 +10,7 @@ import su.nightexpress.nightcore.config.ConfigValue; import su.nightexpress.nightcore.config.FileConfig; import su.nightexpress.nightcore.util.StringUtil; +@Deprecated public class UniSound { private final String soundName; diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniTask.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniTask.java index c443172..790e72d 100644 --- a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniTask.java +++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniTask.java @@ -3,6 +3,7 @@ package su.nightexpress.nightcore.util.wrapper; import org.jetbrains.annotations.NotNull; import su.nightexpress.nightcore.NightCorePlugin; +@Deprecated public class UniTask { private final NightCorePlugin plugin; @@ -16,6 +17,14 @@ public class UniTask { this(plugin, runnable, 0L); } + public UniTask(@NotNull NightCorePlugin plugin, @NotNull Runnable runnable, int interval) { + this(plugin, runnable, interval, false); + } + + public UniTask(@NotNull NightCorePlugin plugin, @NotNull Runnable runnable, int interval, boolean async) { + this(plugin, runnable, interval * 20L, async); + } + public UniTask(@NotNull NightCorePlugin plugin, @NotNull Runnable runnable, long interval) { this(plugin, runnable, interval, false); } @@ -23,25 +32,29 @@ public class UniTask { public UniTask(@NotNull NightCorePlugin plugin, @NotNull Runnable runnable, long interval, boolean async) { this.plugin = plugin; this.runnable = runnable; - this.setTicksInterval(interval); - this.setAsync(async); + this.interval = interval; + this.async = async; this.taskId = -1; } + @Deprecated public UniTask setSecondsInterval(int interval) { return this.setTicksInterval(interval * 20L); } + @Deprecated public UniTask setTicksInterval(long interval) { this.interval = interval; return this; } + @Deprecated public UniTask setAsync() { return this.setAsync(true); } + @Deprecated public UniTask setAsync(boolean async) { this.async = async; return this; diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 720f2af..76a3b84 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,10 +1,10 @@ name: nightcore main: su.nightexpress.nightcore.NightCore version: '${project.version}' -description: Plugin Creation Kit. +description: Plugin core author: NightExpress -api-version: 1.18 +api-version: 1.19 load: STARTUP libraries: - - com.zaxxer:HikariCP:5.0.1 + - com.zaxxer:HikariCP:6.0.0 - it.unimi.dsi:fastutil-core:8.5.13 \ No newline at end of file