v2.7.0-beta

This commit is contained in:
nulli0n committed 2024-10-31 21:39:29 +05:00
1 parent 6a88a81a24
commit a34c655315
135 files changed
+4305 -816

No files matched your search

+4 -25
View File
@@ -6,7 +6,7 @@
<groupId>su.nightexpress.nightcore</groupId>
<artifactId>nightcore</artifactId>
<version>2.6.4</version>
<version>2.7.0</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
@@ -20,17 +20,9 @@
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<!--<repository>
<id>papermc</id>
<url>https://repo.papermc.io/repository/maven-public/</url>
</repository>-->
<repository>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
@@ -66,25 +58,12 @@
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.21</version>
</dependency>
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>1.20.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>-->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>5.0.1</version>
</dependency>
<dependency>
<groupId>com.mojang</groupId>
<artifactId>authlib</artifactId>
<version>5.0.47</version>
<version>6.0.0</version>
</dependency>
<dependency>
@@ -96,7 +75,7 @@
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.41.2.2</version>
<version>3.46.1.3</version>
</dependency>
<dependency>
@@ -115,7 +94,7 @@
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.11.2</version>
<version>2.11.6</version>
<scope>provided</scope>
</dependency>
@@ -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<NightCorePlugin> childrens;
private final CoreManager coreManager;
private final Set<NightPlugin> 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<NightCorePlugin> getChildrens() {
public Set<NightPlugin> 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);
}
}
@@ -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();
}
@@ -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<U extends DataUser> extends NightPlugin {
@Override
@@ -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<Runnable> 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();
}
@@ -69,6 +69,7 @@ public class CommandManager extends SimpleManager<NightPlugin> {
}
@NotNull
@Deprecated
public Set<NightPluginCommand> getCommands() {
return this.commands;
}
@@ -79,6 +80,7 @@ public class CommandManager extends SimpleManager<NightPlugin> {
}
@NotNull
@Deprecated
public BaseCommand getMainCommand() {
return this.mainCommand;
}
@@ -102,6 +104,7 @@ public class CommandManager extends SimpleManager<NightPlugin> {
.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<NightPlugin> {
return false;
}
@Deprecated
public boolean unregisterCommand(@NotNull NightPluginCommand command) {
if (this.commands.remove(command)) {
return CommandUtil.unregister(command.getAliases()[0]);
@@ -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 = (string, context) -> string;
public static final ArgumentParser<Boolean> BOOLEAN = (string, context) -> Boolean.parseBoolean(string);
public static final ArgumentParser<Integer> INTEGER = (string, context) -> NumberUtil.parseInteger(string).orElse(null);
public static final ArgumentParser<Integer> INTEGER_ABS = (string, context) -> NumberUtil.parseInteger(string).map(Math::abs).orElse(null);
public static final ArgumentParser<Double> DOUBLE = (string, context) -> NumberUtil.parseDouble(string).orElse(null);
public static final ArgumentParser<Double> DOUBLE_ABS = (string, context) -> NumberUtil.parseDouble(string).map(Math::abs).orElse(null);
public static final ArgumentParser<Player> PLAYER = (string, context) -> Players.getPlayer(string);
public static final ArgumentParser<World> WORLD = (string, context) -> Bukkit.getWorld(string);
public static final ArgumentParser<Material> MATERIAL = (string, context) -> BukkitThing.getMaterial(string);
public static final ArgumentParser<Material> ITEM_MATERIAL = (string, context) -> {
public static final ArgumentParser<String> STRING = (string, context) -> string;
public static final ArgumentParser<Boolean> BOOLEAN = (string, context) -> Boolean.parseBoolean(string);
public static final ArgumentParser<Integer> INTEGER = (string, context) -> NumberUtil.parseInteger(string).orElse(null);
public static final ArgumentParser<Integer> INTEGER_ABS = (string, context) -> NumberUtil.parseInteger(string).map(Math::abs).orElse(null);
public static final ArgumentParser<Integer> INTEGER_COMPACT = (string, context) -> NumberUtil.parseIntCompact(string).orElse(null);
public static final ArgumentParser<Integer> INTEGER_COMPACT_ABS = (string, context) -> NumberUtil.parseIntCompact(string).map(Math::abs).orElse(null);
public static final ArgumentParser<Double> DOUBLE = (string, context) -> NumberUtil.parseDouble(string).orElse(null);
public static final ArgumentParser<Double> DOUBLE_ABS = (string, context) -> NumberUtil.parseDouble(string).map(Math::abs).orElse(null);
public static final ArgumentParser<Double> DOUBLE_COMPACT = (string, context) -> NumberUtil.parseCompact(string).orElse(null);
public static final ArgumentParser<Double> DOUBLE_COMPACT_ABS = (string, context) -> NumberUtil.parseCompact(string).map(Math::abs).orElse(null);
public static final ArgumentParser<Player> PLAYER = (string, context) -> Players.getPlayer(string);
public static final ArgumentParser<World> WORLD = (string, context) -> Bukkit.getWorld(string);
public static final ArgumentParser<Material> MATERIAL = (string, context) -> BukkitThing.getMaterial(string);
public static final ArgumentParser<Material> ITEM_MATERIAL = (string, context) -> {
Material material = BukkitThing.getMaterial(string);
return material == null || !material.isItem() ? null : material;
};
public static final ArgumentParser<Material> BLOCK_MATERIAL = (string, context) -> {
public static final ArgumentParser<Material> BLOCK_MATERIAL = (string, context) -> {
Material material = BukkitThing.getMaterial(string);
return material == null || !material.isBlock() ? null : material;
};
public static final ArgumentParser<Enchantment> ENCHANTMENT = (string, context) -> BukkitThing.getEnchantment(string);
public static final ArgumentParser<Enchantment> ENCHANTMENT = (string, context) -> BukkitThing.getEnchantment(string);
//public static final ArgumentParser<PotionEffectType> POTION_EFFECT = BukkitThing::getPotionEffect;
//public static final ArgumentParser<Attribute> ATTRIBUTE = BukkitThing::getAttribute;
@@ -48,28 +54,47 @@ public class ArgumentTypes {
@NotNull
public static ArgumentBuilder<Integer> 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<Integer> 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<Integer> integerCompact(@NotNull String name) {
return numeric(name, INTEGER_COMPACT);
}
@NotNull
public static ArgumentBuilder<Integer> integerCompactAbs(@NotNull String name) {
return numeric(name, INTEGER_COMPACT_ABS);
}
@NotNull
public static ArgumentBuilder<Double> 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<Double> decimalAbs(@NotNull String name) {
return CommandArgument.builder(name, DOUBLE_ABS)
return numeric(name, DOUBLE_ABS);
}
@NotNull
public static ArgumentBuilder<Double> decimalCompact(@NotNull String name) {
return numeric(name, DOUBLE_COMPACT);
}
@NotNull
public static ArgumentBuilder<Double> decimalCompactAbs(@NotNull String name) {
return numeric(name, DOUBLE_COMPACT_ABS);
}
@NotNull
private static <T extends Number> ArgumentBuilder<T> numeric(@NotNull String name, @NotNull ArgumentParser<T> 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
@@ -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) {
@@ -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());
@@ -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<T> {
@@ -117,6 +117,7 @@ public class ConfigValue<T> {
}
@NotNull
@Deprecated
public static ConfigValue<UniSound> create(@NotNull String path, @NotNull UniSound defaultValue, @Nullable String... description) {
Reader<UniSound> reader = (cfg, path1, def) -> UniSound.read(cfg, path1);
Writer<UniSound> writer = (cfg, path1, obj) -> obj.write(cfg, path1);
@@ -124,6 +125,14 @@ public class ConfigValue<T> {
return create(path, reader, writer, defaultValue, description);
}
@NotNull
public static ConfigValue<NightSound> create(@NotNull String path, @NotNull NightSound defaultValue, @Nullable String... description) {
Reader<NightSound> reader = (cfg, readPath, def) -> NightSound.read(cfg, readPath);
Writer<NightSound> writer = (cfg, writePath, sound) -> sound.write(cfg, writePath);
return create(path, reader, writer, defaultValue, description);
}
@NotNull
public static ConfigValue<UniParticle> create(@NotNull String path, @NotNull UniParticle defaultValue, @Nullable String... description) {
Reader<UniParticle> reader = (cfg, path1, def) -> UniParticle.read(cfg, path1);
@@ -170,6 +179,7 @@ public class ConfigValue<T> {
}
@NotNull
@Deprecated
public static <K, V> ConfigValue<Map<K, V>> forMap(@NotNull String path,
@NotNull Function<String, K> keyFun,
@NotNull TriFunction<FileConfig, String, String, V> valFun,
@@ -180,6 +190,7 @@ public class ConfigValue<T> {
}
@NotNull
@Deprecated
public static <K, V> ConfigValue<Map<K, V>> forMap(@NotNull String path,
@NotNull Function<String, K> keyFun,
@NotNull TriFunction<FileConfig, String, String, V> valFun,
@@ -190,6 +201,7 @@ public class ConfigValue<T> {
}
@NotNull
@Deprecated
public static <K, V> ConfigValue<TreeMap<K, V>> forTreeMap(@NotNull String path,
@NotNull Function<String, K> keyFun,
@NotNull TriFunction<FileConfig, String, String, V> valFun,
@@ -199,6 +211,7 @@ public class ConfigValue<T> {
}
@NotNull
@Deprecated
public static <K, V> ConfigValue<TreeMap<K, V>> forTreeMap(@NotNull String path,
@NotNull Function<String, K> keyFun,
@NotNull TriFunction<FileConfig, String, String, V> valFun,
@@ -208,6 +221,7 @@ public class ConfigValue<T> {
}
@NotNull
@Deprecated
public static <K, V, M extends Map<K, V>> ConfigValue<M> forMap(@NotNull String path,
@NotNull Function<String, K> keyFun,
@NotNull TriFunction<FileConfig, String, String, V> valFun,
@@ -230,6 +244,68 @@ public class ConfigValue<T> {
}
@NotNull
public static <K, V extends Writeable> ConfigValue<Map<K, V>> forMap(@NotNull String path,
@NotNull Function<String, K> keyReadFun,
@NotNull Function<K, String> keyWriteFun,
@NotNull BiFunction<FileConfig, String, V> valReadFun,
//@NotNull Supplier<Map<K, V>> mapSupplier,
@NotNull Consumer<Map<K, V>> defaultValue,
@Nullable String... description) {
Reader<Map<K, V>> reader = (cfg, readPath, def) -> {
var map = new HashMap<K, V>();//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<Map<K, V>> 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<K, V> defaultMap = new LinkedHashMap<>();
defaultValue.accept(defaultMap);
return create(path, reader, writer, defaultMap, description);
}
// @NotNull
// public static <K, V extends Writeable> ConfigValue<HashMap<K, V>> forHashMap(@NotNull String path,
// @NotNull Function<String, K> keyReadFun,
// @NotNull Function<K, String> keyWriteFun,
// @NotNull BiFunction<FileConfig, String, V> valReadFun,
// @NotNull Consumer<HashMap<K, V>> defaultValue,
// @Nullable String... description) {
// return forMap(path, keyReadFun, keyWriteFun, valReadFun, HashMap::new, defaultValue, description);
// }
@NotNull
public static <V extends Writeable> ConfigValue<Map<String, V>> forMapById(@NotNull String path,
@NotNull BiFunction<FileConfig, String, V> valReadFun,
@NotNull Consumer<Map<String, V>> defaultValue,
@Nullable String... description) {
return forMap(path, String::toLowerCase, key -> key, valReadFun, defaultValue, description);
}
@NotNull
public static <E extends Enum<E>, V extends Writeable> ConfigValue<Map<E, V>> forMapByEnum(@NotNull String path,
@NotNull Class<E> clazz,
@NotNull BiFunction<FileConfig, String, V> valReadFun,
@NotNull Consumer<Map<E, V>> defaultValue,
@Nullable String... description) {
return forMap(path, str -> StringUtil.getEnum(str, clazz).orElse(null), Enum::name, valReadFun, defaultValue, description);
}
@NotNull
@Deprecated
public static <V> ConfigValue<Map<String, V>> forMap(@NotNull String path,
@NotNull TriFunction<FileConfig, String, String, V> function,
@NotNull Writer<Map<String, V>> writer,
@@ -239,6 +315,7 @@ public class ConfigValue<T> {
}
@NotNull
@Deprecated
public static <V> ConfigValue<Map<String, V>> forMap(@NotNull String path,
@NotNull TriFunction<FileConfig, String, String, V> function,
@NotNull Writer<Map<String, V>> writer,
@@ -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;
@@ -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;
@@ -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);
}
@@ -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<Boolean> 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<Map<String, Color>> 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<String, Color> map = new HashMap<>();
map.put("aqua", Color.CYAN);
return map;
},
"Here you can define custom colors to use it in all nightcore plugins like <aqua>Text</aqua>.",
"You can also override default ones."
"[Default is true]"
);
public static final ConfigValue<Long> 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<Boolean> USER_DEBUG_ENABLED = ConfigValue.create("UserData.Debug",
false,
"Enables debug messages for user data management.",
"[Default is false]");
// @Deprecated
// public static final ConfigValue<Boolean> USER_DEBUG_ENABLED = ConfigValue.create("UserData.Debug",
// false,
// "Enables debug messages for user data management.",
// "[Default is false]");
@Deprecated
public static final ConfigValue<Integer> 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<Boolean> 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<Boolean> 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<Boolean> 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<Boolean> 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<Boolean> 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<UniFormatter> NUMBER_FORMAT = ConfigValue.create("Engine.Number_Format",
public static final ConfigValue<UniFormatter> 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<Integer> 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<Map<String, NumberShortcut>> 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."
);
}
@@ -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) {
@@ -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<NightCore> {
public CoreManager(@NotNull NightCore plugin) {
@@ -21,21 +23,25 @@ public class CoreManager extends AbstractManager<NightCore> {
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());
}
});
}
}
@@ -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() + ":")) +
@@ -16,8 +16,8 @@ public class CoreListener extends AbstractListener<NightCore> {
}
@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);
}
}
@@ -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;
@@ -24,6 +24,7 @@ import java.util.List;
import java.util.Optional;
import java.util.function.Function;
@Deprecated
public abstract class AbstractDataHandler<P extends NightCorePlugin> extends AbstractManager<P> {
protected final DatabaseConfig config;
@@ -150,11 +151,6 @@ public abstract class AbstractDataHandler<P extends NightCorePlugin> extends Abs
return UpdateEntity.create(values, conditions);
}
// @NotNull
// public UpdateQuery updateQuery(@NotNull String table, @NotNull List<SQLValue> values, @NotNull List<SQLCondition> conditions) {
// return UpdateQuery.create(table, values, conditions);
// }
//
public void executeUpdate(@NotNull String table, @NotNull List<SQLValue> values, @NotNull List<SQLCondition> conditions) {
this.executeUpdate(UpdateQuery.create(table, values, conditions));
}
@@ -163,11 +159,6 @@ public abstract class AbstractDataHandler<P extends NightCorePlugin> extends Abs
SQLQueries.executeUpdate(this.connector, query);
}
// @Deprecated
// public void executeUpdates(@NotNull UpdateQuery queries) {
// SQLQueries.executeUpdates(this.connector, queries);
// }
@@ -8,6 +8,7 @@ import su.nightexpress.nightcore.NightCorePlugin;
import java.util.UUID;
@Deprecated
public abstract class AbstractUser<P extends NightCorePlugin> implements DataUser {
protected final P plugin;
@@ -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<P extends NightDataPlugin<U>, U extends DataUser> extends AbstractDataHandler<P> {
protected static final SQLColumn COLUMN_USER_ID = SQLColumn.of("uuid", ColumnType.STRING);
@@ -83,8 +83,7 @@ public abstract class AbstractUserDataHandler<P extends NightDataPlugin<U>, 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() {
@@ -15,6 +15,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Supplier;
@Deprecated
public abstract class AbstractUserManager<P extends NightDataPlugin<U>, U extends DataUser> extends AbstractManager<P> {
private final UserdataConfig config;
@@ -34,7 +35,7 @@ public abstract class AbstractUserManager<P extends NightDataPlugin<U>, 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<P extends NightDataPlugin<U>, 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<P extends NightDataPlugin<U>, 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<P extends NightDataPlugin<U>, 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);
}
@@ -7,6 +7,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.UUID;
@Deprecated
public interface DataUser {
void onLoad();
@@ -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;
}
@@ -1,5 +1,6 @@
package su.nightexpress.nightcore.database;
@Deprecated
public enum DatabaseType {
MYSQL,
@@ -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 +
'}';
}
}
@@ -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) {
@@ -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) {
@@ -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<P extends NightDataPlugin<U>, U extends DataUser> extends AbstractListener<P> {
private final AbstractUserManager<? extends NightDataPlugin<U>, U> userManager;
@@ -31,9 +31,9 @@ public class UserListener<P extends NightDataPlugin<U>, 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);
@@ -6,6 +6,7 @@ import su.nightexpress.nightcore.util.ItemNbt;
import java.lang.reflect.Type;
@Deprecated
public class ItemStackSerializer implements JsonSerializer<ItemStack>, JsonDeserializer<ItemStack> {
@Override
@@ -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;
@@ -2,6 +2,7 @@ package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
@Deprecated
public class SQLCondition {
private final SQLValue value;
@@ -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<T> {
protected final String table;
@@ -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) {
@@ -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() + " ?";
}
}
@@ -2,6 +2,7 @@ package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
@Deprecated
public class SQLValue {
private final SQLColumn column;
@@ -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) -> {
@@ -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);
@@ -14,6 +14,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Deprecated
public final class AlterTableExecutor extends SQLExecutor<Void> {
private final DatabaseType databaseType;
@@ -13,6 +13,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Deprecated
public final class CreateTableExecutor extends SQLExecutor<Void> {
private final DatabaseType databaseType;
@@ -12,6 +12,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Deprecated
public final class DeleteQueryExecutor extends SQLExecutor<Void> {
private final List<SQLCondition> wheres;
@@ -12,6 +12,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Deprecated
public final class InsertQueryExecutor extends SQLExecutor<Void> {
private final List<SQLValue> values;
@@ -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<Void> {
private final DatabaseType databaseType;
@@ -11,6 +11,7 @@ import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
@Deprecated
public final class SelectQueryExecutor<T> extends SQLExecutor<List<T>> {
private final List<SQLColumn> columns;
@@ -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;
}
}
@@ -8,6 +8,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Deprecated
public class UpdateEntity {
private final List<String> columnNames;
@@ -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<UpdateEntity> entities;
@@ -73,48 +74,4 @@ public class UpdateQuery /*extends AbstractQuery*/ {
public List<UpdateEntity> getEntities() {
return entities;
}
/*@NotNull
public static UpdateQuery create(@NotNull String table, @NotNull List<SQLValue> values) {
return create(table, values, Collections.emptyList());
}
@NotNull
public static UpdateQuery create(@NotNull String table, @NotNull List<SQLValue> values, @NotNull List<SQLCondition> conditions) {
List<String> columnNames = new ArrayList<>();
List<String> columnValues = new ArrayList<>();
List<String> whereColumns = new ArrayList<>();
List<String> 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<String> getValues() {
return values;
}
@NotNull
public List<String> getWheres() {
return wheres;
}*/
}
@@ -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<P extends NightPlugin> extends AbstractManager<P> {
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<Column> 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 <T> void insert(@NotNull String table, @NotNull InsertQuery<T> query, @NotNull T entity) {
this.executeUpdate(table, query, entity);
}
public <T> void insert(@NotNull String table, @NotNull InsertQuery<T> query, @NotNull Collection<T> entities) {
this.executeUpdate(table, query, entities);
}
public <T> void update(@NotNull String table, @NotNull UpdateQuery<T> query, @NotNull T entity) {
this.executeUpdate(table, query, entity);
}
public <T> void update(@NotNull String table, @NotNull UpdateQuery<T> query, @NotNull Collection<T> entities) {
this.executeUpdate(table, query, entities);
}
public <T> void delete(@NotNull String table, @NotNull DeleteQuery<T> query, @NotNull T entity) {
this.executeUpdate(table, query, entity);
}
public <T> void delete(@NotNull String table, @NotNull DeleteQuery<T> query, @NotNull Collection<T> entities) {
this.executeUpdate(table, query, entities);
}
public <T> void executeUpdate(@NotNull String table, @NotNull AbstractQuery<T> query, @NotNull T entity) {
SQLQueries.executeQuery(this.connector, table, query, entity);
}
public <T> void executeUpdate(@NotNull String table, @NotNull AbstractQuery<T> query, @NotNull Collection<T> entities) {
SQLQueries.executeQuery(this.connector, table, query, entities);
}
public boolean contains(@NotNull String table, @NotNull Consumer<SelectQuery<Boolean>> consumer) {
return this.selectFirst(table, resultSet -> true, consumer) != null;
}
@Nullable
public <T> T selectFirst(@NotNull String table, @NotNull Function<ResultSet, T> function, @NotNull Consumer<SelectQuery<T>> consumer) {
SelectQuery<T> query = new SelectQuery<>(function);
consumer.accept(query);
return this.selectFirst(table, query);
}
@NotNull
public <T> List<T> select(@NotNull String table, @NotNull Function<ResultSet, T> function, @NotNull Consumer<SelectQuery<T>> consumer) {
SelectQuery<T> query = new SelectQuery<>(function);
consumer.accept(query);
return this.select(table, query);
}
@Nullable
public <T> T selectFirst(@NotNull String table, @NotNull SelectQuery<T> query) {
List<T> list = this.select(table, query);
return list.isEmpty() ? null : list.get(0);
}
@NotNull
public <T> List<T> select(@NotNull String table, @NotNull SelectQuery<T> query) {
return SQLQueries.executeSelect(this.connector, table, query);
}
}
@@ -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 + "]";
}
}
@@ -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 <P extends NightPlugin, U extends AbstractUser> extends AbstractDataManager<P> {
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<ResultSet, U> 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<ResultSet, U> createUserFunction();
protected void createUserTable() {
List<Column> 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<?, U> query);
//protected abstract void addInsertQueryData(@NotNull InsertQuery<U> query);
//protected abstract void addUpdateQueryData(@NotNull UpdateQuery<U> query);
protected abstract void addSelectQueryData(@NotNull SelectQuery<U> query);
protected abstract void addTableColumns(@NotNull List<Column> columns);
@NotNull
public List<U> 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<SelectQuery<U>> consumer) {
SelectQuery<U> 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<U> users) {
UpdateQuery<U> query = UserQueries.update();
this.addUpsertQueryData(query);
this.update(this.tableUsers, query, users);
}
public void insertUser(@NotNull U user) {
InsertQuery<U> 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);
}
}
@@ -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<P extends NightPlugin, U extends AbstractUser> extends AbstractManager<P> {
private final UserdataConfig config;
private final AbstractUserDataManager<P, U> dataManager;
private final Map<UUID, U> loadedByIdMap;
private final Map<String, U> loadedByNameMap;
public AbstractUserManager(@NotNull P plugin, @NotNull AbstractUserDataManager<P, U> 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<U> 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<U> getUserDataAsync(@NotNull String name) {
return CompletableFuture.supplyAsync(() -> this.getOrFetch(name));
}
public final CompletableFuture<U> getUserDataAsync(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> this.getOrFetch(uuid));
}
/**
* Performs an operation on the given user.<br>
* Runs immediately in the current thread if player is online or data is already loaded.<br>
* 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<U> consumer) {
this.manageUser(() -> this.getLoaded(name), () -> this.getUserDataAsync(name), consumer);
}
/**
* Performs an operation on the given user.<br>
* Runs immediately in the current thread if player is online or data is already loaded.<br>
* 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<U> consumer) {
this.manageUser(() -> this.getLoaded(playerId), () -> this.getUserDataAsync(playerId), consumer);
}
/**
* Performs an operation on the given user.<br>
* Runs immediately in the current thread if player is online or data is already loaded.<br>
* 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<U> consumer) {
this.manageUserSynchronized(() -> this.getLoaded(name), () -> this.getUserDataAsync(name), consumer);
}
/**
* Performs an operation on the given user.<br>
* Runs immediately in the current thread if player is online or data is already loaded.<br>
* 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<U> consumer) {
this.manageUserSynchronized(() -> this.getLoaded(playerId), () -> this.getUserDataAsync(playerId), consumer);
}
private void manageUser(@NotNull Supplier<U> loadedSupplier, @NotNull Supplier<CompletableFuture<U>> fetchSupplier, @NotNull Consumer<U> consumer) {
U user = loadedSupplier.get();
if (user != null) {
consumer.accept(user);
}
else fetchSupplier.get().thenAccept(consumer);
}
private void manageUserSynchronized(@NotNull Supplier<U> loadedSupplier, @NotNull Supplier<CompletableFuture<U>> fetchSupplier, @NotNull Consumer<U> 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.<br>
* Users that are already loaded won't be replaced by ones from the database, however they will be fetched anyway.
*/
@NotNull
public Set<U> getAll() {
Set<U> users = this.getLoaded();
this.dataManager.getUsers().stream().filter(user -> !this.isLoaded(user.getId())).forEach(users::add);
return users;
}
@NotNull
public Set<U> getLoaded() {
return new HashSet<>(this.loadedByIdMap.values());
}
@NotNull
public Map<UUID, U> getLoadedByIdMap() {
return this.loadedByIdMap;
}
@NotNull
public Map<String, U> 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());
}
}
@@ -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;
}
}
@@ -0,0 +1,7 @@
package su.nightexpress.nightcore.db.config;
public enum DatabaseType {
MYSQL,
SQLITE,
}
@@ -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 +
'}';
}
}
@@ -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();
}
}
@@ -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());
}
}
@@ -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);
}
}
@@ -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<P extends NightPlugin, U extends AbstractUser> extends AbstractListener<P> {
private final AbstractUserManager<P, U> manager;
public UserListener(@NotNull P plugin, @NotNull AbstractUserManager<P, U> 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.
}
}
@@ -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;
}
}
@@ -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);
}
@@ -0,0 +1,31 @@
package su.nightexpress.nightcore.db.sql.query;
import org.jetbrains.annotations.NotNull;
import java.util.function.Function;
public class QueryValue<T> {
private final String sqlPart;
private final Function<T, String> statementPart;
public QueryValue(String sqlPart, Function<T, String> 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<T, String> getStatementPart() {
return this.statementPart;
}
}
@@ -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<Column> 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 <T> void executeQuery(@NotNull AbstractConnector connector, @NotNull String table, @NotNull AbstractQuery<T> query, @NotNull T entity) {
executeQuery(connector, table, query, Lists.newList(entity));
}
public static <T> void executeQuery(@NotNull AbstractConnector connector, @NotNull String table, @NotNull AbstractQuery<T> query, @NotNull Collection<T> 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 <T> List<T> executeSelect(@NotNull AbstractConnector connector, @NotNull String table, @NotNull SelectQuery<T> query) {
ArrayList<T> 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;
}
}
@@ -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<Long> deleteByLastOnline() {
return new DeleteQuery<Long>().where(AbstractUserDataManager.COLUMN_USER_LAST_ONLINE, WhereOperator.SMALLER, String::valueOf);
}
@NotNull
public static DeleteQuery<UUID> deleteByUUID() {
return new DeleteQuery<UUID>().where(AbstractUserDataManager.COLUMN_USER_ID, WhereOperator.EQUAL, String::valueOf);
}
@NotNull
public static <U extends AbstractUser> UpdateQuery<U> update() {
return new UpdateQuery<U>()
.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 <U extends AbstractUser> InsertQuery<U> insert() {
return new InsertQuery<U>()
.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()));
}
}
@@ -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<T> extends ConditionalQuery<DeleteQuery<T>, T> {
public DeleteQuery() {
}
@Override
protected DeleteQuery<T> 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));
}
}
}
@@ -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<T> extends AbstractQuery<T> implements ValuedQuery<InsertQuery<T>, T> {
private final List<QueryValue<T>> 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<T> setValue(@NotNull Column column, @NotNull Function<T, String> 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);
}
}
@@ -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<T> extends ConditionalQuery<SelectQuery<T>, ArrayList<T>> {
private final List<String> columns;
private final Function<ResultSet, T> dataFunction;
private int amount;
public SelectQuery(@NotNull Function<ResultSet, T> dataFunction) {
this.columns = new ArrayList<>();
this.dataFunction = dataFunction;
this.amount = -1;
}
@Override
protected SelectQuery<T> 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<T> 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<T> limit(int amount) {
this.amount = Math.abs(amount);
return this;
}
@NotNull
public SelectQuery<T> all() {
this.columns.clear();
this.columns.add("*");
return this;
}
@NotNull
public SelectQuery<T> column(@NotNull Column column) {
this.columns.add(column.getNameEscaped());
return this;
}
@NotNull
public SelectQuery<T> where(@NotNull Column column, @NotNull WhereOperator operator, @NotNull String value) {
return super.where(column, operator, obj -> value);
}
@NotNull
public SelectQuery<T> 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);
}
}
@@ -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<T> extends ConditionalQuery<UpdateQuery<T>, T> implements ValuedQuery<UpdateQuery<T>, T> {
private final List<QueryValue<T>> dataColumns;
public UpdateQuery() {
this.dataColumns = new ArrayList<>();
}
@Override
protected UpdateQuery<T> 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<T> setValue(@NotNull Column column, @NotNull Function<T, String> 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);
}
}
@@ -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<T> {
@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);
}
@@ -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<Q extends ConditionalQuery<Q, T>, T> extends AbstractQuery<T> {
protected final List<QueryValue<T>> 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<T, String> 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<T, String> 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);
}
}
@@ -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<Q extends ValuedQuery<Q, T>, T> {
@NotNull Q setValue(@NotNull Column column, @NotNull Function<T, String> function);
}
@@ -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() + " ?";
}
}
@@ -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;
}
}
@@ -54,7 +54,7 @@ public class DialogListener extends AbstractListener<NightCore> {
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;
@@ -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
@@ -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> T getProvider(@NotNull Class<T> clazz) {
RegisteredServiceProvider<T> provider = Bukkit.getServer().getServicesManager().getRegistration(clazz);
RegisteredServiceProvider<T> 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();
}
}
@@ -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() {
@@ -90,8 +90,8 @@ public class LangManager extends SimpleManager<NightCorePlugin> {
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;
}
@@ -4,7 +4,7 @@ import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.FileConfig;
public abstract class LangEntry<T> {
public abstract class LangEntry/*<T>*/ {
protected final String path;
protected final String defaultText;
@@ -16,8 +16,8 @@ public abstract class LangEntry<T> {
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() {
@@ -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<Pair<String, List<String>>> {
public class LangItem extends LangEntry/*<Pair<String, List<String>>>*/ {
private final List<String> defaultLore;
@@ -47,8 +46,7 @@ public class LangItem extends LangEntry<Pair<String, List<String>>> {
}
@Override
@NotNull
public Pair<String, List<String>> 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<Pair<String, List<String>>> {
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) {
@@ -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<String> {
public class LangString extends LangEntry {
private String string;
private TextRoot message;
@@ -31,15 +31,14 @@ public class LangString extends LangEntry<String> {
}
@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
@@ -10,7 +10,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LangText extends LangEntry<LangMessage> {
public class LangText extends LangEntry {
private LangMessage message;
@@ -40,8 +40,7 @@ public class LangText extends LangEntry<LangMessage> {
}
@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<LangMessage> {
this.setMessage(LangMessage.parse(plugin, String.join(Placeholders.TAG_LINE_BREAK, text)));
return this.getMessage();
//return this.getMessage();
}
@NotNull
@@ -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<List<String>> replacer) {
List<String> list = new ArrayList<>();
replacer.accept(list);
@@ -196,11 +206,13 @@ public class LangMessage {
}
@NotNull
@Deprecated
public LangMessage replace(@NotNull String var, @NotNull List<String> replacer) {
return this.replace(str -> str.replace(var, String.join(Placeholders.TAG_LINE_BREAK, replacer)));
}
@NotNull
@Deprecated
public LangMessage replace(@NotNull UnaryOperator<String> 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<Replacer> 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]) : "";
@@ -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;
@@ -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<P extends NightCorePlugin> extends SimpleManager<P> {
protected final Set<SimpeListener> listeners;
protected final List<UniTask> tasks;
protected final List<UniTask> tasks;
protected final List<NightTask> 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<P extends NightCorePlugin> 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);
}
}
}
@@ -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() {
@@ -166,9 +166,10 @@ public abstract class ConfigMenu<P extends NightCorePlugin> extends AbstractMenu
if (clickType == null) continue;
List<String> 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<String> commands = commandMap.getOrDefault(ClickType.from(event), Collections.emptyList());
@@ -11,8 +11,8 @@ import java.util.function.Predicate;
public class ItemOptions {
private Predicate<MenuViewer> visibilityPolicy;
private Predicate<MenuViewer> weakPolicy;
private Predicate<MenuViewer> visibilityPolicy;
private Predicate<MenuViewer> weakPolicy;
private BiConsumer<MenuViewer, ItemStack> displayModifier;
public ItemOptions() {
@@ -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<String> worldNames() {
return Bukkit.getServer().getWorlds().stream().map(WorldInfo::getName).toList();
}
@Nullable
public static <T extends Keyed> T fromRegistry(@NotNull Registry<T> 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);
}
@@ -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)) {
@@ -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) {
@@ -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) {
@@ -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<UnaryOperator<String>> operatorCache;
//private final PlaceholderMap placeholderCache;
//private final List<UnaryOperator<String>> operatorCache;
private final Replacer replacer;
private String displayName;
private List<String> 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<UnaryOperator<String>> operators = new ArrayList<>(this.operatorCache);
operators.add(this.placeholderCache.replacer());
//List<UnaryOperator<String>> 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<String> 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<String> operator) {
//create(itemStack).trimmed().readMeta().replace(replacer).writeMeta();
create(itemStack).readMeta().replacement(replacer -> replacer.replace(operator)).writeMeta();
}
public static <T> void replace(@NotNull ItemStack itemStack, @NotNull PlaceholderList<T> 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<String> 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<String> 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<String> value) {
return this.cachePlaceholder(placeholder, value);
}
@NotNull
@Deprecated
public ItemReplacer replace(@NotNull String placeholder, @NotNull List<String> replacer) {
return this.cacheOperator(str -> str.replace(placeholder, String.join("\n", replacer)));
}
@NotNull
@Deprecated
public <T> ItemReplacer replace(@NotNull String placeholder, @NotNull PlaceholderList<T> placeholderList, @NotNull T source) {
return this.cacheOperator(placeholderList.replacer(source));
}
public ItemReplacer replacement(@NotNull Consumer<Replacer> 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<String> 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<String> fixed = fixLore(lore);
List<String> fixed = addEmptyLines(lore);
return NightMessage.asLegacy(fixed);
}
@NotNull
private List<String> fixLore(@NotNull List<String> lore) {
private List<String> addEmptyLines(@NotNull List<String> 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
@@ -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<Property> properties = profile.getProperties().get("textures");
Optional<Property> 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) {
@@ -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<String> 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<String> stripEmpty(@NotNull List<String> original) {
List<String> stripped = new ArrayList<>();
@@ -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<String> serialize(@NotNull Collection<Location> 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<Location> deserialize(@NotNull Collection<String> list) {
return new ArrayList<>(list.stream().map(LocationUtil::deserialize).filter(Objects::nonNull).toList());
}
@@ -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<Integer, String> ROMAN_MAP = new TreeMap<>();
private final static TreeMap<Integer, Supplier<String>> NUMERIC_MAP = new TreeMap<>();
//private final static TreeMap<Integer, Supplier<String>> 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<String, String> pair = formatCompact(value);
return pair.getFirst() + pair.getSecond();
}
@NotNull
public static Pair<String, String> 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<NumberShortcut> 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<String, String> 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<String, String> 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<NumberShortcut> 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<NumberShortcut> 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<Integer> parseIntCompact(@NotNull String input) {
return parseCompact(input).map(Double::intValue);
}
@NotNull
public static Optional<Double> parseCompact(@NotNull String input) {
input = input.toLowerCase();
double multiplier = 1D;
List<NumberShortcut> 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;
}
}
@@ -4,6 +4,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.Objects;
@Deprecated
public class Pair<F, S> {
private final F first;
@@ -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> PLAYER = new PlaceholderList<Player>()
.add(PLAYER_NAME, Player::getName)
.add(PLAYER_DISPLAY_NAME, Player::getDisplayName);
public static final PlaceholderList<Location> LOCATION = new PlaceholderList<Location>()
.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<CommandSender> SENDER = new PlaceholderList<CommandSender>()
.add(PLAYER_NAME, CommandSender::getName)
.add(PLAYER_DISPLAY_NAME, CommandSender::getName);
@NotNull
public static UnaryOperator<String> 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<String> 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<String> forPlayerWithPAPI(@NotNull Player player) {
return str -> setPlaceholderAPI(forPlayer(player).apply(str), player);
}
@NotNull
public static UnaryOperator<String> 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<String> 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);
}
}
@@ -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<Player> getOnline() {
return new HashSet<>(Bukkit.getServer().getOnlinePlayers());
}
@NotNull
public static List<String> playerNames() {
return playerNames(null);
@@ -32,31 +35,37 @@ public class Players {
@NotNull
public static List<String> 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<String> realPlayerNames() {
return realPlayerNames(null);
}
@NotNull
@Deprecated
public static List<String> realPlayerNames(@Nullable Player viewer) {
return playerNames(viewer, false);
}
@NotNull
@Deprecated
public static List<String> playerNames(@Nullable Player viewer, boolean includeCustom) {
Set<String> 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<String> 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);
}
}
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff. Show more