mirror of
https://github.com/darksaid98/nightcore-spigot.git
synced 2026-12-04 06:28:51 +00:00
v2.7.6
- Add support for the 'fallback' argument of the Translatable tag. - Apply PlaceholderAPI for menu titles if enabled in the menu config. - Split 'spigot' and 'paper' bridge into modules. - Full reload support for the nightcore plugin.
This commit is contained in:
1 parent
84addd3454
commit
12a85ce198
326 files changed
+3586
-1534
No files matched your search
+175
@@ -0,0 +1,175 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>su.nightexpress.nightcore</groupId>
|
||||
<artifactId>nightcore</artifactId>
|
||||
<version>2.7.6</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>main</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>21</maven.compiler.source>
|
||||
<maven.compiler.target>21</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spigot-repo</id>
|
||||
<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>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<id>opencollab-snapshot</id>
|
||||
<url>https://repo.opencollab.dev/maven-snapshots/</url>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<id>minecraft-repo</id>
|
||||
<url>https://libraries.minecraft.net/</url>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<id>jitpack.io</id>
|
||||
<url>https://jitpack.io</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>su.nightexpress.nightcore</groupId>
|
||||
<artifactId>bridge</artifactId>
|
||||
<version>2.7.6</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>su.nightexpress.nightcore</groupId>
|
||||
<artifactId>utils</artifactId>
|
||||
<version>2.7.6</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>su.nightexpress.nightcore</groupId>
|
||||
<artifactId>paper</artifactId>
|
||||
<version>2.7.6</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>su.nightexpress.nightcore</groupId>
|
||||
<artifactId>spigot</artifactId>
|
||||
<version>2.7.6</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.papermc.paper</groupId>
|
||||
<artifactId>paper-api</artifactId>
|
||||
<version>1.21.5-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.zaxxer</groupId>
|
||||
<artifactId>HikariCP</artifactId>
|
||||
<version>6.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.mojang</groupId>
|
||||
<artifactId>datafixerupper</artifactId>
|
||||
<version>8.0.16</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.xerial</groupId>
|
||||
<artifactId>sqlite-jdbc</artifactId>
|
||||
<version>3.47.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil-core</artifactId>
|
||||
<version>8.5.13</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.MilkBowl</groupId>
|
||||
<artifactId>VaultAPI</artifactId>
|
||||
<version>1.7</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>me.clip</groupId>
|
||||
<artifactId>placeholderapi</artifactId>
|
||||
<version>2.11.6</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.luckperms</groupId>
|
||||
<artifactId>api</artifactId>
|
||||
<version>5.4</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.geysermc.floodgate</groupId>
|
||||
<artifactId>api</artifactId>
|
||||
<version>2.2.0-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory> <!-- (your resources folder location) -->
|
||||
<filtering>true
|
||||
</filtering> <!-- this is the important part, it's what replaces, filters, all placeholders in the resources folder (such as ${project.version} in plugin.yml) -->
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.2.4</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputFile>${project.parent.basedir}\target\${project.parent.name}-${project.version}.jar
|
||||
</outputFile>
|
||||
<artifactSet>
|
||||
<includes>
|
||||
<include>su.nightexpress.nightcore:*</include>
|
||||
</includes>
|
||||
</artifactSet>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,142 @@
|
||||
package su.nightexpress.nightcore;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.integration.VaultHook;
|
||||
import su.nightexpress.nightcore.integration.permission.PermissionProvider;
|
||||
import su.nightexpress.nightcore.integration.permission.impl.LuckPermissionProvider;
|
||||
import su.nightexpress.nightcore.integration.permission.impl.VaultPermissionProvider;
|
||||
import su.nightexpress.nightcore.util.ItemNbt;
|
||||
import su.nightexpress.nightcore.util.Lists;
|
||||
import su.nightexpress.nightcore.util.Plugins;
|
||||
import su.nightexpress.nightcore.util.Version;
|
||||
import su.nightexpress.nightcore.util.bridge.Software;
|
||||
import su.nightexpress.nightcore.bridge.paper.PaperBridge;
|
||||
import su.nightexpress.nightcore.bridge.spigot.SpigotBridge;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class Engine {
|
||||
|
||||
private static final Set<NightPlugin> CHILDRENS = new HashSet<>();
|
||||
|
||||
private static NightCore core;
|
||||
private static Software software;
|
||||
private static PermissionProvider permissions;
|
||||
|
||||
@NotNull
|
||||
public static Set<NightPlugin> getChildrens() {
|
||||
return CHILDRENS;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static NightCore core() {
|
||||
if (core == null) throw new IllegalStateException("NightCore is not initialized!");
|
||||
|
||||
return core;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static Software software() {
|
||||
if (software == null) throw new IllegalStateException("Software is not initialized!");
|
||||
|
||||
return software;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PermissionProvider getPermissions() {
|
||||
return permissions;
|
||||
}
|
||||
|
||||
public static boolean hasPermissions() {
|
||||
return permissions != null;
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
if (Plugins.hasVault()) {
|
||||
VaultHook.shutdown();
|
||||
}
|
||||
|
||||
CHILDRENS.clear();
|
||||
permissions = null;
|
||||
core = null;
|
||||
}
|
||||
|
||||
private static void init(@NotNull NightCore instance) {
|
||||
core = instance;
|
||||
|
||||
Version version = Version.detect();
|
||||
if (version.isDropped()) return;
|
||||
|
||||
software = Version.isPaper() ? new PaperBridge() : new SpigotBridge();
|
||||
software.initialize();
|
||||
core.info("Server version detected as " + version.getLocalized() + ". Using " + software.getName() + ".");
|
||||
|
||||
ItemNbt.load(core);
|
||||
loadPermissionsProvider();
|
||||
|
||||
Plugins.detectPlugins();
|
||||
|
||||
if (Plugins.hasVault()) {
|
||||
VaultHook.load();
|
||||
}
|
||||
}
|
||||
|
||||
private static void loadPermissionsProvider() {
|
||||
if (Plugins.isInstalled(Plugins.LUCK_PERMS)) {
|
||||
permissions = new LuckPermissionProvider();
|
||||
}
|
||||
else if (Plugins.isInstalled(Plugins.VAULT)) {
|
||||
permissions = new VaultPermissionProvider();
|
||||
}
|
||||
else return;
|
||||
|
||||
core.info("Found permissions provider: " + permissions.getName());
|
||||
core.runTask(task -> permissions.setup()); // Run after the server load to setup Vault services properly.
|
||||
}
|
||||
|
||||
public static boolean handleEnable(@NotNull NightPlugin plugin) {
|
||||
if (plugin instanceof NightCore nightCore) {
|
||||
init(nightCore);
|
||||
}
|
||||
else {
|
||||
CHILDRENS.add(plugin);
|
||||
plugin.info("Powered by " + core.getName());
|
||||
}
|
||||
|
||||
return checkVersion(plugin);
|
||||
}
|
||||
|
||||
public static boolean checkVersion(@NotNull NightCorePlugin plugin) {
|
||||
Version current = Version.getCurrent();
|
||||
if (current != Version.UNKNOWN && current.isSupported()) return true;
|
||||
|
||||
plugin.warn("=".repeat(35));
|
||||
|
||||
if (current == Version.UNKNOWN) {
|
||||
plugin.warn("WARNING: This plugin is not supposed to run on this server version!");
|
||||
plugin.warn("If server version is newer than " + Version.values()[Version.values().length - 1] + ", then wait for an update please.");
|
||||
plugin.warn("Otherwise this plugin will not work properly or even load.");
|
||||
}
|
||||
else if (current.isDeprecated()) {
|
||||
plugin.warn("WARNING: You're running an outdated server version (" + current.getLocalized() + ")!");
|
||||
plugin.warn("This version will no longer be supported in future relases.");
|
||||
plugin.warn("Please upgrade your server to " + Lists.next(current, (Version::isSupported)).getLocalized() + ".");
|
||||
}
|
||||
else if (current.isDropped()) {
|
||||
plugin.error("ERROR: You're running an unsupported server version (" + current.getLocalized() + ")!");
|
||||
plugin.error("Please upgrade your server to " + Lists.next(current, (Version::isSupported)).getLocalized() + ".");
|
||||
}
|
||||
|
||||
plugin.warn("ABSOLUTELY NO DISCORD SUPPORT WILL BE PROVIDED");
|
||||
plugin.warn("=".repeat(35));
|
||||
|
||||
if (current.isDropped()) {
|
||||
plugin.getPluginManager().disablePlugin(plugin);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package su.nightexpress.nightcore;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.experimental.ImprovedCommands;
|
||||
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.CoreCommands;
|
||||
import su.nightexpress.nightcore.language.LangAssets;
|
||||
import su.nightexpress.nightcore.ui.UIUtils;
|
||||
import su.nightexpress.nightcore.util.TimeUtil;
|
||||
import su.nightexpress.nightcore.util.blocktracker.PlayerBlockTracker;
|
||||
import su.nightexpress.nightcore.util.text.tag.Tags;
|
||||
|
||||
public class NightCore extends NightPlugin implements ImprovedCommands {
|
||||
|
||||
private CoreManager coreManager;
|
||||
|
||||
@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() {
|
||||
Tags.loadColorsFromFile(this);
|
||||
LangAssets.load(this);
|
||||
UIUtils.load(this);
|
||||
this.loadCommands();
|
||||
this.info("Time zone set as " + TimeUtil.getTimeZone().getID());
|
||||
|
||||
this.coreManager = new CoreManager(this);
|
||||
this.coreManager.setup();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disable() {
|
||||
if (this.coreManager != null) this.coreManager.shutdown();
|
||||
|
||||
UIUtils.clear();
|
||||
LangAssets.shutdown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
super.onDisable();
|
||||
PlayerBlockTracker.shutdown();
|
||||
Engine.clear();
|
||||
}
|
||||
|
||||
private void loadCommands() {
|
||||
CoreCommands.load(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package su.nightexpress.nightcore;
|
||||
|
||||
import io.papermc.paper.plugin.bootstrap.BootstrapContext;
|
||||
import io.papermc.paper.plugin.bootstrap.PluginBootstrap;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class NightCoreBootstrap implements PluginBootstrap {
|
||||
|
||||
@Override
|
||||
public void bootstrap(@NotNull BootstrapContext context) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package su.nightexpress.nightcore;
|
||||
|
||||
import io.papermc.paper.plugin.loader.PluginClasspathBuilder;
|
||||
import io.papermc.paper.plugin.loader.PluginLoader;
|
||||
import io.papermc.paper.plugin.loader.library.impl.MavenLibraryResolver;
|
||||
import org.eclipse.aether.artifact.DefaultArtifact;
|
||||
import org.eclipse.aether.graph.Dependency;
|
||||
import org.eclipse.aether.repository.RemoteRepository;
|
||||
|
||||
public class NightCoreLoader implements PluginLoader {
|
||||
|
||||
@Override
|
||||
public void classloader(PluginClasspathBuilder classpathBuilder) {
|
||||
MavenLibraryResolver resolver = new MavenLibraryResolver();
|
||||
|
||||
resolver.addRepository(new RemoteRepository.Builder("maven", "default", "https://repo1.maven.org/maven2/").build());
|
||||
|
||||
resolver.addDependency(new Dependency(new DefaultArtifact("com.zaxxer:HikariCP:6.0.0"), null));
|
||||
resolver.addDependency(new Dependency(new DefaultArtifact("it.unimi.dsi:fastutil-core:8.5.13"), null));
|
||||
|
||||
classpathBuilder.addLibrary(resolver);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package su.nightexpress.nightcore;
|
||||
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.CommandManager;
|
||||
import su.nightexpress.nightcore.command.api.NightPluginCommand;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.config.PluginDetails;
|
||||
import su.nightexpress.nightcore.language.LangManager;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniTask;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface NightCorePlugin extends Plugin {
|
||||
|
||||
//boolean isEngine();
|
||||
|
||||
void enable();
|
||||
|
||||
void disable();
|
||||
|
||||
void reload();
|
||||
|
||||
@Deprecated
|
||||
NightPluginCommand getBaseCommand();
|
||||
|
||||
@Override
|
||||
@NotNull FileConfig getConfig();
|
||||
|
||||
@NotNull FileConfig getLang();
|
||||
|
||||
@NotNull PluginDetails getDetails();
|
||||
|
||||
void extractResources(@NotNull String jarPath);
|
||||
|
||||
void extractResources(@NotNull String jarParh, @NotNull String toPath);
|
||||
|
||||
@NotNull
|
||||
default String getNameLocalized() {
|
||||
return this.getDetails().getName();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default String getPrefix() {
|
||||
return this.getDetails().getPrefix();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default String[] getCommandAliases() {
|
||||
return this.getDetails().getCommandAliases();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default String getLanguage() {
|
||||
return this.getDetails().getLanguage();
|
||||
}
|
||||
|
||||
default void info(@NotNull String msg) {
|
||||
this.getLogger().info(msg);
|
||||
}
|
||||
|
||||
default void warn(@NotNull String msg) {
|
||||
this.getLogger().warning(msg);
|
||||
}
|
||||
|
||||
default void error(@NotNull String msg) {
|
||||
this.getLogger().severe(msg);
|
||||
}
|
||||
|
||||
default void debug(@NotNull String msg) {
|
||||
this.info("[DEBUG] " + msg);
|
||||
}
|
||||
|
||||
@NotNull LangManager getLangManager();
|
||||
|
||||
@NotNull CommandManager getCommandManager();
|
||||
|
||||
@NotNull
|
||||
default BukkitScheduler getScheduler() {
|
||||
return this.getServer().getScheduler();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default PluginManager getPluginManager() {
|
||||
return this.getServer().getPluginManager();
|
||||
}
|
||||
|
||||
default void runTask(@NotNull Consumer<BukkitTask> consumer) {
|
||||
this.getScheduler().runTask(this, consumer);
|
||||
}
|
||||
|
||||
default void runTaskAsync(@NotNull Consumer<BukkitTask> consumer) {
|
||||
this.getScheduler().runTaskAsynchronously(this, consumer);
|
||||
}
|
||||
|
||||
default void runTaskLater(@NotNull Consumer<BukkitTask> consumer, long delay) {
|
||||
this.getScheduler().runTaskLater(this, consumer, delay);
|
||||
}
|
||||
|
||||
default void runTaskLaterAsync(@NotNull Consumer<BukkitTask> consumer, long delay) {
|
||||
this.getScheduler().runTaskLaterAsynchronously(this, consumer, delay);
|
||||
}
|
||||
|
||||
default void runTaskTimer(@NotNull Consumer<BukkitTask> consumer, long delay, long interval) {
|
||||
this.getScheduler().runTaskTimer(this, consumer, delay, interval);
|
||||
}
|
||||
|
||||
default void runTaskTimerAsync(@NotNull Consumer<BukkitTask> consumer, long delay, long interval) {
|
||||
this.getScheduler().runTaskTimerAsynchronously(this, consumer, delay, interval);
|
||||
}
|
||||
|
||||
@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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package su.nightexpress.nightcore;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
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
|
||||
protected void loadManagers() {
|
||||
super.loadManagers();
|
||||
this.getUserManager().loadOnlineUsers();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void unloadManagers() {
|
||||
super.unloadManagers();
|
||||
this.getUserManager().shutdown();
|
||||
this.getData().shutdown();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public abstract AbstractUserDataHandler<? extends NightDataPlugin<U>, U> getData();
|
||||
|
||||
@NotNull
|
||||
public abstract AbstractUserManager<? extends NightDataPlugin<U>, U> getUserManager();
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package su.nightexpress.nightcore;
|
||||
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.CommandManager;
|
||||
import su.nightexpress.nightcore.command.api.NightPluginCommand;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.config.PluginDetails;
|
||||
import su.nightexpress.nightcore.language.LangManager;
|
||||
import su.nightexpress.nightcore.menu.impl.AbstractMenu;
|
||||
import su.nightexpress.nightcore.ui.menu.MenuRegistry;
|
||||
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 {
|
||||
|
||||
public static final String CONFIG_FILE = "config.yml";
|
||||
public static final String ENGINE_FILE = "engine.yml";
|
||||
|
||||
protected List<Runnable> postLoaders;
|
||||
|
||||
protected LangManager langManager;
|
||||
protected CommandManager commandManager;
|
||||
|
||||
protected FileConfig engineConf;
|
||||
protected FileConfig config;
|
||||
protected PluginDetails details;
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
if (!Engine.handleEnable(this)) {
|
||||
return;
|
||||
}
|
||||
|
||||
long loadTook = System.currentTimeMillis();
|
||||
this.loadManagers();
|
||||
this.info("Plugin loaded in " + (System.currentTimeMillis() - loadTook) + " ms!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
this.unloadManagers();
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
this.unloadManagers();
|
||||
this.loadManagers();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public final FileConfig getConfig() {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public FileConfig getEngineConfig() {
|
||||
return this.engineConf;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final FileConfig getLang() {
|
||||
return this.langManager.getConfig();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public PluginDetails getDetails() {
|
||||
if (this.details == null) throw new IllegalStateException("Plugin is not yet initialized!");
|
||||
|
||||
return this.details;
|
||||
//return this.details == null ? this.getDefaultDetails() : this.details;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected abstract PluginDetails getDefaultDetails();
|
||||
|
||||
public void registerPermissions(@NotNull Class<?> clazz) {
|
||||
Reflex.getFields(clazz, UniPermission.class).forEach(permission -> {
|
||||
if (this.getPluginManager().getPermission(permission.getName()) == null) {
|
||||
this.getPluginManager().addPermission(permission);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected void setupConfig() {
|
||||
this.engineConf = FileConfig.loadOrExtract(this, ENGINE_FILE);
|
||||
this.config = FileConfig.loadOrExtract(this, CONFIG_FILE);
|
||||
|
||||
// ---------- MIGRATION - START ----------
|
||||
if (this.config.contains("Plugin")) {
|
||||
PluginDetails details = PluginDetails.read(this, this.config, this.getDefaultDetails());
|
||||
details.write(this.engineConf, "");
|
||||
this.config.remove("Plugin");
|
||||
}
|
||||
// ---------- MIGRATION - END ----------
|
||||
|
||||
this.details = PluginDetails.read(this, this.engineConf, this.getDefaultDetails());
|
||||
|
||||
if (this.details.getConfigClass() != null) {
|
||||
this.config.initializeOptions(this.details.getConfigClass());
|
||||
}
|
||||
}
|
||||
|
||||
protected void setupLanguage() {
|
||||
this.langManager = new LangManager(this);
|
||||
this.langManager.setup();
|
||||
|
||||
if (this.details.getLangClass() != null) {
|
||||
this.langManager.loadEntries(this.details.getLangClass());
|
||||
}
|
||||
}
|
||||
|
||||
protected void setupPermissions() {
|
||||
Class<?> clazz = this.details.getPermissionsClass();
|
||||
if (clazz == null) return;
|
||||
|
||||
this.registerPermissions(clazz);
|
||||
}
|
||||
|
||||
protected void setupCommands() {
|
||||
this.commandManager = new CommandManager(this);
|
||||
this.commandManager.setup();
|
||||
}
|
||||
|
||||
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.
|
||||
this.setupCommands(); // Register plugin commands.
|
||||
|
||||
this.enable(); // Load the plugin.
|
||||
|
||||
this.postLoad(); // Load some stuff that needs to be injected after the rest managers.
|
||||
|
||||
this.config.saveChanges();
|
||||
this.getLang().saveChanges();
|
||||
this.engineConf.saveChanges();
|
||||
}
|
||||
|
||||
protected void unloadManagers() {
|
||||
this.getScheduler().cancelTasks(this); // Stop all plugin tasks.
|
||||
|
||||
this.disable();
|
||||
|
||||
AbstractMenu.clearAll(this); // Close all GUIs.
|
||||
MenuRegistry.closeAll();
|
||||
HandlerList.unregisterAll(this); // Unregister all plugin listeners.
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final LangManager getLangManager() {
|
||||
return this.langManager;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final CommandManager getCommandManager() {
|
||||
return this.commandManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void extractResources(@NotNull String jarPath) {
|
||||
this.extractResources(jarPath, this.getDataFolder() + jarPath);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void extractResources(@NotNull String jarPath, @NotNull String targetPath) {
|
||||
File destination = new File(targetPath);
|
||||
if (destination.exists()) return;
|
||||
|
||||
if (jarPath.startsWith("/")) {
|
||||
jarPath = jarPath.substring(1);
|
||||
}
|
||||
if (jarPath.endsWith("/")) {
|
||||
jarPath = jarPath.substring(0, jarPath.length() - 1);
|
||||
}
|
||||
|
||||
FileUtil.extractResources(this.getFile(), jarPath, destination);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package su.nightexpress.nightcore.command;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.util.NumberUtil;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
@Deprecated
|
||||
public class CommandFlag<T> {
|
||||
|
||||
public static final char PREFIX = '-';
|
||||
|
||||
private final String name;
|
||||
private final Function<String, T> parser;
|
||||
|
||||
public CommandFlag(@NotNull String name, @NotNull Function<String, T> parser) {
|
||||
this.name = name;
|
||||
this.parser = parser;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<World> worldFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, Bukkit::getWorld);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<String> stringFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, Function.identity());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<String> textFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, s -> s);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<Integer> intFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, str -> NumberUtil.getAnyInteger(str, 0));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<Double> doubleFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, str -> NumberUtil.getAnyDouble(str, 0D));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<Boolean> booleanFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, str -> true);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getNamePrefixed() {
|
||||
return PREFIX + this.getName();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Function<String, T> getParser() {
|
||||
return parser;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CommandFlag{" +
|
||||
"name='" + name + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package su.nightexpress.nightcore.command;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightPlugin;
|
||||
import su.nightexpress.nightcore.command.api.NightPluginCommand;
|
||||
import su.nightexpress.nightcore.command.base.HelpSubCommand;
|
||||
import su.nightexpress.nightcore.command.experimental.ImprovedCommands;
|
||||
import su.nightexpress.nightcore.command.experimental.RootCommand;
|
||||
import su.nightexpress.nightcore.command.experimental.ServerCommand;
|
||||
import su.nightexpress.nightcore.command.experimental.node.ChainedNode;
|
||||
import su.nightexpress.nightcore.command.impl.BaseCommand;
|
||||
import su.nightexpress.nightcore.manager.SimpleManager;
|
||||
import su.nightexpress.nightcore.util.CommandUtil;
|
||||
import su.nightexpress.nightcore.util.Lists;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class CommandManager extends SimpleManager<NightPlugin> {
|
||||
|
||||
private final Set<NightPluginCommand> commands;
|
||||
private final Set<ServerCommand> serverCommands;
|
||||
|
||||
private BaseCommand mainCommand;
|
||||
private RootCommand<NightPlugin, ChainedNode> rootCommand;
|
||||
|
||||
public CommandManager(@NotNull NightPlugin plugin) {
|
||||
super(plugin);
|
||||
this.commands = new HashSet<>();
|
||||
this.serverCommands = new HashSet<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
String[] aliases = this.plugin.getCommandAliases();
|
||||
if (aliases == null || aliases.length == 0) {
|
||||
this.plugin.error("Could not register plugin commands!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.plugin instanceof ImprovedCommands) {
|
||||
this.rootCommand = RootCommand.chained(this.plugin, aliases, builder -> builder
|
||||
// TODO Permission?
|
||||
.localized(this.plugin.getNameLocalized())
|
||||
);
|
||||
this.registerCommand(this.rootCommand);
|
||||
}
|
||||
else {
|
||||
// Create main plugin command and attach help sub-command as a default executor.
|
||||
this.mainCommand = new BaseCommand(this.plugin);
|
||||
this.mainCommand.addDefaultCommand(new HelpSubCommand(this.plugin));
|
||||
|
||||
// Register main command as a bukkit command.
|
||||
this.registerCommand(this.mainCommand);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onShutdown() {
|
||||
this.serverCommands.forEach(ServerCommand::unregister);
|
||||
this.serverCommands.clear();
|
||||
|
||||
for (NightPluginCommand command : new HashSet<>(this.getCommands())) {
|
||||
this.unregisterCommand(command);
|
||||
command.getChildrens().clear();
|
||||
}
|
||||
this.getCommands().clear();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public Set<NightPluginCommand> getCommands() {
|
||||
return this.commands;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<ServerCommand> getServerCommands() {
|
||||
return serverCommands;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public BaseCommand getMainCommand() {
|
||||
return this.mainCommand;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public RootCommand<NightPlugin, ChainedNode> getRootCommand() {
|
||||
return rootCommand;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public NightPluginCommand getCommand(@NotNull String alias) {
|
||||
return this.getCommands().stream()
|
||||
.filter(command -> Lists.contains(command.getAliases(), alias))
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public ServerCommand getServerCommand(@NotNull String alias) {
|
||||
return this.serverCommands.stream()
|
||||
.filter(command -> command.getNode().getName().equalsIgnoreCase(alias) || Lists.contains(command.getNode().getAliases(), alias))
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void registerCommand(@NotNull NightPluginCommand command) {
|
||||
if (this.commands.add(command)) {
|
||||
CommandUtil.register(this.plugin, command);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean unregisterCommand(@NotNull String alias) {
|
||||
NightPluginCommand command = this.getCommand(alias);
|
||||
if (command != null) {
|
||||
return this.unregisterCommand(command);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public boolean unregisterCommand(@NotNull NightPluginCommand command) {
|
||||
if (this.commands.remove(command)) {
|
||||
return CommandUtil.unregister(command.getAliases()[0]);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void registerCommand(@NotNull ServerCommand command) {
|
||||
if (!this.serverCommands.contains(command)) {
|
||||
if (command.register()) {
|
||||
this.serverCommands.add(command);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean unregisterServerCommand(@NotNull String alias) {
|
||||
ServerCommand command = this.getServerCommand(alias);
|
||||
if (command != null) {
|
||||
return this.unregisterCommand(command);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean unregisterCommand(@NotNull ServerCommand command) {
|
||||
return this.serverCommands.remove(command) && command.unregister();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package su.nightexpress.nightcore.command;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.util.NumberUtil;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Deprecated
|
||||
public class CommandResult {
|
||||
|
||||
private final String label;
|
||||
private final String[] args;
|
||||
private final Map<CommandFlag<?>, String> flags;
|
||||
|
||||
public CommandResult(@NotNull String label, String[] args, @NotNull Map<CommandFlag<?>, StringBuilder> flags) {
|
||||
this.label = label;
|
||||
this.flags = new HashMap<>();
|
||||
this.args = args;
|
||||
|
||||
flags.forEach((flag, content) -> this.flags.put(flag, content.toString()));
|
||||
}
|
||||
|
||||
public int length() {
|
||||
return this.args.length;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getArg(int index) {
|
||||
return this.getArgs()[index];
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getArg(int index, @NotNull String def) {
|
||||
if (index >= this.length()) return def;
|
||||
|
||||
return this.getArgs()[index];
|
||||
}
|
||||
|
||||
public int getInt(int index, int def) {
|
||||
return NumberUtil.getAnyInteger(this.getArg(index, ""), def);
|
||||
}
|
||||
|
||||
public double getDouble(int index, double def) {
|
||||
return NumberUtil.getAnyDouble(this.getArg(index, ""), def);
|
||||
}
|
||||
|
||||
public boolean hasFlag(@NotNull CommandFlag<?> flag) {
|
||||
return this.getFlags().containsKey(flag);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public <T> T getFlag(@NotNull CommandFlag<T> flag) {
|
||||
String value = this.getFlags().get(flag);
|
||||
if (value == null) return null;
|
||||
|
||||
return flag.getParser().apply(value);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> T getFlag(@NotNull CommandFlag<T> flag, @NotNull T def) {
|
||||
T value = this.getFlag(flag);
|
||||
return value == null ? def : value;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
|
||||
public String[] getArgs() {
|
||||
return args;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<CommandFlag<?>, String> getFlags() {
|
||||
return flags;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package su.nightexpress.nightcore.command.api;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.command.CommandFlag;
|
||||
import su.nightexpress.nightcore.language.entry.LangString;
|
||||
import su.nightexpress.nightcore.util.placeholder.Placeholder;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
@Deprecated
|
||||
public interface NightCommand extends Placeholder {
|
||||
|
||||
@NotNull List<String> getTab(@NotNull Player player, int arg, @NotNull String[] args);
|
||||
|
||||
void execute(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args);
|
||||
|
||||
void addChildren(@NotNull NightCommand children);
|
||||
|
||||
void removeChildren(@NotNull String alias);
|
||||
|
||||
default boolean hasPermission(@NotNull CommandSender sender) {
|
||||
return this.getPermission() == null || sender.hasPermission(this.getPermission());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default String getLabelWithParents() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
NightCommand parent = this.getParent();
|
||||
while (parent != null) {
|
||||
builder.insert(0, parent.getAliases()[0] + " ");
|
||||
parent = parent.getParent();
|
||||
}
|
||||
builder.append(this.getAliases()[0]);
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
@Nullable NightCommand getParent();
|
||||
|
||||
void setParent(@Nullable NightCommand parent);
|
||||
|
||||
@Nullable NightCommand getChildren(@NotNull String alias);
|
||||
|
||||
@NotNull Collection<NightCommand> getChildrens();
|
||||
|
||||
@NotNull String[] getAliases();
|
||||
|
||||
@Nullable String getPermission();
|
||||
|
||||
default void setPermission(@Nullable Permission permission) {
|
||||
this.setPermission(permission == null ? null : permission.getName());
|
||||
}
|
||||
|
||||
void setPermission(@Nullable String permission);
|
||||
|
||||
@Nullable CommandFlag<?> getFlag(@NotNull String name);
|
||||
|
||||
@NotNull Collection<CommandFlag<?>> getFlags();
|
||||
|
||||
default void addFlag(@NotNull CommandFlag<?>... flags) {
|
||||
for (CommandFlag<?> flag : flags) this.addFlag(flag);
|
||||
}
|
||||
|
||||
void addFlag(@NotNull CommandFlag<?> flag);
|
||||
|
||||
@NotNull String getUsage();
|
||||
|
||||
default void setUsage(@NotNull LangString string) {
|
||||
this.setUsage(string.getString());
|
||||
}
|
||||
|
||||
void setUsage(@NotNull String usage);
|
||||
|
||||
@NotNull String getDescription();
|
||||
|
||||
default void setDescription(@NotNull LangString string) {
|
||||
this.setDescription(string.getString());
|
||||
}
|
||||
|
||||
void setDescription(@NotNull String description);
|
||||
|
||||
boolean isPlayerOnly();
|
||||
|
||||
void setPlayerOnly(boolean playerOnly);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package su.nightexpress.nightcore.command.api;
|
||||
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.TabExecutor;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@Deprecated
|
||||
public interface NightPluginCommand extends NightCommand, TabExecutor {
|
||||
|
||||
@Nullable NightCommand getDefaultCommand();
|
||||
|
||||
void addDefaultCommand(@NotNull NightCommand command);
|
||||
|
||||
Command getBackend();
|
||||
|
||||
void setBackend(@NotNull Command backend);
|
||||
|
||||
//@NotNull NightCommand findChildren(@NotNull String[] args);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package su.nightexpress.nightcore.command.base;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.impl.AbstractCommand;
|
||||
import su.nightexpress.nightcore.command.CommandResult;
|
||||
import su.nightexpress.nightcore.command.api.NightCommand;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.util.Placeholders;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Deprecated
|
||||
public class HelpSubCommand extends AbstractCommand<NightCorePlugin> {
|
||||
|
||||
public HelpSubCommand(@NotNull NightCorePlugin plugin) {
|
||||
super(plugin, new String[]{"help"});
|
||||
this.setDescription(CoreLang.COMMAND_HELP_DESC);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) {
|
||||
NightCommand parent = this.getParent();
|
||||
if (parent == null) return;
|
||||
|
||||
if (!parent.hasPermission(sender)) {
|
||||
this.errorPermission(sender);
|
||||
return;
|
||||
}
|
||||
|
||||
CoreLang.COMMAND_HELP_LIST.getMessage()
|
||||
.replace(Placeholders.GENERIC_NAME, this.plugin.getNameLocalized())
|
||||
.replace(Placeholders.GENERIC_ENTRY, list -> {
|
||||
Set<NightCommand> commands = new HashSet<>(parent.getChildrens());
|
||||
|
||||
commands.stream().sorted(Comparator.comparing(command -> command.getAliases()[0])).forEach(children -> {
|
||||
if (!children.hasPermission(sender)) return;
|
||||
|
||||
list.add(children.replacePlaceholders().apply(CoreLang.COMMAND_HELP_ENTRY.getString()));
|
||||
});
|
||||
}).send(sender);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package su.nightexpress.nightcore.command.base;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.CommandResult;
|
||||
import su.nightexpress.nightcore.command.impl.AbstractCommand;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
|
||||
@Deprecated
|
||||
public class ReloadSubCommand extends AbstractCommand<NightCorePlugin> {
|
||||
|
||||
public ReloadSubCommand(@NotNull NightCorePlugin plugin, @NotNull Permission permission) {
|
||||
this(plugin, permission.getName());
|
||||
}
|
||||
|
||||
public ReloadSubCommand(@NotNull NightCorePlugin plugin, @NotNull String permission) {
|
||||
super(plugin, new String[]{"reload"}, permission);
|
||||
this.setDescription(CoreLang.COMMAND_RELOAD_DESC);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) {
|
||||
this.plugin.reload();
|
||||
CoreLang.COMMAND_RELOAD_DONE.getMessage(plugin).send(sender);
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package su.nightexpress.nightcore.command.experimental;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.language.entry.LangText;
|
||||
import su.nightexpress.nightcore.language.message.LangMessage;
|
||||
import su.nightexpress.nightcore.util.placeholder.Replacer;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class CommandContext {
|
||||
|
||||
private final NightCorePlugin plugin;
|
||||
private final CommandSender sender;
|
||||
private final Player executor;
|
||||
private final String label;
|
||||
private final String[] args;
|
||||
|
||||
private int argumentIndex;
|
||||
|
||||
public CommandContext(@NotNull NightCorePlugin plugin, @NotNull CommandSender sender, @NotNull String label, String[] args) {
|
||||
this.plugin = plugin;
|
||||
this.sender = sender;
|
||||
this.executor = sender instanceof Player player ? player : null;
|
||||
this.label = label;
|
||||
this.args = args;
|
||||
this.argumentIndex = 0;
|
||||
}
|
||||
|
||||
public void send(@NotNull String string) {
|
||||
this.sender.sendMessage(string);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public boolean sendSuccess(@NotNull String string) {
|
||||
this.send(string);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public boolean sendFailure(@NotNull String string) {
|
||||
this.send(string);
|
||||
return false;
|
||||
}
|
||||
|
||||
public void send(@NotNull LangText text) {
|
||||
this.send(text, null);
|
||||
}
|
||||
|
||||
public void send(@NotNull LangText text, @Nullable Consumer<Replacer> consumer) {
|
||||
this.send(text.getMessage(), consumer);
|
||||
}
|
||||
|
||||
public void send(@NotNull LangMessage message) {
|
||||
this.send(message, null);
|
||||
}
|
||||
|
||||
public void send(@NotNull LangMessage message, @Nullable Consumer<Replacer> consumer) {
|
||||
message.send(this.sender, consumer);
|
||||
}
|
||||
|
||||
// public void send(@NotNull LangMessage message) {
|
||||
// message.send(this.sender);
|
||||
// }
|
||||
|
||||
@Deprecated
|
||||
public boolean sendSuccess(@NotNull LangMessage message) {
|
||||
this.send(message);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public boolean sendFailure(@NotNull LangMessage message) {
|
||||
this.send(message);
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean checkPermission(@NotNull Permission permission) {
|
||||
return this.sender.hasPermission(permission);
|
||||
}
|
||||
|
||||
public boolean checkPermission(@NotNull String permission) {
|
||||
return this.sender.hasPermission(permission);
|
||||
}
|
||||
|
||||
public boolean isPlayer() {
|
||||
return this.executor != null;
|
||||
}
|
||||
|
||||
public int getArgumentIndex() {
|
||||
return this.argumentIndex;
|
||||
}
|
||||
|
||||
public void setArgumentIndex(int argumentIndex) {
|
||||
this.argumentIndex = argumentIndex;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public CommandSender getSender() {
|
||||
return this.sender;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Player getExecutor() {
|
||||
return this.executor;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Player getPlayerOrThrow() {
|
||||
if (this.isPlayer()) return this.executor;
|
||||
|
||||
throw new IllegalStateException("CommandContext is not bound to a player!");
|
||||
}
|
||||
|
||||
public int length() {
|
||||
return this.args.length;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getLabel() {
|
||||
return this.label;
|
||||
}
|
||||
|
||||
public String[] getArgs() {
|
||||
return this.args;
|
||||
}
|
||||
|
||||
public void errorPermission() {
|
||||
this.send(CoreLang.ERROR_NO_PERMISSION.getMessage(plugin));
|
||||
}
|
||||
|
||||
public void errorBadPlayer() {
|
||||
this.send(CoreLang.ERROR_INVALID_PLAYER.getMessage(plugin));
|
||||
}
|
||||
|
||||
public void errorPlayerOnly() {
|
||||
this.send(CoreLang.ERROR_COMMAND_PLAYER_ONLY.getMessage(plugin));
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package su.nightexpress.nightcore.command.experimental;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.experimental.node.ChainedNode;
|
||||
|
||||
public interface ImprovedCommands extends NightCorePlugin {
|
||||
|
||||
@NotNull
|
||||
default ServerCommand getRootCommand() {
|
||||
return this.getCommandManager().getRootCommand();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default ChainedNode getRootNode() {
|
||||
return this.getCommandManager().getRootCommand().getNode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package su.nightexpress.nightcore.command.experimental;
|
||||
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.experimental.builder.ChainedNodeBuilder;
|
||||
import su.nightexpress.nightcore.command.experimental.builder.DirectNodeBuilder;
|
||||
import su.nightexpress.nightcore.command.experimental.builder.NodeBuilder;
|
||||
import su.nightexpress.nightcore.command.experimental.node.ChainedNode;
|
||||
import su.nightexpress.nightcore.command.experimental.node.CommandNode;
|
||||
import su.nightexpress.nightcore.command.experimental.node.DirectNode;
|
||||
import su.nightexpress.nightcore.command.impl.WrappedCommand;
|
||||
import su.nightexpress.nightcore.util.CommandUtil;
|
||||
import su.nightexpress.nightcore.util.Lists;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class RootCommand<P extends NightCorePlugin, S extends CommandNode> implements ServerCommand {
|
||||
|
||||
private final P plugin;
|
||||
private final S node;
|
||||
|
||||
private WrappedCommand backend;
|
||||
|
||||
public RootCommand(@NotNull P plugin, @NotNull S node) {
|
||||
this.plugin = plugin;
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T extends NightCorePlugin> RootCommand<T, DirectNode> direct(@NotNull T plugin, @NotNull String name, @NotNull Consumer<DirectNodeBuilder> consumer) {
|
||||
return direct(plugin, new String[] {name}, consumer);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T extends NightCorePlugin> RootCommand<T, ChainedNode> chained(@NotNull T plugin, @NotNull String name, @NotNull Consumer<ChainedNodeBuilder> consumer) {
|
||||
return chained(plugin, new String[] {name}, consumer);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T extends NightCorePlugin> RootCommand<T, DirectNode> direct(@NotNull T plugin, @NotNull String[] aliases, @NotNull Consumer<DirectNodeBuilder> consumer) {
|
||||
DirectNodeBuilder builder = DirectNode.builder(plugin, aliases);
|
||||
consumer.accept(builder);
|
||||
return build(plugin, builder);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T extends NightCorePlugin> RootCommand<T, ChainedNode> chained(@NotNull T plugin, @NotNull String[] aliases, @NotNull Consumer<ChainedNodeBuilder> consumer) {
|
||||
ChainedNodeBuilder builder = ChainedNode.builder(plugin, aliases);
|
||||
consumer.accept(builder);
|
||||
return build(plugin, builder);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T extends NightCorePlugin, S extends CommandNode, B extends NodeBuilder<S, B>> RootCommand<T, S> build(@NotNull T plugin, @NotNull B builder) {
|
||||
return new RootCommand<>(plugin, builder.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean register() {
|
||||
this.backend = new WrappedCommand(this.plugin, this, this,
|
||||
this.node.getName(),
|
||||
this.node.getAliases(),
|
||||
this.node.getDescription(),
|
||||
this.node.getUsage(),
|
||||
this.node.getPermission()
|
||||
);
|
||||
return CommandUtil.register(this.plugin, this.backend);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean unregister() {
|
||||
if (CommandUtil.unregister(this.getNode().getName())) {
|
||||
this.backend = null;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
|
||||
if (args.length == 0) return Collections.emptyList();
|
||||
|
||||
TabContext context = new TabContext(sender, label, args, 0);
|
||||
List<String> samples = this.node.getTab(context);
|
||||
|
||||
return Lists.getSequentialMatches(samples, context.getInput());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
||||
CommandContext commandContext = new CommandContext(this.plugin, sender, label, args);
|
||||
|
||||
return this.node.run(commandContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public S getNode() {
|
||||
return node;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public WrappedCommand getBackend() {
|
||||
return backend;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package su.nightexpress.nightcore.command.experimental;
|
||||
|
||||
import org.bukkit.command.TabExecutor;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.experimental.node.CommandNode;
|
||||
import su.nightexpress.nightcore.command.impl.WrappedCommand;
|
||||
|
||||
public interface ServerCommand extends TabExecutor {
|
||||
|
||||
boolean register();
|
||||
|
||||
boolean unregister();
|
||||
|
||||
@NotNull CommandNode getNode();
|
||||
|
||||
@NotNull WrappedCommand getBackend();
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package su.nightexpress.nightcore.command.experimental;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.CommandArgument;
|
||||
import su.nightexpress.nightcore.command.experimental.flag.CommandFlag;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class TabContext {
|
||||
|
||||
private final CommandSender sender;
|
||||
private final Player player;
|
||||
private final String label;
|
||||
private final String[] args;
|
||||
|
||||
private final Map<String, String> argumentCache;
|
||||
private final Map<String, String> flagCache;
|
||||
|
||||
private int lastCommandIndex;
|
||||
|
||||
public TabContext(@NotNull CommandSender sender, @NotNull String label, String[] args, int lastCommandIndex) {
|
||||
this.sender = sender;
|
||||
this.player = sender instanceof Player user ? user : null;
|
||||
this.label = label;
|
||||
this.args = args;
|
||||
this.lastCommandIndex = lastCommandIndex;
|
||||
|
||||
this.argumentCache = new HashMap<>();
|
||||
this.flagCache = new HashMap<>();
|
||||
}
|
||||
|
||||
public int length() {
|
||||
return this.args.length;
|
||||
}
|
||||
|
||||
public boolean hasCachedArgument(@NotNull CommandArgument<?> argument) {
|
||||
return this.argumentCache.containsKey(argument.getName());
|
||||
}
|
||||
|
||||
public boolean hasCachedFlag(@NotNull CommandFlag flag) {
|
||||
return this.flagCache.containsKey(flag.getName());
|
||||
}
|
||||
|
||||
public void cacheArgument(@NotNull CommandArgument<?> argument, @NotNull String value) {
|
||||
this.argumentCache.put(argument.getName(), value);
|
||||
}
|
||||
|
||||
public void cacheFlag(@NotNull CommandFlag flag, @NotNull String value) {
|
||||
this.flagCache.put(flag.getName(), value);
|
||||
}
|
||||
|
||||
public void appendArgumentCache(@NotNull CommandArgument<?> argument, @NotNull String value) {
|
||||
String cached = this.getCachedArgument(argument.getName());
|
||||
cached = cached == null ? value : cached + " " + value;
|
||||
this.cacheArgument(argument, cached);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getCachedArgument(@NotNull String name) {
|
||||
return this.argumentCache.get(name.toLowerCase());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getCachedFlag(@NotNull String name) {
|
||||
return this.flagCache.get(name.toLowerCase());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getArg(int index) {
|
||||
return this.args[index];
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public CommandSender getSender() {
|
||||
return this.sender;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Player getPlayer() {
|
||||
return this.player;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Player getPlayerOrThrow() {
|
||||
if (this.player != null) return this.player;
|
||||
|
||||
throw new IllegalStateException("TabContext is not bound to a player!");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getLabel() {
|
||||
return this.label;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String[] getArgs() {
|
||||
return this.args;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public int getIndex() {
|
||||
return this.getLastCommandIndex();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void setIndex(int index) {
|
||||
this.setLastCommandIndex(index);
|
||||
}
|
||||
|
||||
public int getLastCommandIndex() {
|
||||
return this.lastCommandIndex;
|
||||
}
|
||||
|
||||
public void setLastCommandIndex(int index) {
|
||||
this.lastCommandIndex = index;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public String getAtIndex() {
|
||||
return this.args[this.lastCommandIndex];
|
||||
}
|
||||
|
||||
public String getInput() {
|
||||
return this.args[this.args.length - 1];
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<String, String> getArgumentCache() {
|
||||
return this.argumentCache;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<String, String> getFlagCache() {
|
||||
return this.flagCache;
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package su.nightexpress.nightcore.command.experimental.argument;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.command.experimental.CommandContext;
|
||||
|
||||
public interface ArgumentParser<T> {
|
||||
|
||||
@Nullable T parse(@NotNull String string, @NotNull CommandContext context);
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
package su.nightexpress.nightcore.command.experimental.argument;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.BlockType;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemType;
|
||||
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.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<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);
|
||||
@Deprecated 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) -> {
|
||||
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<PotionEffectType> POTION_EFFECT = BukkitThing::getPotionEffect;
|
||||
//public static final ArgumentParser<Attribute> ATTRIBUTE = BukkitThing::getAttribute;
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<String> string(@NotNull String name) {
|
||||
return CommandArgument.builder(name, STRING).localized(CoreLang.COMMAND_ARGUMENT_NAME_GENERIC);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<Boolean> bool(@NotNull String name) {
|
||||
return CommandArgument.builder(name, BOOLEAN).localized(CoreLang.COMMAND_ARGUMENT_NAME_GENERIC);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<Integer> integer(@NotNull String name) {
|
||||
return numeric(name, INTEGER);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<Integer> integerAbs(@NotNull String name) {
|
||||
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 numeric(name, DOUBLE);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<Double> decimalAbs(@NotNull String name) {
|
||||
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);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<Player> player(@NotNull String name) {
|
||||
return CommandArgument.builder(name, PLAYER)
|
||||
.localized(CoreLang.COMMAND_ARGUMENT_NAME_PLAYER)
|
||||
.customFailure(CoreLang.ERROR_COMMAND_INVALID_PLAYER_ARGUMENT)
|
||||
.withSamples(tabContext -> Players.playerNames(tabContext.getPlayer()));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<String> playerName(@NotNull String name) {
|
||||
return CommandArgument.builder(name, STRING)
|
||||
.localized(CoreLang.COMMAND_ARGUMENT_NAME_PLAYER)
|
||||
.withSamples(tabContext -> Players.playerNames(tabContext.getPlayer()));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<World> world(@NotNull String name) {
|
||||
return CommandArgument.builder(name, WORLD)
|
||||
.localized(CoreLang.COMMAND_ARGUMENT_NAME_WORLD)
|
||||
.customFailure(CoreLang.ERROR_COMMAND_INVALID_WORLD_ARGUMENT)
|
||||
.withSamples(tabContext -> BukkitThing.worldNames());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<Material> material(@NotNull String name) {
|
||||
return CommandArgument.builder(name, MATERIAL)
|
||||
.localized(CoreLang.COMMAND_ARGUMENT_NAME_MATERIAL)
|
||||
.customFailure(CoreLang.ERROR_COMMAND_INVALID_MATERIAL_ARGUMENT);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<Material> itemMaterial(@NotNull String name) {
|
||||
return CommandArgument.builder(name, ITEM_MATERIAL)
|
||||
.localized(CoreLang.COMMAND_ARGUMENT_NAME_ITEM_MATERIAL)
|
||||
.customFailure(CoreLang.ERROR_COMMAND_INVALID_MATERIAL_ARGUMENT);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<Material> blockMaterial(@NotNull String name) {
|
||||
return CommandArgument.builder(name, BLOCK_MATERIAL)
|
||||
.localized(CoreLang.COMMAND_ARGUMENT_NAME_BLOCK_MATERIAL)
|
||||
.customFailure(CoreLang.ERROR_COMMAND_INVALID_MATERIAL_ARGUMENT);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<ItemType> itemType(@NotNull String name) {
|
||||
return CommandArgument.builder(name, (string, context) -> BukkitThing.getItemType(string))
|
||||
.localized(CoreLang.COMMAND_ARGUMENT_NAME_ITEM_MATERIAL)
|
||||
.customFailure(CoreLang.ERROR_COMMAND_INVALID_MATERIAL_ARGUMENT);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<BlockType> blockType(@NotNull String name) {
|
||||
return CommandArgument.builder(name, (string, context) -> BukkitThing.getBlockType(string))
|
||||
.localized(CoreLang.COMMAND_ARGUMENT_NAME_BLOCK_MATERIAL)
|
||||
.customFailure(CoreLang.ERROR_COMMAND_INVALID_MATERIAL_ARGUMENT);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<Enchantment> enchantment(@NotNull String name) {
|
||||
return CommandArgument.builder(name, ENCHANTMENT)
|
||||
.localized(CoreLang.COMMAND_ARGUMENT_NAME_ENCHANTMENT)
|
||||
.customFailure(CoreLang.ERROR_COMMAND_INVALID_ENCHANTMENT_ARGUMENT);
|
||||
}
|
||||
|
||||
/*@NotNull
|
||||
public static ArgumentBuilder<PotionEffectType> potionEffect(@NotNull String name) {
|
||||
return CommandArgument.builder(name, POTION_EFFECT)
|
||||
.localized(CoreLang.COMMAND_ARGUMENT_NAME_POTION_EFFECT)
|
||||
.customFailure(CoreLang.ERROR_INVALID_POTION_EFFECT);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ArgumentBuilder<Attribute> attribute(@NotNull String name) {
|
||||
return CommandArgument.builder(name, ATTRIBUTE)
|
||||
.localized(CoreLang.COMMAND_ARGUMENT_NAME_ATTRIBUTE)
|
||||
.customFailure(CoreLang.ERROR_INVALID_ATTRIBUTE);
|
||||
}*/
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package su.nightexpress.nightcore.command.experimental.argument;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.experimental.CommandContext;
|
||||
import su.nightexpress.nightcore.command.experimental.TabContext;
|
||||
import su.nightexpress.nightcore.command.experimental.builder.ArgumentBuilder;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.language.message.LangMessage;
|
||||
import su.nightexpress.nightcore.util.Lists;
|
||||
import su.nightexpress.nightcore.util.Placeholders;
|
||||
import su.nightexpress.nightcore.util.text.NightMessage;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class CommandArgument<T> {
|
||||
|
||||
private final String name;
|
||||
private final ArgumentParser<T> parser;
|
||||
private final boolean required;
|
||||
private final boolean complex;
|
||||
private final String localized;
|
||||
private final String permission;
|
||||
private final Function<TabContext, List<String>> samples;
|
||||
private final LangMessage failureMessage;
|
||||
|
||||
public CommandArgument(@NotNull String name,
|
||||
@NotNull ArgumentParser<T> parser,
|
||||
boolean required,
|
||||
boolean complex,
|
||||
@Nullable String localized,
|
||||
@Nullable String permission,
|
||||
@Nullable LangMessage failureMessage,
|
||||
@Nullable Function<TabContext, List<String>> samples) {
|
||||
this.name = name.toLowerCase();
|
||||
this.parser = parser;
|
||||
this.required = required;
|
||||
this.complex = complex;
|
||||
this.samples = samples;
|
||||
this.localized = this.getLocalized(localized);
|
||||
this.permission = permission;
|
||||
this.failureMessage = failureMessage;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public static <T> ArgumentBuilder<T> builder(@NotNull String name, @NotNull Function<String, T> parser) {
|
||||
return builder(name, (string, context) -> parser.apply(string));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> ArgumentBuilder<T> builder(@NotNull String name, @NotNull ArgumentParser<T> parser) {
|
||||
return new ArgumentBuilder<>(name, parser);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public ParsedArgument<T> parse(@NotNull String str, @NotNull CommandContext context) {
|
||||
T result = this.parser.parse(str, context);
|
||||
return result == null ? null : new ParsedArgument<>(result);
|
||||
}
|
||||
|
||||
public boolean hasPermission(@NotNull CommandSender sender) {
|
||||
return this.permission == null || sender.hasPermission(this.permission);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getSamples(@NotNull TabContext context) {
|
||||
return this.samples == null ? Lists.newList(NightMessage.stripAll(this.getLocalized())) : this.samples.apply(context);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private String getLocalized(@Nullable String localized) {
|
||||
if (localized == null) {
|
||||
localized = this.name;
|
||||
}
|
||||
|
||||
String format = (this.isRequired() ? CoreLang.COMMAND_ARGUMENT_FORMAT_REQUIRED : CoreLang.COMMAND_ARGUMENT_FORMAT_OPTIONAL).getString();
|
||||
|
||||
return format.replace(Placeholders.GENERIC_NAME, localized);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public LangMessage getFailureMessage() {
|
||||
return this.failureMessage == null ? CoreLang.ERROR_COMMAND_PARSE_ARGUMENT.getMessage() : this.failureMessage;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LangMessage getFailureMessage(@NotNull NightCorePlugin plugin) {
|
||||
return this.failureMessage == null ? CoreLang.ERROR_COMMAND_PARSE_ARGUMENT.getMessage(plugin) : this.failureMessage.setPrefix(plugin);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentParser<T> getParser() {
|
||||
return this.parser;
|
||||
}
|
||||
|
||||
public boolean isRequired() {
|
||||
return this.required;
|
||||
}
|
||||
|
||||
public boolean isComplex() {
|
||||
return this.complex;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getLocalized() {
|
||||
return this.localized == null ? this.name : this.localized;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getPermission() {
|
||||
return this.permission;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Function<TabContext, List<String>> getSamples() {
|
||||
return this.samples;
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package su.nightexpress.nightcore.command.experimental.argument;
|
||||
|
||||
public class ParsedArgument<T> {
|
||||
|
||||
private final T result;
|
||||
|
||||
public ParsedArgument(T result) {
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
public T getResult() {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
package su.nightexpress.nightcore.command.experimental.argument;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.experimental.flag.CommandFlag;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ParsedArguments {
|
||||
|
||||
private final Map<String, ParsedArgument<?>> argumentMap;
|
||||
private final Map<String, ParsedArgument<?>> flags;
|
||||
|
||||
public ParsedArguments() {
|
||||
this.argumentMap = new HashMap<>();
|
||||
this.flags = new HashMap<>();
|
||||
}
|
||||
|
||||
public void add(@NotNull CommandArgument<?> argument, @NotNull ParsedArgument<?> parsedArgument) {
|
||||
this.argumentMap.put(argument.getName(), parsedArgument);
|
||||
}
|
||||
|
||||
public void addFlag(@NotNull CommandFlag flag, @NotNull ParsedArgument<?> content) {
|
||||
this.flags.put(flag.getName(), content);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<String, ParsedArgument<?>> getArgumentMap() {
|
||||
return argumentMap;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<String, ParsedArgument<?>> getFlags() {
|
||||
return flags;
|
||||
}
|
||||
|
||||
public int getIntArgument(@NotNull String name, int defaultValue) {
|
||||
return this.getArgument(name, Integer.class, defaultValue);
|
||||
}
|
||||
|
||||
public int getIntArgument(@NotNull String name) {
|
||||
return this.getArgument(name, Integer.class);
|
||||
}
|
||||
|
||||
public double getDoubleArgument(@NotNull String name, double defaultValue) {
|
||||
return this.getArgument(name, Double.class, defaultValue);
|
||||
}
|
||||
|
||||
public double getDoubleArgument(@NotNull String name) {
|
||||
return this.getArgument(name, Double.class);
|
||||
}
|
||||
|
||||
public boolean getBooleanArgument(@NotNull String name, boolean defaultValue) {
|
||||
return this.getArgument(name, Boolean.class, defaultValue);
|
||||
}
|
||||
|
||||
public boolean getBooleanArgument(@NotNull String name) {
|
||||
return this.getArgument(name, Boolean.class);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getStringArgument(@NotNull String name, @NotNull String defaultValue) {
|
||||
return this.getArgument(name, String.class, defaultValue);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getStringArgument(@NotNull String name) {
|
||||
return this.getArgument(name, String.class);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Material getMaterialArgument(@NotNull String name, @NotNull Material defaultValue) {
|
||||
return this.getArgument(name, Material.class, defaultValue);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Material getMaterialArgument(@NotNull String name) {
|
||||
return this.getArgument(name, Material.class);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public World getWorldArgument(@NotNull String name, @NotNull World defaultValue) {
|
||||
return this.getArgument(name, World.class, defaultValue);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public World getWorldArgument(@NotNull String name) {
|
||||
return this.getArgument(name, World.class);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Enchantment getEnchantmentArgument(@NotNull String name, @NotNull Enchantment defaultValue) {
|
||||
return this.getArgument(name, Enchantment.class, defaultValue);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Enchantment getEnchantmentArgument(@NotNull String name) {
|
||||
return this.getArgument(name, Enchantment.class);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Player getPlayerArgument(@NotNull String name) {
|
||||
return this.getArgument(name, Player.class);
|
||||
}
|
||||
|
||||
public boolean hasArgument(@NotNull String name) {
|
||||
return this.argumentMap.containsKey(name);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> T getArgument(@NotNull String name, @NotNull Class<T> clazz, @NotNull T defaultValue) {
|
||||
if (!this.hasArgument(name)) return defaultValue;
|
||||
|
||||
return this.getArgument(name, clazz);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> T getArgument(@NotNull String name, @NotNull Class<T> clazz) {
|
||||
ParsedArgument<?> argument = this.argumentMap.get(name);
|
||||
if (argument == null) {
|
||||
throw new IllegalArgumentException("No such argument '" + name + "' exists on this command");
|
||||
}
|
||||
|
||||
Object result = argument.getResult();
|
||||
if (clazz.isAssignableFrom(result.getClass())) {
|
||||
return clazz.cast(result);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Argument '" + name + "' is defined as " + result.getClass().getSimpleName() + ", not " + clazz);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasFlag(@NotNull CommandFlag flag) {
|
||||
return this.hasFlag(flag.getName());
|
||||
}
|
||||
|
||||
public boolean hasFlag(@NotNull String name) {
|
||||
return this.flags.containsKey(name);
|
||||
}
|
||||
|
||||
public int getIntFlag(@NotNull String name, int defaultValue) {
|
||||
return this.getFlag(name, Integer.class, defaultValue);
|
||||
}
|
||||
|
||||
public double getDoubleFlag(@NotNull String name, double defaultValue) {
|
||||
return this.getFlag(name, Double.class, defaultValue);
|
||||
}
|
||||
|
||||
public boolean getBooleanFlag(@NotNull String name, boolean defaultValue) {
|
||||
return this.getFlag(name, Boolean.class, defaultValue);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getStringFlag(@NotNull String name, @NotNull String defaultValue) {
|
||||
return this.getFlag(name, String.class, defaultValue);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> T getFlag(@NotNull String name, @NotNull Class<T> clazz, @NotNull T defaultValue) {
|
||||
if (!this.hasFlag(name)) return defaultValue;
|
||||
|
||||
return this.getFlag(name, clazz);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> T getFlag(@NotNull String name, @NotNull Class<T> clazz) {
|
||||
ParsedArgument<?> parsed = this.flags.get(name);
|
||||
if (parsed == null) {
|
||||
throw new IllegalArgumentException("No such flag '" + name + "' exists on this command");
|
||||
}
|
||||
|
||||
Object result = parsed.getResult();
|
||||
if (clazz.isAssignableFrom(result.getClass())) {
|
||||
return clazz.cast(result);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Flag '" + name + "' is defined as " + result.getClass().getSimpleName() + ", not " + clazz);
|
||||
}
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package su.nightexpress.nightcore.command.experimental.builder;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.command.experimental.TabContext;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.ArgumentParser;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.CommandArgument;
|
||||
import su.nightexpress.nightcore.language.entry.LangString;
|
||||
import su.nightexpress.nightcore.language.entry.LangText;
|
||||
import su.nightexpress.nightcore.language.message.LangMessage;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniPermission;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ArgumentBuilder<T> {
|
||||
|
||||
protected final String name;
|
||||
protected final ArgumentParser<T> parser;
|
||||
|
||||
protected boolean required;
|
||||
protected boolean complex;
|
||||
protected String localized;
|
||||
protected String permission;
|
||||
protected Function<TabContext, List<String>> samples;
|
||||
protected LangMessage failureMessage;
|
||||
|
||||
@Deprecated
|
||||
public ArgumentBuilder(@NotNull String name, @NotNull Function<String, T> parser) {
|
||||
this(name, (string, context) -> parser.apply(string));
|
||||
}
|
||||
|
||||
public ArgumentBuilder(@NotNull String name, @NotNull ArgumentParser<T> parser) {
|
||||
this.name = name;
|
||||
this.parser = parser;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentBuilder<T> required() {
|
||||
return this.required(true);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentBuilder<T> required(boolean required) {
|
||||
this.required = required;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentBuilder<T> complex() {
|
||||
this.complex = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentBuilder<T> localized(@NotNull LangString localized) {
|
||||
return this.localized(localized.getString());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentBuilder<T> localized(@Nullable String localized) {
|
||||
this.localized = localized;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentBuilder<T> permission(@NotNull UniPermission permission) {
|
||||
return this.permission(permission.getName());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentBuilder<T> permission(@Nullable String permission) {
|
||||
this.permission = permission;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentBuilder<T> customFailure(@NotNull LangText text) {
|
||||
return this.customFailure(text.getMessage());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentBuilder<T> customFailure(@Nullable LangMessage message) {
|
||||
this.failureMessage = message;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentBuilder<T> withSamples(@NotNull Function<TabContext, List<String>> samples) {
|
||||
this.samples = samples;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public CommandArgument<T> build() {
|
||||
return new CommandArgument<>(this.name, this.parser, this.required, this.complex, this.localized, this.permission, this.failureMessage, this.samples);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package su.nightexpress.nightcore.command.experimental.builder;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.experimental.node.NodeExecutor;
|
||||
import su.nightexpress.nightcore.command.experimental.node.ChainedNode;
|
||||
import su.nightexpress.nightcore.command.experimental.node.CommandNode;
|
||||
import su.nightexpress.nightcore.command.experimental.node.DirectNode;
|
||||
import su.nightexpress.nightcore.language.entry.LangString;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class ChainedNodeBuilder extends NodeBuilder<ChainedNode, ChainedNodeBuilder> {
|
||||
|
||||
private final Map<String, CommandNode> childrenMap;
|
||||
|
||||
private String localized;
|
||||
private NodeExecutor executor;
|
||||
|
||||
public ChainedNodeBuilder(@NotNull NightCorePlugin plugin, @NotNull String... aliases) {
|
||||
super(plugin, aliases);
|
||||
this.childrenMap = new HashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
protected ChainedNodeBuilder getThis() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ChainedNodeBuilder localized(@NotNull LangString localized) {
|
||||
return this.localized(localized.getString());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ChainedNodeBuilder localized(@Nullable String localized) {
|
||||
this.localized = localized;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ChainedNodeBuilder addChained(@NotNull String name, @NotNull Consumer<ChainedNodeBuilder> consumer) {
|
||||
ChainedNodeBuilder builder = ChainedNode.builder(this.plugin, name);
|
||||
consumer.accept(builder);
|
||||
return this.child(builder);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ChainedNodeBuilder addDirect(@NotNull String name, @NotNull Consumer<DirectNodeBuilder> consumer) {
|
||||
DirectNodeBuilder builder = DirectNode.builder(this.plugin, name);
|
||||
consumer.accept(builder);
|
||||
return this.child(builder);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <S extends CommandNode, B extends NodeBuilder<S, B>> ChainedNodeBuilder child(@NotNull B builder) {
|
||||
return this.child(builder.build());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private ChainedNodeBuilder child(@NotNull CommandNode name) {
|
||||
this.childrenMap.put(name.getName(), name);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ChainedNodeBuilder fallback(@NotNull NodeExecutor executor) {
|
||||
this.executor = executor;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public ChainedNode build() {
|
||||
return new ChainedNode(this.plugin, this.name, this.aliases, this.description, this.localized, this.permission, this.playerOnly,
|
||||
this.executor, this.childrenMap);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package su.nightexpress.nightcore.command.experimental.builder;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.ArgumentParser;
|
||||
import su.nightexpress.nightcore.command.experimental.flag.ContentFlag;
|
||||
|
||||
public class ContentFlagBuilder<T> extends FlagBuilder<ContentFlag<T>, ContentFlagBuilder<T>> {
|
||||
|
||||
private final ArgumentParser<T> parser;
|
||||
|
||||
private String sample;
|
||||
|
||||
// public ContentFlagBuilder(@NotNull String name, @NotNull Function<String , T> parser) {
|
||||
// super(name);
|
||||
// this.parser = parser;
|
||||
// this.sample = "";
|
||||
// }
|
||||
|
||||
public ContentFlagBuilder(@NotNull String name, @NotNull ArgumentParser<T> parser) {
|
||||
super(name);
|
||||
this.parser = parser;
|
||||
this.sample = "";
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
protected ContentFlagBuilder<T> getThis() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ContentFlagBuilder<T> sample(@NotNull String sample) {
|
||||
this.sample = sample;
|
||||
return getThis();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull ContentFlag<T> build() {
|
||||
return new ContentFlag<>(this.name, this.parser, this.sample, this.permission);
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package su.nightexpress.nightcore.command.experimental.builder;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.CommandArgument;
|
||||
import su.nightexpress.nightcore.command.experimental.flag.CommandFlag;
|
||||
import su.nightexpress.nightcore.command.experimental.node.DirectExecutor;
|
||||
import su.nightexpress.nightcore.command.experimental.node.DirectNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class DirectNodeBuilder extends NodeBuilder<DirectNode, DirectNodeBuilder> {
|
||||
|
||||
private final List<CommandArgument<?>> arguments;
|
||||
private final Map<String, CommandFlag> flags;
|
||||
|
||||
private DirectExecutor executor;
|
||||
|
||||
public DirectNodeBuilder(@NotNull NightCorePlugin plugin, @NotNull String... aliases) {
|
||||
super(plugin, aliases);
|
||||
this.arguments = new ArrayList<>();
|
||||
this.flags = new HashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
protected DirectNodeBuilder getThis() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DirectNodeBuilder withArgument(@NotNull ArgumentBuilder<?> builder) {
|
||||
return this.withArgument(builder.build());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DirectNodeBuilder withArgument(@NotNull CommandArgument<?> argument) {
|
||||
this.arguments.add(argument);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DirectNodeBuilder withFlag(@NotNull FlagBuilder<?, ?> builder) {
|
||||
return this.withFlag(builder.build());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DirectNodeBuilder withFlag(@NotNull CommandFlag flag) {
|
||||
this.flags.put(flag.getName(), flag);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DirectNodeBuilder executes(DirectExecutor executor) {
|
||||
this.executor = executor;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public DirectNode build() {
|
||||
return new DirectNode(this.plugin, this.name, this.aliases, this.description, this.permission, this.playerOnly, this.arguments, this.flags, this.executor);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package su.nightexpress.nightcore.command.experimental.builder;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.command.experimental.flag.CommandFlag;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniPermission;
|
||||
|
||||
public abstract class FlagBuilder<F extends CommandFlag, B extends FlagBuilder<F, B>> {
|
||||
|
||||
protected final String name;
|
||||
|
||||
protected String permission;
|
||||
|
||||
public FlagBuilder(@NotNull String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected abstract FlagBuilder<F, B> getThis();
|
||||
|
||||
@NotNull
|
||||
public FlagBuilder<F, B> permission(@NotNull UniPermission permission) {
|
||||
return this.permission(permission.getName());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public FlagBuilder<F, B> permission(@Nullable String permission) {
|
||||
this.permission = permission;
|
||||
return this.getThis();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public abstract F build();
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package su.nightexpress.nightcore.command.experimental.builder;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.experimental.node.CommandNode;
|
||||
import su.nightexpress.nightcore.language.entry.LangString;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniPermission;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public abstract class NodeBuilder<S extends CommandNode, B extends NodeBuilder<S, B>> {
|
||||
|
||||
protected final NightCorePlugin plugin;
|
||||
protected final String name;
|
||||
|
||||
protected String[] aliases;
|
||||
protected String description;
|
||||
protected String permission;
|
||||
protected boolean playerOnly;
|
||||
|
||||
public NodeBuilder(@NotNull NightCorePlugin plugin, @NotNull String... aliases) {
|
||||
this.plugin = plugin;
|
||||
this.name = aliases[0];
|
||||
this.aliases = Stream.of(aliases).skip(1).toArray(String[]::new);
|
||||
this.description = "";
|
||||
this.permission = null;
|
||||
this.playerOnly = false;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected abstract B getThis();
|
||||
|
||||
@NotNull
|
||||
public abstract S build();
|
||||
|
||||
@NotNull
|
||||
public B aliases(@NotNull String... aliases) {
|
||||
this.aliases = aliases;
|
||||
return this.getThis();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public B description(@NotNull LangString description) {
|
||||
return this.description(description.getString());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public B description(@NotNull String description) {
|
||||
this.description = description;
|
||||
return this.getThis();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public B permission(@NotNull UniPermission permission) {
|
||||
return this.permission(permission.getName());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public B permission(@Nullable String permission) {
|
||||
this.permission = permission;
|
||||
return this.getThis();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public B playerOnly() {
|
||||
this.playerOnly = true;
|
||||
return this.getThis();
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package su.nightexpress.nightcore.command.experimental.builder;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.experimental.flag.SimpleFlag;
|
||||
|
||||
public class SimpleFlagBuilder extends FlagBuilder<SimpleFlag, SimpleFlagBuilder> {
|
||||
|
||||
public SimpleFlagBuilder(@NotNull String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
protected SimpleFlagBuilder getThis() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public SimpleFlag build() {
|
||||
return new SimpleFlag(this.name, this.permission);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package su.nightexpress.nightcore.command.experimental.flag;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.util.Placeholders;
|
||||
|
||||
public abstract class CommandFlag {
|
||||
|
||||
public static final char PREFIX = '-';
|
||||
public static final char DELIMITER = '=';
|
||||
|
||||
private final String name;
|
||||
private final String permission;
|
||||
|
||||
public CommandFlag(@NotNull String name, @Nullable String permission) {
|
||||
this.name = name.toLowerCase();
|
||||
this.permission = permission;
|
||||
}
|
||||
|
||||
public boolean hasPermission(@NotNull CommandSender sender) {
|
||||
return this.permission == null || sender.hasPermission(this.permission);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getPrefixed() {
|
||||
return PREFIX + this.getName();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getPrefixedFormatted() {
|
||||
return CoreLang.COMMAND_FLAG_FORMAT.getString().replace(Placeholders.GENERIC_NAME, this.getPrefixed());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getPermission() {
|
||||
return permission;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CommandFlag{" +
|
||||
"name='" + name + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package su.nightexpress.nightcore.command.experimental.flag;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.command.experimental.CommandContext;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.ArgumentParser;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.ParsedArgument;
|
||||
import su.nightexpress.nightcore.command.experimental.builder.ContentFlagBuilder;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ContentFlag<T> extends CommandFlag {
|
||||
|
||||
private final ArgumentParser<T> parser;
|
||||
private final String sample;
|
||||
|
||||
public ContentFlag(@NotNull String name, @NotNull ArgumentParser<T> parser, @Nullable String sample, @Nullable String permission) {
|
||||
super(name, permission);
|
||||
this.parser = parser;
|
||||
this.sample = sample == null ? "" : sample;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public static <T> ContentFlagBuilder<T> builder(@NotNull String name, @NotNull Function<String , T> parser) {
|
||||
// return new ContentFlagBuilder<>(name, parser);
|
||||
return builder(name, (string, context) -> parser.apply(string));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> ContentFlagBuilder<T> builder(@NotNull String name, @NotNull ArgumentParser<T> parser) {
|
||||
return new ContentFlagBuilder<>(name, parser);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public ParsedArgument<T> parse(@NotNull String str, @NotNull CommandContext context) {
|
||||
T result = this.parser.parse(str, context);
|
||||
return result == null ? null : new ParsedArgument<>(result);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getSampled() {
|
||||
return this.getPrefixed() + DELIMITER + this.getSample();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ArgumentParser<T> getParser() {
|
||||
return parser;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getSample() {
|
||||
return sample;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package su.nightexpress.nightcore.command.experimental.flag;
|
||||
|
||||
import org.bukkit.World;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.ArgumentTypes;
|
||||
import su.nightexpress.nightcore.command.experimental.builder.ContentFlagBuilder;
|
||||
import su.nightexpress.nightcore.command.experimental.builder.SimpleFlagBuilder;
|
||||
|
||||
public class FlagTypes {
|
||||
|
||||
@NotNull
|
||||
public static SimpleFlagBuilder simple(@NotNull String name) {
|
||||
return SimpleFlag.builder(name);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ContentFlagBuilder<World> world(@NotNull String name) {
|
||||
return ContentFlag.builder(name, ArgumentTypes.WORLD).sample("world");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ContentFlagBuilder<String> string(@NotNull String name) {
|
||||
return ContentFlag.builder(name, ArgumentTypes.STRING).sample("foo");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ContentFlagBuilder<Integer> integer(@NotNull String name) {
|
||||
return ContentFlag.builder(name, ArgumentTypes.INTEGER).sample("0");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ContentFlagBuilder<Double> decimal(@NotNull String name) {
|
||||
return ContentFlag.builder(name, ArgumentTypes.DOUBLE).sample("0.0");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ContentFlagBuilder<Boolean> bool(@NotNull String name) {
|
||||
return ContentFlag.builder(name, ArgumentTypes.BOOLEAN).sample(Boolean.TRUE.toString());
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package su.nightexpress.nightcore.command.experimental.flag;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.command.experimental.builder.SimpleFlagBuilder;
|
||||
|
||||
public class SimpleFlag extends CommandFlag {
|
||||
|
||||
public SimpleFlag(@NotNull String name, @Nullable String permission) {
|
||||
super(name, permission);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SimpleFlagBuilder builder(@NotNull String name) {
|
||||
return new SimpleFlagBuilder(name);
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package su.nightexpress.nightcore.command.experimental.impl;
|
||||
|
||||
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;
|
||||
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(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));
|
||||
}
|
||||
|
||||
public static boolean execute(@NotNull NightCorePlugin plugin, @NotNull CommandContext context, @NotNull ParsedArguments arguments) {
|
||||
plugin.reload();
|
||||
context.send(CoreLang.COMMAND_RELOAD_DONE.getMessage(plugin));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package su.nightexpress.nightcore.command.experimental.node;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.experimental.CommandContext;
|
||||
import su.nightexpress.nightcore.command.experimental.TabContext;
|
||||
import su.nightexpress.nightcore.command.experimental.builder.ChainedNodeBuilder;
|
||||
import su.nightexpress.nightcore.command.experimental.builder.NodeBuilder;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.util.Placeholders;
|
||||
import su.nightexpress.nightcore.util.StringUtil;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class ChainedNode extends CommandNode {
|
||||
|
||||
private final String localized;
|
||||
private final Map<String, CommandNode> commandMap;
|
||||
|
||||
private NodeExecutor fallback;
|
||||
|
||||
public ChainedNode(@NotNull NightCorePlugin plugin,
|
||||
@NotNull String name,
|
||||
@NotNull String[] aliases,
|
||||
@NotNull String description,
|
||||
@Nullable String localized,
|
||||
@Nullable String permission,
|
||||
boolean playerOnly,
|
||||
@Nullable NodeExecutor fallback,
|
||||
@NotNull Map<String, CommandNode> commandMap) {
|
||||
super(plugin, name, aliases, description, permission, playerOnly);
|
||||
this.localized = localized == null ? StringUtil.capitalizeUnderscored(name) : localized;
|
||||
this.commandMap = new HashMap<>();
|
||||
this.setFallback(fallback);
|
||||
|
||||
this.addChildren(DirectNode.builder(plugin, "help")
|
||||
.description(CoreLang.COMMAND_HELP_DESC)
|
||||
.permission(permission)
|
||||
.executes((context, arguments) -> this.sendCommandList(context))
|
||||
);
|
||||
|
||||
commandMap.values().forEach(this::addChildren);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ChainedNodeBuilder builder(@NotNull NightCorePlugin plugin, @NotNull String... aliases) {
|
||||
return new ChainedNodeBuilder(plugin, aliases);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean onRun(@NotNull CommandContext context) {
|
||||
if (context.length() == 0 || context.getArgumentIndex() >= context.length()) {
|
||||
return this.onFallback(context);
|
||||
}
|
||||
|
||||
String node = context.getArgs()[context.getArgumentIndex()];
|
||||
CommandNode children = this.commandMap.get(node);
|
||||
if (children == null) {
|
||||
return this.onFallback(context);
|
||||
}
|
||||
|
||||
context.setArgumentIndex(context.getArgumentIndex() + 1);
|
||||
return children.run(context);
|
||||
}
|
||||
|
||||
public void setFallback(@Nullable NodeExecutor fallback) {
|
||||
this.fallback = fallback;
|
||||
}
|
||||
|
||||
private boolean onFallback(@NotNull CommandContext context) {
|
||||
if (this.fallback != null) {
|
||||
return this.fallback.run(context);
|
||||
}
|
||||
return this.sendCommandList(context);
|
||||
}
|
||||
|
||||
private boolean sendCommandList(@NotNull CommandContext context) {
|
||||
CommandSender sender = context.getSender();
|
||||
|
||||
context.send(CoreLang.COMMAND_HELP_LIST.getMessage(), replacer -> replacer
|
||||
.replace(Placeholders.GENERIC_NAME, this.localized)
|
||||
.replace(Placeholders.GENERIC_ENTRY, list -> {
|
||||
this.getChildrens().stream().sorted(Comparator.comparing(CommandNode::getName)).forEach(children -> {
|
||||
if (!children.hasPermission(sender)) return;
|
||||
|
||||
list.add(CoreLang.COMMAND_HELP_ENTRY.getString()
|
||||
.replace(Placeholders.COMMAND_LABEL, children.getNameWithParents())
|
||||
.replace(Placeholders.COMMAND_USAGE, children.getUsage())
|
||||
.replace(Placeholders.COMMAND_DESCRIPTION, children.getDescription())
|
||||
);
|
||||
});
|
||||
}));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public List<String> getTab(@NotNull TabContext context) {
|
||||
int index = context.getLastCommandIndex();
|
||||
|
||||
if (index == context.length() - 1) {
|
||||
return this.getChildrens().stream().filter(node -> node.hasPermission(context.getSender())).map(CommandNode::getName).toList();
|
||||
}
|
||||
if (index >= context.length()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
String node = context.getArg(index);
|
||||
CommandNode children = this.commandMap.get(node);
|
||||
if (children == null) return Collections.emptyList();
|
||||
|
||||
context.setLastCommandIndex(index + 1);
|
||||
|
||||
return children.getTab(context);
|
||||
}
|
||||
|
||||
public void addChildren(@NotNull NodeBuilder<?, ?> builder) {
|
||||
this.addChildren(builder.build());
|
||||
}
|
||||
|
||||
public void addChildren(@NotNull CommandNode children) {
|
||||
if (children.getParent() != null) return;
|
||||
|
||||
this.commandMap.put(children.getName(), children);
|
||||
for (String alias : children.getAliases()) {
|
||||
this.commandMap.put(alias, children);
|
||||
}
|
||||
children.setParent(this);
|
||||
}
|
||||
|
||||
public void removeChildren(@NotNull String alias) {
|
||||
this.commandMap.keySet().removeIf(key -> key.equalsIgnoreCase(alias));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public CommandNode getChildren(@NotNull String alias) {
|
||||
return this.commandMap.get(alias);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<CommandNode> getChildrens() {
|
||||
return new HashSet<>(this.commandMap.values());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getLocalized() {
|
||||
return this.localized;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<String, CommandNode> getCommandMap() {
|
||||
return this.commandMap;
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package su.nightexpress.nightcore.command.experimental.node;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.experimental.CommandContext;
|
||||
import su.nightexpress.nightcore.command.experimental.TabContext;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public abstract class CommandNode implements NodeExecutor {
|
||||
|
||||
protected final NightCorePlugin plugin;
|
||||
protected final String name;
|
||||
protected final String[] aliases;
|
||||
protected final String description;
|
||||
protected final String permission;
|
||||
protected final boolean playerOnly;
|
||||
|
||||
protected CommandNode parent;
|
||||
|
||||
public CommandNode(@NotNull NightCorePlugin plugin,
|
||||
@NotNull String name,
|
||||
@NotNull String[] aliases,
|
||||
@NotNull String description,
|
||||
@Nullable String permission,
|
||||
boolean playerOnly) {
|
||||
this.plugin = plugin;
|
||||
this.name = name.toLowerCase();
|
||||
this.aliases = Stream.of(aliases).map(String::toLowerCase).toArray(String[]::new);
|
||||
this.description = description;
|
||||
this.permission = permission;
|
||||
this.playerOnly = playerOnly;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public abstract List<String> getTab(@NotNull TabContext context);
|
||||
|
||||
@Override
|
||||
public boolean run(@NotNull CommandContext context) {
|
||||
if (this.isPlayerOnly() && !(context.getSender() instanceof Player)) {
|
||||
context.errorPlayerOnly();
|
||||
return false;
|
||||
}
|
||||
if (!this.hasPermission(context.getSender())) {
|
||||
context.errorPermission();
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.onRun(context);
|
||||
}
|
||||
|
||||
protected abstract boolean onRun(@NotNull CommandContext context);
|
||||
|
||||
public boolean hasPermission(@NotNull CommandSender sender) {
|
||||
return this.permission == null || sender.hasPermission(this.permission);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getNameWithParents() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
CommandNode parent = this.getParent();
|
||||
while (parent != null) {
|
||||
if (!builder.isEmpty()) {
|
||||
builder.insert(0, " ");
|
||||
}
|
||||
builder.insert(0, parent.getName());
|
||||
parent = parent.getParent();
|
||||
}
|
||||
|
||||
builder.append(" ").append(this.getName());
|
||||
|
||||
return builder.toString().strip();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String[] getAliases() {
|
||||
return this.aliases;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getUsage() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public CommandNode getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
protected void setParent(@Nullable CommandNode parent) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getPermission() {
|
||||
return permission;
|
||||
}
|
||||
|
||||
public boolean isPlayerOnly() {
|
||||
return this.playerOnly;
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package su.nightexpress.nightcore.command.experimental.node;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.experimental.CommandContext;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.ParsedArguments;
|
||||
|
||||
public interface DirectExecutor {
|
||||
|
||||
boolean execute(@NotNull CommandContext context, @NotNull ParsedArguments arguments);
|
||||
}
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
package su.nightexpress.nightcore.command.experimental.node;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.experimental.CommandContext;
|
||||
import su.nightexpress.nightcore.command.experimental.TabContext;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.CommandArgument;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.ParsedArgument;
|
||||
import su.nightexpress.nightcore.command.experimental.argument.ParsedArguments;
|
||||
import su.nightexpress.nightcore.command.experimental.builder.DirectNodeBuilder;
|
||||
import su.nightexpress.nightcore.command.experimental.flag.CommandFlag;
|
||||
import su.nightexpress.nightcore.command.experimental.flag.ContentFlag;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.util.Lists;
|
||||
import su.nightexpress.nightcore.util.Placeholders;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class DirectNode extends CommandNode implements DirectExecutor {
|
||||
|
||||
private final List<CommandArgument<?>> arguments;
|
||||
private final Map<String, CommandFlag> flags;
|
||||
private final DirectExecutor executor;
|
||||
|
||||
private final int requiredArguments;
|
||||
|
||||
public DirectNode(@NotNull NightCorePlugin plugin,
|
||||
@NotNull String name,
|
||||
@NotNull String[] aliases,
|
||||
@NotNull String description,
|
||||
@Nullable String permission,
|
||||
boolean playerOnly,
|
||||
@NotNull List<CommandArgument<?>> arguments,
|
||||
@NotNull Map<String, CommandFlag> flags,
|
||||
@NotNull DirectExecutor executor) {
|
||||
super(plugin, name, aliases, description, permission, playerOnly);
|
||||
this.arguments = Collections.unmodifiableList(arguments);
|
||||
this.flags = Collections.unmodifiableMap(flags);
|
||||
this.executor = executor;
|
||||
this.requiredArguments = (int) this.arguments.stream().filter(CommandArgument::isRequired).count();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static DirectNodeBuilder builder(@NotNull NightCorePlugin plugin, @NotNull String... aliases) {
|
||||
return new DirectNodeBuilder(plugin, aliases);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean execute(@NotNull CommandContext context, @NotNull ParsedArguments arguments) {
|
||||
return this.executor.execute(context, arguments);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean onRun(@NotNull CommandContext context) {
|
||||
CommandSender sender = context.getSender();
|
||||
String[] args = context.getArgs();
|
||||
int index = context.getArgumentIndex();
|
||||
//System.out.println("plaincmd args = " + Arrays.toString(args));
|
||||
//System.out.println("plaincmd index = " + index);
|
||||
|
||||
ParsedArguments parsedArguments = new ParsedArguments();
|
||||
for (CommandArgument<?> argument : this.arguments) {
|
||||
if (index >= args.length) break;
|
||||
|
||||
if (!argument.hasPermission(sender)) {
|
||||
context.errorPermission();
|
||||
return false;
|
||||
}
|
||||
|
||||
String arg;
|
||||
// must be last.
|
||||
if (argument.isComplex()) {
|
||||
arg = Stream.of(args).skip(index).collect(Collectors.joining(" "));
|
||||
}
|
||||
else {
|
||||
arg = args[index++];
|
||||
}
|
||||
|
||||
//String
|
||||
ParsedArgument<?> parsedArgument = argument.parse(arg, context);
|
||||
if (parsedArgument == null) {
|
||||
context.send(argument.getFailureMessage(this.plugin), replacer -> replacer
|
||||
.replace(Placeholders.GENERIC_VALUE, arg)
|
||||
.replace(Placeholders.GENERIC_NAME, argument.getLocalized())
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
parsedArguments.add(argument, parsedArgument);
|
||||
}
|
||||
|
||||
if (parsedArguments.getArgumentMap().size() < this.requiredArguments) {
|
||||
context.send(CoreLang.ERROR_COMMAND_USAGE.getMessage(this.plugin), replacer -> replacer
|
||||
.replace(Placeholders.COMMAND_LABEL, this.getNameWithParents())
|
||||
.replace(Placeholders.COMMAND_USAGE, this.getUsage())
|
||||
.replace(Placeholders.COMMAND_DESCRIPTION, this.getDescription()));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!this.flags.isEmpty() && index < args.length) {
|
||||
for (int flagIndex = index; flagIndex < args.length; flagIndex++) {
|
||||
String arg = args[flagIndex];
|
||||
if (arg.charAt(0) != CommandFlag.PREFIX) continue;
|
||||
|
||||
int delimiterIndex = arg.indexOf(ContentFlag.DELIMITER);
|
||||
boolean hasDelimiter = delimiterIndex != -1;
|
||||
|
||||
String flagName = (hasDelimiter ? arg.substring(0, delimiterIndex) : arg).substring(1);
|
||||
CommandFlag flag = this.getFlag(flagName);
|
||||
if (flag == null || parsedArguments.hasFlag(flag) || !flag.hasPermission(sender)) continue;
|
||||
|
||||
if (flag instanceof ContentFlag<?> contentFlag) {
|
||||
if (!hasDelimiter) continue;
|
||||
|
||||
String content = arg.substring(delimiterIndex + 1);
|
||||
if (content.isEmpty()) continue;
|
||||
|
||||
ParsedArgument<?> parsed = contentFlag.parse(content, context);
|
||||
if (parsed == null) {
|
||||
context.send(CoreLang.ERROR_COMMAND_PARSE_FLAG.getMessage(this.plugin), replacer -> replacer
|
||||
.replace(Placeholders.GENERIC_VALUE, content)
|
||||
.replace(Placeholders.GENERIC_NAME, flag.getName())
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
parsedArguments.addFlag(flag, parsed);
|
||||
}
|
||||
else {
|
||||
parsedArguments.addFlag(flag, new ParsedArgument<>(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this.execute(context, parsedArguments);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public List<String> getTab(@NotNull TabContext context) {
|
||||
if (this.isPlayerOnly() && context.getPlayer() == null) return Collections.emptyList();
|
||||
|
||||
int firstArgIndex = context.getLastCommandIndex();
|
||||
int tabLength = context.length();
|
||||
int argIndex = 0;
|
||||
List<String> samples = new ArrayList<>();
|
||||
|
||||
//System.out.println("firstArgIndex = " + firstArgIndex);
|
||||
//System.out.println("context.getArgs() = " + Arrays.toString(context.getArgs()));
|
||||
|
||||
for (int tabIndex = firstArgIndex; tabIndex < tabLength; tabIndex++) {
|
||||
String tabValue = context.getArg(tabIndex);
|
||||
boolean lastIndex = tabIndex == tabLength - 1;
|
||||
|
||||
if (argIndex >= this.arguments.size()) {
|
||||
if (!this.arguments.isEmpty()) {
|
||||
CommandArgument<?> lastArgument = this.arguments.getLast();
|
||||
if (lastArgument.isComplex()) {
|
||||
if (lastIndex) samples = this.getArgumentSamples(lastArgument, context);
|
||||
context.appendArgumentCache(lastArgument, tabValue);
|
||||
}
|
||||
}
|
||||
|
||||
for (CommandFlag commandFlag : this.getFlags()) {
|
||||
if (context.hasCachedFlag(commandFlag)) continue;
|
||||
if (!commandFlag.hasPermission(context.getSender())) continue;
|
||||
|
||||
if (lastIndex) {
|
||||
if (commandFlag instanceof ContentFlag<?> contentFlag) {
|
||||
samples = Lists.newList(contentFlag.getSampled());
|
||||
}
|
||||
else {
|
||||
samples = Lists.newList(commandFlag.getPrefixed());
|
||||
}
|
||||
}
|
||||
context.cacheFlag(commandFlag, tabValue);
|
||||
}
|
||||
}
|
||||
else {
|
||||
CommandArgument<?> argument = this.arguments.get(argIndex++);
|
||||
|
||||
context.cacheArgument(argument, tabValue);
|
||||
|
||||
if (lastIndex) {
|
||||
samples = this.getArgumentSamples(argument, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//System.out.println("context.getArgumentData() = " + context.getArgumentData());
|
||||
//System.out.println("context.getFlagData() = " + context.getFlagData());
|
||||
|
||||
return samples;
|
||||
|
||||
// int index = context.getArgs().length - (context.getIndex() + 1);
|
||||
// //System.out.println("index = " + index);
|
||||
// //System.out.println("arguments.size() = " + arguments.size());
|
||||
// if (index >= this.arguments.size()) {
|
||||
// if (!this.arguments.isEmpty()) {
|
||||
// CommandArgument<?> lastArgument = this.arguments.getLast();
|
||||
// if (lastArgument.isComplex()) return this.getArgumentSamples(lastArgument, context);
|
||||
// }
|
||||
//
|
||||
// List<String> samples = new ArrayList<>();
|
||||
//
|
||||
// this.getFlags().forEach(commandFlag -> {
|
||||
// if (!commandFlag.hasPermission(context.getSender())) return;
|
||||
// if (commandFlag instanceof ContentFlag<?> contentFlag) {
|
||||
// samples.add(contentFlag.getSampled());
|
||||
// }
|
||||
// else {
|
||||
// samples.add(commandFlag.getPrefixed());
|
||||
// }
|
||||
// });
|
||||
//
|
||||
// return samples;
|
||||
// }
|
||||
//
|
||||
// CommandArgument<?> argument = this.arguments.get(index);
|
||||
// return this.getArgumentSamples(argument, context);
|
||||
}
|
||||
|
||||
private List<String> getArgumentSamples(@NotNull CommandArgument<?> argument, @NotNull TabContext context) {
|
||||
if (!argument.hasPermission(context.getSender())) return Collections.emptyList();
|
||||
|
||||
//System.out.println("argument = " + argument);
|
||||
return argument.getSamples(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getUsage() {
|
||||
StringBuilder labelBuilder = new StringBuilder();
|
||||
|
||||
this.arguments.forEach(argument -> {
|
||||
if (!labelBuilder.isEmpty()) {
|
||||
labelBuilder.append(" ");
|
||||
}
|
||||
labelBuilder.append(argument.getLocalized());
|
||||
});
|
||||
|
||||
StringBuilder flagBuilder = new StringBuilder();
|
||||
this.flags.values().forEach(commandFlag -> {
|
||||
if (!flagBuilder.isEmpty()) {
|
||||
flagBuilder.append(" ");
|
||||
}
|
||||
flagBuilder.append(commandFlag.getPrefixedFormatted());
|
||||
});
|
||||
|
||||
if (!flagBuilder.isEmpty()) {
|
||||
labelBuilder.append(" ").append(flagBuilder);
|
||||
}
|
||||
|
||||
return labelBuilder.toString();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<CommandArgument<?>> getArguments() {
|
||||
return arguments;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public CommandFlag getFlag(@NotNull String name) {
|
||||
return this.flags.get(name.toLowerCase());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Collection<CommandFlag> getFlags() {
|
||||
return this.flags.values();
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package su.nightexpress.nightcore.command.experimental.node;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.experimental.CommandContext;
|
||||
|
||||
public interface NodeExecutor {
|
||||
|
||||
boolean run(@NotNull CommandContext context);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package su.nightexpress.nightcore.command.impl;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.CommandFlag;
|
||||
import su.nightexpress.nightcore.command.CommandResult;
|
||||
import su.nightexpress.nightcore.command.api.NightCommand;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.core.CorePerms;
|
||||
import su.nightexpress.nightcore.util.Placeholders;
|
||||
import su.nightexpress.nightcore.util.placeholder.PlaceholderMap;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Deprecated
|
||||
public abstract class AbstractCommand<P extends NightCorePlugin> implements NightCommand {
|
||||
|
||||
protected final P plugin;
|
||||
private final String[] aliases;
|
||||
private final Map<String, NightCommand> childrens;
|
||||
private final Map<String, CommandFlag<?>> commandFlags;
|
||||
private final PlaceholderMap placeholderMap;
|
||||
|
||||
private NightCommand parent;
|
||||
private String permission;
|
||||
private String usage;
|
||||
private String description;
|
||||
private boolean playerOnly;
|
||||
|
||||
public AbstractCommand(@NotNull P plugin, @NotNull String[] aliases) {
|
||||
this(plugin, aliases, (String) null);
|
||||
}
|
||||
|
||||
public AbstractCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable Permission permission) {
|
||||
this(plugin, aliases, permission == null ? null : permission.getName());
|
||||
}
|
||||
|
||||
public AbstractCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable String permission) {
|
||||
this.plugin = plugin;
|
||||
this.aliases = Stream.of(aliases).map(String::toLowerCase).toArray(String[]::new);
|
||||
this.permission = permission;
|
||||
this.childrens = new TreeMap<>();
|
||||
this.commandFlags = new HashMap<>();
|
||||
this.placeholderMap = new PlaceholderMap()
|
||||
.add(Placeholders.COMMAND_DESCRIPTION, this::getDescription)
|
||||
.add(Placeholders.COMMAND_USAGE, this::getUsage)
|
||||
.add(Placeholders.COMMAND_LABEL, this::getLabelWithParents);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PlaceholderMap getPlaceholders() {
|
||||
return this.placeholderMap;
|
||||
}
|
||||
|
||||
protected abstract void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result);
|
||||
|
||||
@NotNull
|
||||
public List<String> getTab(@NotNull Player player, int arg, @NotNull String[] args) {
|
||||
if (player.hasPermission(CorePerms.COMMAND_FLAGS)) {
|
||||
return this.getFlags().stream().map(CommandFlag::getNamePrefixed).toList();
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void execute(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args) {
|
||||
if (this.isPlayerOnly() && !(sender instanceof Player)) {
|
||||
this.errorSender(sender);
|
||||
return;
|
||||
}
|
||||
if (!this.hasPermission(sender)) {
|
||||
this.errorPermission(sender);
|
||||
return;
|
||||
}
|
||||
|
||||
List<String> cleanArgs = new ArrayList<>();
|
||||
Map<CommandFlag<?>, StringBuilder> flagContent = new HashMap<>();
|
||||
CommandFlag<?> lastFlag = null;
|
||||
|
||||
for (String arg : args) {
|
||||
CommandFlag<?> found = arg.charAt(0) == CommandFlag.PREFIX ? this.getFlag(arg.substring(1)) : null;
|
||||
|
||||
if (found != null) {
|
||||
flagContent.put(found, new StringBuilder());
|
||||
lastFlag = found;
|
||||
}
|
||||
else if (lastFlag != null) {
|
||||
StringBuilder builder = flagContent.get(lastFlag);
|
||||
if (!builder.isEmpty()) builder.append(" ");
|
||||
|
||||
builder.append(arg);
|
||||
}
|
||||
else {
|
||||
cleanArgs.add(arg);
|
||||
}
|
||||
}
|
||||
if (!sender.hasPermission(CorePerms.COMMAND_FLAGS)) {
|
||||
flagContent.clear();
|
||||
}
|
||||
|
||||
CommandResult result = new CommandResult(label, cleanArgs.toArray(new String[0]), flagContent);
|
||||
|
||||
this.onExecute(sender, result);
|
||||
}
|
||||
|
||||
public final void addChildren(@NotNull NightCommand children) {
|
||||
if (children.getParent() != null) return;
|
||||
|
||||
Stream.of(children.getAliases()).forEach(alias -> {
|
||||
this.childrens.put(alias, children);
|
||||
});
|
||||
children.setParent(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void removeChildren(@NotNull String alias) {
|
||||
this.childrens.keySet().removeIf(key -> key.equalsIgnoreCase(alias));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public NightCommand getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setParent(@Nullable NightCommand parent) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public final NightCommand getChildren(@NotNull String alias) {
|
||||
return this.childrens.get(alias);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Collection<NightCommand> getChildrens() {
|
||||
return this.childrens.values();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public final String[] getAliases() {
|
||||
return this.aliases;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public final String getPermission() {
|
||||
return this.permission;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPermission(@Nullable String permission) {
|
||||
this.permission = permission;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public CommandFlag<?> getFlag(@NotNull String name) {
|
||||
return this.commandFlags.get(name.toLowerCase());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addFlag(@NotNull CommandFlag<?> flag) {
|
||||
this.commandFlags.put(flag.getName(), flag);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Collection<CommandFlag<?>> getFlags() {
|
||||
return this.commandFlags.values();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getUsage() {
|
||||
return this.usage == null ? "" : this.usage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setUsage(@NotNull String usage) {
|
||||
this.usage = usage;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getDescription() {
|
||||
return this.description == null ? "" : this.description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDescription(@NotNull String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayerOnly() {
|
||||
return this.playerOnly;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPlayerOnly(boolean playerOnly) {
|
||||
this.playerOnly = playerOnly;
|
||||
}
|
||||
|
||||
protected final void errorUsage(@NotNull CommandSender sender) {
|
||||
CoreLang.ERROR_COMMAND_USAGE.getMessage(plugin).replace(this.replacePlaceholders()).send(sender);
|
||||
}
|
||||
|
||||
protected final void errorPermission(@NotNull CommandSender sender) {
|
||||
CoreLang.ERROR_NO_PERMISSION.getMessage(plugin).send(sender);
|
||||
}
|
||||
|
||||
protected final void errorPlayer(@NotNull CommandSender sender) {
|
||||
CoreLang.ERROR_INVALID_PLAYER.getMessage(plugin).send(sender);
|
||||
}
|
||||
|
||||
protected final void errorSender(@NotNull CommandSender sender) {
|
||||
CoreLang.ERROR_COMMAND_PLAYER_ONLY.getMessage(plugin).send(sender);
|
||||
}
|
||||
|
||||
protected final void errorNumber(@NotNull CommandSender sender, @NotNull String from) {
|
||||
CoreLang.ERROR_INVALID_NUMBER.getMessage(plugin).replace(Placeholders.GENERIC_VALUE, from).send(sender);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package su.nightexpress.nightcore.command.impl;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.CommandResult;
|
||||
|
||||
@Deprecated
|
||||
public class BaseCommand extends PluginCommand<NightCorePlugin> {
|
||||
|
||||
public BaseCommand(@NotNull NightCorePlugin plugin) {
|
||||
super(plugin, plugin.getCommandAliases());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package su.nightexpress.nightcore.command.impl;
|
||||
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.api.NightCommand;
|
||||
import su.nightexpress.nightcore.command.api.NightPluginCommand;
|
||||
import su.nightexpress.nightcore.util.Lists;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Deprecated
|
||||
public abstract class PluginCommand<P extends NightCorePlugin> extends AbstractCommand<P> implements NightPluginCommand {
|
||||
|
||||
private Command backend;
|
||||
private NightCommand defaultCommand;
|
||||
|
||||
public PluginCommand(@NotNull P plugin, @NotNull String[] aliases) {
|
||||
this(plugin, aliases, (String) null);
|
||||
}
|
||||
|
||||
public PluginCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable Permission permission) {
|
||||
super(plugin, aliases, permission);
|
||||
}
|
||||
|
||||
public PluginCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable String permission) {
|
||||
super(plugin, aliases, permission);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addDefaultCommand(@NotNull NightCommand command) {
|
||||
this.addChildren(command);
|
||||
this.defaultCommand = command;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public NightCommand getDefaultCommand() {
|
||||
return defaultCommand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Command getBackend() {
|
||||
return backend;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBackend(@NotNull Command backend) {
|
||||
this.backend = backend;
|
||||
}
|
||||
|
||||
//@Override
|
||||
@NotNull
|
||||
private NightCommand findChildren(@NotNull String[] args) {
|
||||
NightCommand command = this;//.defaultCommand;
|
||||
int childCount = 0;
|
||||
while (args.length > childCount) {
|
||||
NightCommand child = command.getChildren(args[childCount++]);
|
||||
if (child == null) break;
|
||||
|
||||
command = child;
|
||||
}
|
||||
return command;
|
||||
}
|
||||
|
||||
/*private int countChildren(@NotNull String[] args) {
|
||||
AbstractCommand<P> command = this;
|
||||
int childCount = 0;
|
||||
while (args.length > childCount) {
|
||||
AbstractCommand<P> child = command.getChildren(args[childCount]);
|
||||
if (child == null) break;
|
||||
|
||||
command = child;
|
||||
childCount++;
|
||||
}
|
||||
return childCount;
|
||||
}*/
|
||||
|
||||
/*private String[] insertArg(@NotNull String arg, int index, String[] args) {
|
||||
List<String> list = new ArrayList<>(Arrays.asList(args));
|
||||
if (index >= list.size()) {
|
||||
list.add(arg);
|
||||
}
|
||||
else list.add(index, arg);
|
||||
return list.toArray(new String[0]);
|
||||
}*/
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) {
|
||||
NightCommand command = this.findChildren(args);
|
||||
if (command instanceof NightPluginCommand pluginCommand) {
|
||||
if (pluginCommand.getDefaultCommand() != null) {
|
||||
command = pluginCommand.getDefaultCommand();
|
||||
//args = insertArg(command.getAliases()[0], 0, args);
|
||||
}
|
||||
}
|
||||
command.execute(sender, label, args);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd,
|
||||
@NotNull String label, String[] args) {
|
||||
|
||||
if (!(sender instanceof Player player) || args.length == 0) return Collections.emptyList();
|
||||
|
||||
NightCommand command = this.findChildren(args);
|
||||
if (!command.hasPermission(sender)) return Collections.emptyList();
|
||||
|
||||
List<String> list = new ArrayList<>();
|
||||
if (!command.getChildrens().isEmpty()) {
|
||||
command.getChildrens().stream().filter(child -> child.hasPermission(sender))
|
||||
.forEach(child -> list.addAll(Arrays.asList(child.getAliases())));
|
||||
}
|
||||
else {
|
||||
list.addAll(command.getTab(player, command.equals(this) ? (args.length) : (args.length - 1), args));
|
||||
}
|
||||
return Lists.getSequentialMatches(list, args[args.length - 1]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package su.nightexpress.nightcore.command.impl;
|
||||
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.command.api.NightPluginCommand;
|
||||
import su.nightexpress.nightcore.util.text.NightMessage;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class WrappedCommand extends Command implements PluginIdentifiableCommand {
|
||||
|
||||
protected final Plugin plugin;
|
||||
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());
|
||||
}
|
||||
|
||||
public WrappedCommand(@NotNull Plugin plugin,
|
||||
@NotNull CommandExecutor executor,
|
||||
@NotNull TabCompleter tabCompleter,
|
||||
@NotNull String[] aliases,
|
||||
@NotNull String description,
|
||||
@NotNull String usage,
|
||||
@Nullable String permission) {
|
||||
/*super(aliases[0], description, usage, Arrays.asList(aliases));
|
||||
this.plugin = plugin;
|
||||
this.executor = executor;
|
||||
this.tabCompleter = tabCompleter;*/
|
||||
this(plugin, executor, tabCompleter, aliases[0], aliases, description, usage, permission);
|
||||
}
|
||||
|
||||
public WrappedCommand(@NotNull Plugin plugin,
|
||||
@NotNull CommandExecutor executor,
|
||||
@NotNull TabCompleter tabCompleter,
|
||||
@NotNull String name,
|
||||
@NotNull String[] aliases,
|
||||
@NotNull String description,
|
||||
@NotNull String usage,
|
||||
@Nullable String permission) {
|
||||
super(name, NightMessage.clean(description), NightMessage.clean(usage), Arrays.asList(aliases));
|
||||
this.plugin = plugin;
|
||||
this.executor = executor;
|
||||
this.tabCompleter = tabCompleter;
|
||||
this.setPermission(permission);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Plugin getPlugin() {
|
||||
return this.plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean execute(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args) {
|
||||
return this.executor.onCommand(sender, this, label, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) {
|
||||
List<String> list = this.tabCompleter.onTabComplete(sender, this, alias, args);
|
||||
return list == null ? Collections.emptyList() : list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
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.NightItem;
|
||||
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.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ConfigValue<T> {
|
||||
|
||||
private final String path;
|
||||
private final T defaultValue;
|
||||
private final String[] description;
|
||||
private final Loader<T> reader;
|
||||
private final Writer<T> writer;
|
||||
|
||||
private T value;
|
||||
private UnaryOperator<T> onRead;
|
||||
|
||||
public ConfigValue(@NotNull String path,
|
||||
@NotNull ConfigValue.Loader<T> reader,
|
||||
@NotNull Writer<T> writer,
|
||||
@NotNull T defaultValue,
|
||||
@Nullable String... description) {
|
||||
this.path = path;
|
||||
this.description = description == null ? new String[0] : description;
|
||||
this.reader = reader;
|
||||
this.writer = writer;
|
||||
this.defaultValue = defaultValue;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public ConfigValue(@NotNull String path,
|
||||
@NotNull ConfigValue.Reader<T> reader,
|
||||
@NotNull Writer<T> writer,
|
||||
@NotNull T defaultValue,
|
||||
@Nullable String... description) {
|
||||
this(path, reader.update(), writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static <T> ConfigValue<T> create(@NotNull String path,
|
||||
@NotNull ConfigValue.Loader<T> reader,
|
||||
@NotNull Writer<T> writer,
|
||||
@NotNull T defaultValue,
|
||||
@Nullable String... description) {
|
||||
return new ConfigValue<>(path, reader, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> ConfigValue<T> create(@NotNull String path,
|
||||
@NotNull ConfigValue.Loader<T> reader,
|
||||
@NotNull Writer<T> writer,
|
||||
@NotNull Supplier<T> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return create(path, reader, writer, defaultValue.get(), description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
private static <T> ConfigValue<T> create(@NotNull String path,
|
||||
@NotNull ConfigValue.Reader<T> reader,
|
||||
@NotNull Writer<T> writer,
|
||||
@NotNull T defaultValue,
|
||||
@Nullable String... description) {
|
||||
return new ConfigValue<>(path, reader.update(), writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public static <T> ConfigValue<T> create(@NotNull String path,
|
||||
@NotNull ConfigValue.Reader<T> reader,
|
||||
@NotNull Writer<T> writer,
|
||||
@NotNull Supplier<T> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return create(path, reader, writer, defaultValue.get(), description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public static <T> ConfigValue<T> create(@NotNull String path, @NotNull ConfigValue.Reader<T> reader, @NotNull T defaultValue, @Nullable String... description) {
|
||||
return create(path, reader.update(), FileConfig::set, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public static <T> ConfigValue<T> create(@NotNull String path, @NotNull ConfigValue.Reader<T> reader, @NotNull Supplier<T> defaultValue, @Nullable String... description) {
|
||||
return create(path, reader.update(), FileConfig::set, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> ConfigValue<T> create(@NotNull String path, @NotNull ConfigValue.Loader<T> reader, @NotNull T defaultValue, @Nullable String... description) {
|
||||
return create(path, reader, FileConfig::set, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> ConfigValue<T> create(@NotNull String path, @NotNull ConfigValue.Loader<T> reader, @NotNull Supplier<T> defaultValue, @Nullable String... description) {
|
||||
return create(path, reader, FileConfig::set, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<Boolean> create(@NotNull String path, boolean defaultValue, @Nullable String... description) {
|
||||
return create(path, (Loader<Boolean>) FileConfig::getBoolean, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<Integer> create(@NotNull String path, int defaultValue, @Nullable String... description) {
|
||||
return create(path, (Loader<Integer>) FileConfig::getInt, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<int[]> create(@NotNull String path, int[] defaultValue, @Nullable String... description) {
|
||||
return create(path, (Loader<int[]>) FileConfig::getIntArray, FileConfig::setIntArray, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<Double> create(@NotNull String path, double defaultValue, @Nullable String... description) {
|
||||
return create(path, (Loader<Double>) FileConfig::getDouble, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<Long> create(@NotNull String path, long defaultValue, @Nullable String... description) {
|
||||
return create(path, (Loader<Long>) FileConfig::getLong, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<String> create(@NotNull String path, @NotNull String defaultValue, @Nullable String... description) {
|
||||
return create(path, (Loader<String>) FileConfig::getString, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<String[]> create(@NotNull String path, @NotNull String[] defaultValue, @Nullable String... description) {
|
||||
return create(path, (Loader<String[]>) FileConfig::getStringArray, FileConfig::setStringArray, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<List<String>> create(@NotNull String path, @NotNull List<String> defaultValue, @Nullable String... description) {
|
||||
return create(path, FileConfig::getStringList, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<Set<String>> create(@NotNull String path, @NotNull Set<String> defaultValue, @Nullable String... description) {
|
||||
return create(path, FileConfig::getStringSet, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public static ConfigValue<ItemStack> create(@NotNull String path, @NotNull ItemStack defaultValue, @Nullable String... description) {
|
||||
return create(path, (Loader<ItemStack>) FileConfig::getItem, FileConfig::setItem, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<NightItem> create(@NotNull String path, @NotNull NightItem defaultValue, @Nullable String... description) {
|
||||
return create(path, (Loader<NightItem>) FileConfig::getCosmeticItem, FileConfig::set, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public static ConfigValue<UniSound> create(@NotNull String path, @NotNull UniSound defaultValue, @Nullable String... description) {
|
||||
Writer<UniSound> writer = (cfg, path1, obj) -> obj.write(cfg, path1);
|
||||
|
||||
return create(path, UniSound::read, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<NightSound> create(@NotNull String path, @NotNull NightSound defaultValue, @Nullable String... description) {
|
||||
// Reader<NightSound> reader = NightSound::read;
|
||||
// Writer<NightSound> writer = (cfg, writePath, sound) -> sound.write(cfg, writePath);
|
||||
|
||||
return create(path, FileConfig::getSound, FileConfig::set, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<UniParticle> create(@NotNull String path, @NotNull UniParticle defaultValue, @Nullable String... description) {
|
||||
Loader<UniParticle> reader = UniParticle::read;
|
||||
Writer<UniParticle> writer = (cfg, path1, obj) -> obj.write(cfg, path1);
|
||||
|
||||
return create(path, reader, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public static ConfigValue<UniFormatter> create(@NotNull String path, @NotNull UniFormatter defaultValue, @Nullable String... description) {
|
||||
// Reader<UniFormatter> reader = UniFormatter::read;
|
||||
// Writer<UniFormatter> writer = (cfg, path1, obj) -> obj.write(cfg, path1);
|
||||
//
|
||||
// return create(path, reader, writer, defaultValue, description);
|
||||
|
||||
return create(path, UniFormatter::read, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <E extends Enum<E>> ConfigValue<E> create(@NotNull String path, @NotNull Class<E> clazz, @NotNull E defaultValue, @Nullable String... description) {
|
||||
Loader<E> reader = (cfg, path1) -> cfg.getEnum(path1, clazz);
|
||||
Writer<E> writer = (cfg, path1, obj) -> cfg.set(path1, obj.name());
|
||||
|
||||
return create(path, reader, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <V> ConfigValue<Set<V>> forSet(@NotNull String path,
|
||||
@NotNull Function<String, V> reader,
|
||||
@NotNull Writer<Set<V>> writer,
|
||||
@NotNull Supplier<Set<V>> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forSet(path, reader, writer, defaultValue.get(), description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <V> ConfigValue<Set<V>> forSet(@NotNull String path,
|
||||
@NotNull Function<String, V> valFun,
|
||||
@NotNull Writer<Set<V>> writer,
|
||||
@NotNull Set<V> defaultValue,
|
||||
@Nullable String... description) {
|
||||
|
||||
Loader<Set<V>> reader = (cfg, path1) -> cfg.getStringSet(path1).stream().map(valFun).filter(Objects::nonNull).collect(Collectors.toCollection(HashSet::new));
|
||||
|
||||
return create(path, reader, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@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,
|
||||
@NotNull Writer<Map<K, V>> writer,
|
||||
@NotNull Supplier<Map<K, V>> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forMap(path, keyFun, valFun, writer, defaultValue.get(), description);
|
||||
}
|
||||
|
||||
@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,
|
||||
@NotNull Writer<Map<K, V>> writer,
|
||||
@NotNull Map<K, V> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forMap(path, keyFun, valFun, HashMap::new, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@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,
|
||||
@NotNull Writer<TreeMap<K, V>> writer,
|
||||
@NotNull Supplier<TreeMap<K, V>> defaultValue, @Nullable String... description) {
|
||||
return forTreeMap(path, keyFun, valFun, writer, defaultValue.get(), description);
|
||||
}
|
||||
|
||||
@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,
|
||||
@NotNull Writer<TreeMap<K, V>> writer,
|
||||
@NotNull TreeMap<K, V> defaultValue, @Nullable String... description) {
|
||||
return forMap(path, keyFun, valFun, TreeMap::new, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@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,
|
||||
@NotNull Supplier<M> mapSupplier,
|
||||
@NotNull Writer<M> writer,
|
||||
@NotNull M defaultValue, @Nullable String... description) {
|
||||
Loader<M> reader = (cfg, path1) -> {
|
||||
M map = mapSupplier.get();
|
||||
for (String id : cfg.getSection(path1)) {
|
||||
K key = keyFun.apply(id);
|
||||
V val = valFun.apply(cfg, path1, id);
|
||||
if (key == null || val == null) continue;
|
||||
|
||||
map.put(key, val);
|
||||
}
|
||||
return map;
|
||||
};
|
||||
|
||||
return create(path, reader, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <K, V> ConfigValue<Map<K, V>> forMap(@NotNull String path,
|
||||
@NotNull Function<String, K> keyReadFun,
|
||||
@NotNull Function<K, String> keyWriteFun,
|
||||
@NotNull ReadFunction<V> valReadFun,
|
||||
@NotNull Consumer<Map<K, V>> defaultValue,
|
||||
@Nullable String... description) {
|
||||
Loader<Map<K, V>> reader = (config, readPath) -> {
|
||||
var map = new HashMap<K, V>();
|
||||
for (String keyRaw : config.getSection(readPath)) {
|
||||
K key = keyReadFun.apply(keyRaw);
|
||||
V val = valReadFun.read(config, readPath + "." + keyRaw, keyRaw);
|
||||
if (key == null || val == null) continue;
|
||||
|
||||
map.put(key, val);
|
||||
}
|
||||
return map;
|
||||
};
|
||||
|
||||
Writer<Map<K, V>> writer = (config, writePath, map) -> {
|
||||
map.forEach((key, value) -> {
|
||||
String keyRaw = keyWriteFun.apply(key);
|
||||
config.set(writePath + "." + keyRaw, value);
|
||||
//value.write(config, 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<Map<K, V>> forMap(@NotNull String path,
|
||||
@NotNull Function<String, K> keyReadFun,
|
||||
@NotNull Function<K, String> keyWriteFun,
|
||||
@NotNull BiFunction<FileConfig, String, V> valReadFun,
|
||||
@NotNull Consumer<Map<K, V>> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forMap(path,keyReadFun, keyWriteFun, (cfg, path2, id) -> valReadFun.apply(cfg, path2), defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <V> ConfigValue<Map<String, V>> forMapById(@NotNull String path,
|
||||
@NotNull BiFunction<FileConfig, String, V> valReadFun,
|
||||
@NotNull Consumer<Map<String, V>> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forMapById(path, (cfg, path2, id) -> valReadFun.apply(cfg, path2), defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <V> ConfigValue<Map<String, V>> forMapById(@NotNull String path,
|
||||
@NotNull ReadFunction<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> 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 forMapByEnum(path, clazz, (cfg, path2, id) -> valReadFun.apply(cfg, path2), defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <E extends Enum<E>, V> ConfigValue<Map<E, V>> forMapByEnum(@NotNull String path,
|
||||
@NotNull Class<E> clazz,
|
||||
@NotNull ReadFunction<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,
|
||||
@NotNull Supplier<Map<String, V>> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forMap(path, String::toLowerCase, function, writer, defaultValue.get(), 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,
|
||||
@NotNull Map<String, V> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forMap(path, String::toLowerCase, function, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigValue<T> onRead(@NotNull UnaryOperator<T> onRead) {
|
||||
this.onRead = onRead;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigValue<T> whenRead(@NotNull Consumer<T> onRead) {
|
||||
this.onRead(object -> {
|
||||
onRead.accept(object);
|
||||
return object;
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public T read(@NotNull FileConfig config) {
|
||||
if (!config.contains(this.path)) {
|
||||
this.write(config);
|
||||
}
|
||||
if (this.description.length > 0 && !this.description[0].isEmpty()) {
|
||||
config.setComments(this.path, this.description);
|
||||
}
|
||||
|
||||
UnaryOperator<T> postRead = this.onRead == null ? value -> value : this.onRead;
|
||||
|
||||
T read = this.reader.read(config, this.path);
|
||||
if (read == null) {
|
||||
read = this.defaultValue;
|
||||
}
|
||||
|
||||
return (this.value = postRead.apply(read));
|
||||
|
||||
//return (this.value = postRead.apply(this.reader.read(config, this.path, this.defaultValue)));
|
||||
}
|
||||
|
||||
public void write(@NotNull FileConfig config) {
|
||||
this.getWriter().write(config, this.getPath(), this.get());
|
||||
}
|
||||
|
||||
public boolean remove(@NotNull FileConfig config) {
|
||||
return config.remove(this.getPath());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public T get() {
|
||||
return this.value == null ? this.defaultValue : this.value;
|
||||
}
|
||||
|
||||
public void set(@NotNull T value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String[] getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public T getDefaultValue() {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigValue.Loader<T> getReader() {
|
||||
return reader;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Writer<T> getWriter() {
|
||||
return writer;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public interface Reader<T> {
|
||||
|
||||
@NotNull T read(@NotNull FileConfig config, @NotNull String path, T def);
|
||||
|
||||
default Loader<T> update() {
|
||||
return (cfg, path) -> read(cfg, path, null);
|
||||
}
|
||||
}
|
||||
|
||||
public interface Loader<T> {
|
||||
|
||||
@Nullable T read(@NotNull FileConfig config, @NotNull String path);
|
||||
}
|
||||
|
||||
public interface Writer<T> {
|
||||
|
||||
void write(@NotNull FileConfig config, @NotNull String path, @NotNull T obj);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
package su.nightexpress.nightcore.config;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.Damageable;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.inventory.meta.LeatherArmorMeta;
|
||||
import org.bukkit.inventory.meta.PotionMeta;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.util.*;
|
||||
import su.nightexpress.nightcore.util.bukkit.NightItem;
|
||||
import su.nightexpress.nightcore.util.bukkit.NightSound;
|
||||
import su.nightexpress.nightcore.util.text.NightMessage;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class FileConfig extends YamlConfiguration {
|
||||
|
||||
public static final String EXTENSION = ".yml";
|
||||
|
||||
private final File file;
|
||||
private boolean changed;
|
||||
|
||||
public FileConfig(@NotNull String path, @NotNull String file) {
|
||||
this(new File(path, file));
|
||||
}
|
||||
|
||||
public FileConfig(@NotNull File file) {
|
||||
this.changed = false;
|
||||
this.options().width(512);
|
||||
|
||||
FileUtil.create(file);
|
||||
this.file = file;
|
||||
this.reload();
|
||||
}
|
||||
|
||||
public static boolean isConfig(@NotNull File file) {
|
||||
return file.getName().endsWith(EXTENSION);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String withExtension(@NotNull String fileName) {
|
||||
return fileName + EXTENSION;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String getName(@NotNull File file) {
|
||||
String name = file.getName();
|
||||
|
||||
if (isConfig(file)) {
|
||||
return name.substring(0, name.length() - EXTENSION.length());
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static FileConfig loadOrExtract(@NotNull NightCorePlugin plugin, @NotNull String path, @NotNull String file) {
|
||||
if (!path.endsWith("/")) {
|
||||
path += "/";
|
||||
}
|
||||
return loadOrExtract(plugin, path + file);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static FileConfig loadOrExtract(@NotNull NightCorePlugin plugin, @NotNull String filePath) {
|
||||
if (!filePath.startsWith("/")) {
|
||||
filePath = "/" + filePath;
|
||||
}
|
||||
|
||||
File file = new File(plugin.getDataFolder() + filePath);
|
||||
if (FileUtil.create(file)) {
|
||||
try (InputStream input = plugin.getClass().getResourceAsStream(filePath)) {
|
||||
if (input != null) FileUtil.copy(input, file);
|
||||
}
|
||||
catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
return new FileConfig(file);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static List<FileConfig> loadAll(@NotNull String path) {
|
||||
return loadAll(path, false);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static List<FileConfig> loadAll(@NotNull String path, boolean deep) {
|
||||
return FileUtil.getConfigFiles(path, deep).stream().map(FileConfig::new).toList();
|
||||
}
|
||||
|
||||
public void initializeOptions(@NotNull Class<?> clazz) {
|
||||
initializeOptions(clazz, this);
|
||||
}
|
||||
|
||||
public static void initializeOptions(@NotNull Class<?> clazz, @NotNull FileConfig config) {
|
||||
for (ConfigValue<?> value : Reflex.getFields(clazz, ConfigValue.class)) {
|
||||
value.read(config);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public File getFile() {
|
||||
return this.file;
|
||||
}
|
||||
|
||||
public void save() {
|
||||
try {
|
||||
this.save(this.file);
|
||||
}
|
||||
catch (IOException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean saveChanges() {
|
||||
if (!this.changed) return false;
|
||||
|
||||
this.save();
|
||||
this.changed = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean reload() {
|
||||
try {
|
||||
this.load(this.file);
|
||||
this.changed = false;
|
||||
return true;
|
||||
}
|
||||
catch (IOException | InvalidConfigurationException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean addMissing(@NotNull String path, @Nullable Object val) {
|
||||
if (this.contains(path)) return false;
|
||||
this.set(path, val);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(@NotNull String path, @Nullable Object value) {
|
||||
if (value instanceof Writeable writeable) {
|
||||
writeable.write(this, path);
|
||||
this.changed = true;
|
||||
return;
|
||||
}
|
||||
else if (value instanceof String str) {
|
||||
value = LegacyColors.plainColors(str);
|
||||
}
|
||||
else if (value instanceof Collection<?> collection) {
|
||||
List<Object> list = new ArrayList<>(collection);
|
||||
list.replaceAll(obj -> obj instanceof String str ? LegacyColors.plainColors(str) : obj);
|
||||
value = list;
|
||||
}
|
||||
else if (value instanceof Location location) {
|
||||
value = LocationUtil.serialize(location);
|
||||
}
|
||||
else if (value instanceof Enum<?> en) {
|
||||
value = en.name();
|
||||
}
|
||||
super.set(path, value);
|
||||
this.changed = true;
|
||||
}
|
||||
|
||||
public void setComments(@NotNull String path, @Nullable String... comments) {
|
||||
this.setComments(path, Arrays.asList(comments));
|
||||
}
|
||||
|
||||
public void setInlineComments(@NotNull String path, @Nullable String... comments) {
|
||||
this.setInlineComments(path, Arrays.asList(comments));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setComments(@NotNull String path, @Nullable List<String> comments) {
|
||||
if (this.getComments(path).equals(comments)) return;
|
||||
|
||||
super.setComments(path, comments);
|
||||
this.changed = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInlineComments(@NotNull String path, @Nullable List<String> comments) {
|
||||
super.setInlineComments(path, comments);
|
||||
}
|
||||
|
||||
public boolean remove(@NotNull String path) {
|
||||
if (!this.contains(path)) return false;
|
||||
this.set(path, null);
|
||||
return true;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<String> getSection(@NotNull String path) {
|
||||
ConfigurationSection section = this.getConfigurationSection(path);
|
||||
return section == null ? Collections.emptySet() : section.getKeys(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String getString(@NotNull String path) {
|
||||
String str = super.getString(path);
|
||||
return str == null || str.isEmpty() ? null : str;
|
||||
// return super.getString(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getString(@NotNull String path, @Nullable String def) {
|
||||
String str = super.getString(path, def);
|
||||
return str == null ? "" : str;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<String> getStringSet(@NotNull String path) {
|
||||
return new HashSet<>(this.getStringList(path));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
@Deprecated
|
||||
public Location getLocation(@NotNull String path) {
|
||||
String raw = this.getString(path);
|
||||
return raw == null ? null : LocationUtil.deserialize(raw);
|
||||
}
|
||||
|
||||
public int[] getIntArray(@NotNull String path) {
|
||||
return getIntArray(path, new int[0]);
|
||||
}
|
||||
|
||||
public int[] getIntArray(@NotNull String path, int[] def) {
|
||||
String str = this.getString(path);
|
||||
return str == null ? def : NumberUtil.getIntArray(str);
|
||||
}
|
||||
|
||||
public void setIntArray(@NotNull String path, int[] arr) {
|
||||
if (arr == null) {
|
||||
this.set(path, null);
|
||||
return;
|
||||
}
|
||||
this.set(path, String.join(",", IntStream.of(arr).boxed().map(String::valueOf).toList()));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String[] getStringArray(@NotNull String path) {
|
||||
return this.getStringArray(path, new String[0]);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String[] getStringArray(@NotNull String path, @NotNull String[] def) {
|
||||
String str = this.getString(path);
|
||||
return str == null ? def : str.split(",");
|
||||
}
|
||||
|
||||
public void setStringArray(@NotNull String path, String[] arr) {
|
||||
if (arr == null) {
|
||||
this.set(path, null);
|
||||
return;
|
||||
}
|
||||
this.set(path, String.join(",", arr));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public <T extends Enum<T>> T getEnum(@NotNull String path, @NotNull Class<T> clazz) {
|
||||
return Enums.get(this.getString(path), clazz);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T extends Enum<T>> T getEnum(@NotNull String path, @NotNull Class<T> clazz, @NotNull T def) {
|
||||
return Enums.parse(this.getString(path), clazz).orElse(def);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T extends Enum<T>> List<T> getEnumList(@NotNull String path, @NotNull Class<T> clazz) {
|
||||
return this.getStringSet(path).stream().map(str -> Enums.parse(str, clazz).orElse(null))
|
||||
.filter(Objects::nonNull).toList();
|
||||
}
|
||||
|
||||
/*@NotNull
|
||||
public Set<FireworkEffect> getFireworkEffects(@NotNull String path) {
|
||||
Set<FireworkEffect> effects = new HashSet<>();
|
||||
for (String sId : this.getSection(path)) {
|
||||
String path2 = path + "." + sId + ".";
|
||||
FireworkEffect.Type type = this.getEnum(path2 + "Type", FireworkEffect.Type.class);
|
||||
if (type == null) continue;
|
||||
|
||||
boolean flicker = this.getBoolean(path2 + "Flicker");
|
||||
boolean trail = this.getBoolean(path2 + "Trail");
|
||||
|
||||
Set<Color> colors = new HashSet<>();
|
||||
for (String colorRaw : this.getStringList(path2 + "Colors")) {
|
||||
colors.add(StringUtil.parseColor(colorRaw));
|
||||
}
|
||||
|
||||
Set<Color> fadeColors = new HashSet<>();
|
||||
for (String colorRaw : this.getStringList(path2 + "Fade_Colors")) {
|
||||
fadeColors.add(StringUtil.parseColor(colorRaw));
|
||||
}
|
||||
|
||||
FireworkEffect.Builder builder = FireworkEffect.builder()
|
||||
.with(type).flicker(flicker).trail(trail).withColor(colors).withFade(fadeColors);
|
||||
effects.add(builder.build());
|
||||
}
|
||||
|
||||
return effects;
|
||||
}*/
|
||||
|
||||
@NotNull
|
||||
public NightItem getCosmeticItem(@NotNull String path, @NotNull NightItem def) {
|
||||
return this.contains(path) ? this.getCosmeticItem(path) : def;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public NightItem getCosmeticItem(@NotNull String path) {
|
||||
return NightItem.read(this, path);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public NightSound getSound(@NotNull String path) {
|
||||
return NightSound.read(this, path); // Update
|
||||
// if (this.contains(path + ".Name")) {
|
||||
// return NightSound.read(this, path); // Update
|
||||
// }
|
||||
// return NightSound.deserialize(this.getString(path, "null"));
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void setSound(@NotNull String path, @NotNull NightSound sound) {
|
||||
this.set(path, sound);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public ItemStack getItem(@NotNull String path, @Nullable ItemStack def) {
|
||||
ItemStack item = this.getItem(path);
|
||||
return item.getType().isAir() && def != null ? def : item;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public ItemStack getItem(@NotNull String path) {
|
||||
if (!path.isEmpty() && !path.endsWith(".")) path = path + ".";
|
||||
|
||||
Material material = BukkitThing.getMaterial(this.getString(path + "Material", BukkitThing.toString(Material.AIR)));
|
||||
if (material == null || material.isAir()) return new ItemStack(Material.AIR);
|
||||
|
||||
ItemStack item = new ItemStack(material);
|
||||
item.setAmount(this.getInt(path + "Amount", 1));
|
||||
|
||||
// -------- UPDATE OLD TEXTURE FIELD - START --------
|
||||
String headTexture = this.getString(path + "Head_Texture");
|
||||
if (headTexture != null && !headTexture.isEmpty()) {
|
||||
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(headTexture);
|
||||
String decodedStr = new String(decoded, StandardCharsets.UTF_8);
|
||||
JsonElement element = JsonParser.parseString(decodedStr);
|
||||
|
||||
String url = element.getAsJsonObject().getAsJsonObject("textures").getAsJsonObject("SKIN").get("url").getAsString();
|
||||
url = url.substring(ItemUtil.TEXTURES_HOST.length());
|
||||
|
||||
this.set(path + "SkinURL", url);
|
||||
this.remove(path + "Head_Texture");
|
||||
}
|
||||
catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
// -------- UPDATE OLD TEXTURE FIELD - END --------
|
||||
|
||||
String headSkin = this.getString(path + "SkinURL");
|
||||
if (headSkin != null) {
|
||||
ItemUtil.setProfileBySkinURL(item, headSkin);
|
||||
}
|
||||
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null) return item;
|
||||
|
||||
int durability = this.getInt(path + "Durability");
|
||||
if (durability > 0 && meta instanceof Damageable damageable) {
|
||||
damageable.setDamage(durability);
|
||||
}
|
||||
|
||||
String name = this.getString(path + "Name");
|
||||
meta.setDisplayName(name != null ? NightMessage.asLegacy(name) : null);
|
||||
meta.setLore(NightMessage.asLegacy(this.getStringList(path + "Lore")));
|
||||
|
||||
for (String sKey : this.getSection(path + "Enchants")) {
|
||||
Enchantment enchantment = BukkitThing.getEnchantment(sKey);
|
||||
if (enchantment == null) continue;
|
||||
|
||||
int level = this.getInt(path + "Enchants." + sKey);
|
||||
if (level <= 0) continue;
|
||||
|
||||
meta.addEnchant(enchantment, level, true);
|
||||
}
|
||||
|
||||
int model = this.getInt(path + "Custom_Model_Data");
|
||||
meta.setCustomModelData(model != 0 ? model : null);
|
||||
|
||||
List<String> flags = this.getStringList(path + "Item_Flags");
|
||||
if (flags.contains(Placeholders.WILDCARD)) {
|
||||
meta.addItemFlags(ItemFlag.values());
|
||||
}
|
||||
else {
|
||||
flags.stream().map(str -> StringUtil.getEnum(str, ItemFlag.class).orElse(null)).filter(Objects::nonNull).forEach(meta::addItemFlags);
|
||||
}
|
||||
|
||||
String colorRaw = this.getString(path + "Color");
|
||||
if (colorRaw != null && !colorRaw.isEmpty()) {
|
||||
Color color = StringUtil.getColor(colorRaw);
|
||||
if (meta instanceof LeatherArmorMeta armorMeta) {
|
||||
armorMeta.setColor(color);
|
||||
}
|
||||
else if (meta instanceof PotionMeta potionMeta) {
|
||||
potionMeta.setColor(color);
|
||||
}
|
||||
}
|
||||
|
||||
meta.setUnbreakable(this.getBoolean(path + "Unbreakable"));
|
||||
item.setItemMeta(meta);
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void setItem(@NotNull String path, @Nullable ItemStack item) {
|
||||
if (item == null) {
|
||||
this.set(path, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!path.endsWith(".")) path = path + ".";
|
||||
this.set(path.substring(0, path.length() - 1), null);
|
||||
|
||||
Material material = item.getType();
|
||||
this.set(path + "Material", material.name());
|
||||
this.set(path + "Amount", item.getAmount() <= 1 ? null : item.getAmount());
|
||||
this.set(path + "SkinURL", ItemUtil.getProfileSkinURL(item));
|
||||
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null) return;
|
||||
|
||||
if (meta instanceof Damageable damageable) {
|
||||
this.set(path + "Durability", damageable.getDamage() <= 0 ? null : damageable.getDamage());
|
||||
}
|
||||
|
||||
this.set(path + "Name", meta.getDisplayName().isEmpty() ? null : meta.getDisplayName());
|
||||
this.set(path + "Lore", meta.getLore());
|
||||
|
||||
for (Map.Entry<Enchantment, Integer> entry : meta.getEnchants().entrySet()) {
|
||||
this.set(path + "Enchants." + entry.getKey().getKey().getKey(), entry.getValue());
|
||||
}
|
||||
this.set(path + "Custom_Model_Data", meta.hasCustomModelData() ? meta.getCustomModelData() : null);
|
||||
|
||||
Color color = null;
|
||||
String colorRaw = null;
|
||||
if (meta instanceof PotionMeta potionMeta) {
|
||||
color = potionMeta.getColor();
|
||||
}
|
||||
else if (meta instanceof LeatherArmorMeta armorMeta) {
|
||||
color = armorMeta.getColor();
|
||||
}
|
||||
if (color != null) {
|
||||
colorRaw = color.getRed() + "," + color.getGreen() + "," + color.getBlue();
|
||||
}
|
||||
this.set(path + "Color", colorRaw);
|
||||
|
||||
List<String> itemFlags = new ArrayList<>(meta.getItemFlags().stream().map(ItemFlag::name).toList());
|
||||
this.set(path + "Item_Flags", itemFlags.isEmpty() ? null : itemFlags);
|
||||
this.set(path + "Unbreakable", meta.isUnbreakable() ? true : null);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Deprecated
|
||||
public ItemStack getItemEncoded(@NotNull String path) {
|
||||
String compressed = this.getString(path);
|
||||
if (compressed == null) return null;
|
||||
|
||||
return ItemNbt.decompress(compressed);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void setItemEncoded(@NotNull String path, @Nullable ItemStack item) {
|
||||
this.set(path, item == null ? null : ItemNbt.compress(item));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public ItemStack[] getItemsEncoded(@NotNull String path) {
|
||||
return ItemNbt.decompress(this.getStringList(path));
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void setItemsEncoded(@NotNull String path, @NotNull List<ItemStack> item) {
|
||||
this.set(path, ItemNbt.compress(item));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package su.nightexpress.nightcore.config;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightDataPlugin;
|
||||
import su.nightexpress.nightcore.NightPlugin;
|
||||
import su.nightexpress.nightcore.database.DatabaseConfig;
|
||||
import su.nightexpress.nightcore.language.LangManager;
|
||||
import su.nightexpress.nightcore.util.text.tag.Tags;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public class PluginDetails implements Writeable {
|
||||
|
||||
private final String name;
|
||||
private final String prefix;
|
||||
private final String[] commandAliases;
|
||||
private final String language;
|
||||
|
||||
@Deprecated
|
||||
private DatabaseConfig databaseConfig;
|
||||
|
||||
private Class<?> configClass;
|
||||
private Class<?> langClass;
|
||||
private Class<?> permissionsClass;
|
||||
|
||||
public PluginDetails(
|
||||
@NotNull String name,
|
||||
@NotNull String prefix,
|
||||
@NotNull String[] commandAliases,
|
||||
@NotNull String language
|
||||
) {
|
||||
this.name = name;
|
||||
this.prefix = prefix;
|
||||
this.commandAliases = commandAliases;
|
||||
this.language = language.toLowerCase();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static PluginDetails create(@NotNull String name, @NotNull String[] commandAliases) {
|
||||
String prefix = Tags.LIGHT_YELLOW.enclose(Tags.BOLD.enclose(name)) + Tags.DARK_GRAY.enclose(" » ") + Tags.GRAY.getBracketsName();
|
||||
String language = Locale.getDefault().getLanguage();
|
||||
|
||||
return new PluginDetails(name, prefix, commandAliases, language);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static PluginDetails read(@NotNull NightPlugin plugin, @NotNull FileConfig config, @NotNull PluginDetails defaults) {
|
||||
//FileConfig config = plugin.getConfig();
|
||||
//PluginDetails defaults = plugin.getDetails();
|
||||
|
||||
String pluginName = ConfigValue.create("Plugin.Name", defaults.getName(),
|
||||
"Localized plugin name. It's used in messages and with internal placeholders.")
|
||||
.read(config);
|
||||
|
||||
String pluginPrefix = ConfigValue.create("Plugin.Prefix", defaults.getPrefix(),
|
||||
"Plugin prefix. Used in messages."
|
||||
).read(config);
|
||||
|
||||
String[] commandAliases = ConfigValue.create("Plugin.Command_Aliases", defaults.getCommandAliases(),
|
||||
"Command names that will be registered as main plugin commands.",
|
||||
"Do not leave this empty. Split multiple names with a comma.")
|
||||
.read(config);
|
||||
|
||||
String languageCode = ConfigValue.create("Plugin.Language", defaults.getLanguage(),
|
||||
"Sets the plugin language.",
|
||||
"Basically it tells the plugin to use certain messages config from the '" + LangManager.DIR_LANG + "' sub-folder.",
|
||||
"If specified language is not available, default one (English) will be used instead.",
|
||||
"[Default is System Locale]")
|
||||
.read(config);
|
||||
|
||||
DatabaseConfig dataConfig = null;
|
||||
if (plugin instanceof NightDataPlugin<?>) {
|
||||
plugin.info("Read database configuration...");
|
||||
dataConfig = DatabaseConfig.read(plugin);
|
||||
}
|
||||
|
||||
return new PluginDetails(pluginName, pluginPrefix, commandAliases, languageCode)
|
||||
.setDatabaseConfig(dataConfig)
|
||||
.setConfigClass(defaults.getConfigClass())
|
||||
.setLangClass(defaults.getLangClass())
|
||||
.setPermissionsClass(defaults.getPermissionsClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(@NotNull FileConfig config, @NotNull String path) {
|
||||
config.set(path + ".Plugin.Name", this.name);
|
||||
config.set(path + ".Plugin.Prefix", this.prefix);
|
||||
config.setStringArray(path + ".Plugin.Command_Aliases", this.commandAliases);
|
||||
config.set(path + ".Plugin.Language", this.language);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getPrefix() {
|
||||
return prefix;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String[] getCommandAliases() {
|
||||
return commandAliases;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getLanguage() {
|
||||
return language;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Deprecated
|
||||
public DatabaseConfig getDatabaseConfig() {
|
||||
return databaseConfig;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public PluginDetails setDatabaseConfig(@Nullable DatabaseConfig databaseConfig) {
|
||||
this.databaseConfig = databaseConfig;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Class<?> getConfigClass() {
|
||||
return configClass;
|
||||
}
|
||||
|
||||
public PluginDetails setConfigClass(@Nullable Class<?> configClass) {
|
||||
this.configClass = configClass;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Class<?> getLangClass() {
|
||||
return langClass;
|
||||
}
|
||||
|
||||
public PluginDetails setLangClass(@Nullable Class<?> langClass) {
|
||||
this.langClass = langClass;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Class<?> getPermissionsClass() {
|
||||
return permissionsClass;
|
||||
}
|
||||
|
||||
public PluginDetails setPermissionsClass(@Nullable Class<?> permissionsClass) {
|
||||
this.permissionsClass = permissionsClass;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package su.nightexpress.nightcore.config;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface ReadFunction<V> {
|
||||
|
||||
@Nullable V read(@NotNull FileConfig config, @NotNull String path, @NotNull String id);
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package su.nightexpress.nightcore.core;
|
||||
|
||||
import su.nightexpress.nightcore.config.ConfigValue;
|
||||
import su.nightexpress.nightcore.util.*;
|
||||
import su.nightexpress.nightcore.util.number.NumberShortcut;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniFormatter;
|
||||
|
||||
import java.math.RoundingMode;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class CoreConfig {
|
||||
|
||||
public static final String DIR_UI = "/ui/";
|
||||
|
||||
public static final ConfigValue<Integer> DATA_FIXER_MISSING_VERSION = ConfigValue.create("DataFixer.MissingVersion",
|
||||
Version.MC_1_21_4.getDataVersion()
|
||||
);
|
||||
|
||||
public static final ConfigValue<Integer> DATA_FIXER_UNKNOWN_VERSION = ConfigValue.create("DataFixer.UnknownVersion",
|
||||
10000
|
||||
);
|
||||
|
||||
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]"
|
||||
);
|
||||
|
||||
@Deprecated
|
||||
public static final ConfigValue<Integer> USER_CACHE_LIFETIME = ConfigValue.create("UserData.Cache.LifeTime",
|
||||
300,
|
||||
"[ OUTDATED, MOVED IN PER-PLUGIN engine.yml ]"
|
||||
);
|
||||
|
||||
public static final ConfigValue<String> TIME_ZONE = ConfigValue.create("Time.TimeZone",
|
||||
TimeZone.getDefault().getID(),
|
||||
"Sets timezone for plugins to handle local dates and times properly."
|
||||
).whenRead(TimeUtil::setTimeZone);
|
||||
|
||||
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.URL_WIKI_TEXT
|
||||
);
|
||||
|
||||
public static final ConfigValue<UniFormatter> NUMBER_FORMAT = ConfigValue.create("Number.Format",
|
||||
UniFormatter::read,
|
||||
UniFormatter.of("#,###.###", RoundingMode.HALF_EVEN),
|
||||
"Control over how numerical data is formatted and rounded.",
|
||||
"Allowed modes: " + Enums.inline(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."
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package su.nightexpress.nightcore.core;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.dialog.Dialog;
|
||||
import su.nightexpress.nightcore.language.entry.*;
|
||||
import su.nightexpress.nightcore.ui.dialog.DialogManager;
|
||||
import su.nightexpress.nightcore.ui.menu.click.ClickKey;
|
||||
import su.nightexpress.nightcore.util.bridge.wrapper.ClickEventType;
|
||||
import su.nightexpress.nightcore.util.bridge.wrapper.HoverEventType;
|
||||
|
||||
import static su.nightexpress.nightcore.util.Placeholders.*;
|
||||
import static su.nightexpress.nightcore.util.text.tag.Tags.*;
|
||||
|
||||
public class CoreLang {
|
||||
|
||||
public static final LangEnum<ClickKey> CLICK_KEY = LangEnum.of("ClickKey", ClickKey.class, map -> {
|
||||
map.put(ClickKey.LEFT, "L-Click");
|
||||
map.put(ClickKey.RIGHT, "R-Click");
|
||||
map.put(ClickKey.SHIFT_LEFT, "Shift + L-Click");
|
||||
map.put(ClickKey.SHIFT_RIGHT, "Shift + R-Click");
|
||||
map.put(ClickKey.DROP_KEY, "Drop [Q]");
|
||||
map.put(ClickKey.SWAP_KEY, "Swap [F]");
|
||||
map.put(ClickKey.DRAG_N_DROP, "Drag & Drop");
|
||||
});
|
||||
|
||||
public static final LangString COMMAND_ARGUMENT_FORMAT_REQUIRED = LangString.of("Command.Argument.Type.Required",
|
||||
LIGHT_RED.enclose("<" + GENERIC_NAME + ">"));
|
||||
|
||||
public static final LangString COMMAND_ARGUMENT_FORMAT_OPTIONAL = LangString.of("Command.Argument.Type.Optional",
|
||||
LIGHT_YELLOW.enclose("[" + GENERIC_NAME + "]"));
|
||||
|
||||
public static final LangString COMMAND_FLAG_FORMAT = LangString.of("Command.Flag.Format",
|
||||
LIGHT_GRAY.enclose("[" + GENERIC_NAME + "]"));
|
||||
|
||||
public static final LangString COMMAND_ARGUMENT_NAME_GENERIC = LangString.of("Command.Argument.Name.Generic", "value");
|
||||
public static final LangString COMMAND_ARGUMENT_NAME_TYPE = LangString.of("Command.Argument.Name.Type", "type");
|
||||
public static final LangString COMMAND_ARGUMENT_NAME_NAME = LangString.of("Command.Argument.Name.Name", "name");
|
||||
public static final LangString COMMAND_ARGUMENT_NAME_PLAYER = LangString.of("Command.Argument.Name.Player", "player");
|
||||
public static final LangString COMMAND_ARGUMENT_NAME_WORLD = LangString.of("Command.Argument.Name.World", "world");
|
||||
public static final LangString COMMAND_ARGUMENT_NAME_AMOUNT = LangString.of("Command.Argument.Name.Amount", "amount");
|
||||
public static final LangString COMMAND_ARGUMENT_NAME_MATERIAL = LangString.of("Command.Argument.Name.Material", "material");
|
||||
public static final LangString COMMAND_ARGUMENT_NAME_ITEM_MATERIAL = LangString.of("Command.Argument.Name.ItemMaterial", "item type");
|
||||
public static final LangString COMMAND_ARGUMENT_NAME_BLOCK_MATERIAL = LangString.of("Command.Argument.Name.BlockMaterial", "block type");
|
||||
public static final LangString COMMAND_ARGUMENT_NAME_ENCHANTMENT = LangString.of("Command.Argument.Name.Enchantment", "enchantment");
|
||||
//public static final LangString COMMAND_ARGUMENT_NAME_POTION_EFFECT = LangString.of("Command.Argument.Name.Effect", "effect");
|
||||
//public static final LangString COMMAND_ARGUMENT_NAME_ATTRIBUTE = LangString.of("Command.Argument.Name.Attribute", "attribute");
|
||||
|
||||
public static final LangText COMMAND_HELP_LIST = LangText.of("Command.Help.List",
|
||||
TAG_NO_PREFIX,
|
||||
" ",
|
||||
" " + YELLOW.enclose(BOLD.enclose(GENERIC_NAME)) + GRAY.enclose(" - ") + YELLOW.enclose(BOLD.enclose("Commands:")),
|
||||
" ",
|
||||
GRAY.enclose(" " + RED.enclose(BOLD.enclose("<>")) + " - Required, " + GREEN.enclose(BOLD.enclose("[]")) + " - Optional."),
|
||||
" ",
|
||||
GENERIC_ENTRY,
|
||||
" "
|
||||
);
|
||||
|
||||
public static final LangString COMMAND_HELP_ENTRY = LangString.of("Command.Help.Entry",
|
||||
" " + 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_CHECKPERM_DESC = LangString.of("Command.CheckPerm.Desc", "Print player permission info.");
|
||||
public static final LangString COMMAND_DUMPITEM_DESC = LangString.of("Command.DumpItem.Desc", "Print item components info.");
|
||||
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") + "!"));
|
||||
|
||||
public static final LangString TIME_DAY = LangString.of("Time.Day", GENERIC_AMOUNT + "d.");
|
||||
public static final LangString TIME_HOUR = LangString.of("Time.Hour", GENERIC_AMOUNT + "h.");
|
||||
public static final LangString TIME_MINUTE = LangString.of("Time.Min", GENERIC_AMOUNT + "min.");
|
||||
public static final LangString TIME_SECOND = LangString.of("Time.Sec", GENERIC_AMOUNT + "sec.");
|
||||
public static final LangString TIME_DELIMITER = LangString.of("Time.Delimiter", " ");
|
||||
|
||||
public static final LangString OTHER_YES = LangString.of("Other.Yes", GREEN.enclose("Yes"));
|
||||
public static final LangString OTHER_NO = LangString.of("Other.No", RED.enclose("No"));
|
||||
public static final LangString OTHER_ENABLED = LangString.of("Other.Enabled", GREEN.enclose("Enabled"));
|
||||
public static final LangString OTHER_DISABLED = LangString.of("Other.Disabled", RED.enclose("Disabled"));
|
||||
public static final LangString OTHER_ANY = LangString.of("Other.Any", "Any");
|
||||
public static final LangString OTHER_NONE = LangString.of("Other.None", "None");
|
||||
public static final LangString OTHER_NEVER = LangString.of("Other.Never", "Never");
|
||||
public static final LangString OTHER_ONE_TIMED = LangString.of("Other.OneTimed", "One-Timed");
|
||||
public static final LangString OTHER_UNLIMITED = LangString.of("Other.Unlimited", "Unlimited");
|
||||
public static final LangString OTHER_INFINITY = LangString.of("Other.Infinity", "∞");
|
||||
|
||||
public static final LangString ENTRY_GOOD = LangString.of("Entry.Good", GREEN.enclose("✔") + " " + GRAY.enclose(GENERIC_ENTRY));
|
||||
public static final LangString ENTRY_BAD = LangString.of("Entry.Bad", RED.enclose("✘") + " " + GRAY.enclose(GENERIC_ENTRY));
|
||||
public static final LangString ENTRY_WARN = LangString.of("Entry.Warn", ORANGE.enclose("[❗]") + " " + GRAY.enclose(GENERIC_ENTRY));
|
||||
|
||||
public static final LangText ERROR_INVALID_PLAYER = LangText.of("Error.Invalid_Player",
|
||||
RED.enclose("Invalid player!"));
|
||||
|
||||
public static final LangText ERROR_INVALID_WORLD = LangText.of("Error.Invalid_World",
|
||||
RED.enclose("Invalid world!"));
|
||||
|
||||
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!"));
|
||||
|
||||
/*public static final LangText ERROR_INVALID_POTION_EFFECT = LangText.of("Error.InvalidPotionEffectType",
|
||||
LIGHT_GRAY.enclose(LIGHT_RED.enclose(GENERIC_VALUE) + " is not a valid potion effect type!"));
|
||||
|
||||
public static final LangText ERROR_INVALID_ATTRIBUTE = LangText.of("Error.InvalidAttribute",
|
||||
LIGHT_GRAY.enclose(LIGHT_RED.enclose(GENERIC_VALUE) + " is not a valid attribute!"));*/
|
||||
|
||||
public static final LangText ERROR_NO_PERMISSION = LangText.of("Error.NoPermission",
|
||||
RED.enclose("You don't have permissions to do that!"));
|
||||
|
||||
public static final LangText ERROR_COMMAND_PARSE_FLAG = LangText.of("Error.Command.ParseFlag",
|
||||
LIGHT_GRAY.enclose("Invalid value " + LIGHT_RED.enclose(GENERIC_VALUE) + " for " + LIGHT_RED.enclose(GENERIC_NAME) + " flag."));
|
||||
|
||||
public static final LangText ERROR_COMMAND_PARSE_ARGUMENT = LangText.of("Error.Command.ParseArgument",
|
||||
LIGHT_GRAY.enclose("Invalid value " + LIGHT_RED.enclose(GENERIC_VALUE) + " for " + LIGHT_RED.enclose(GENERIC_NAME) + " argument."));
|
||||
|
||||
public static final LangText ERROR_COMMAND_INVALID_PLAYER_ARGUMENT = LangText.of("Error.Command.Argument.InvalidPlayer",
|
||||
LIGHT_GRAY.enclose(LIGHT_RED.enclose("Can not find player " + GENERIC_VALUE) + "!"));
|
||||
|
||||
public static final LangText ERROR_COMMAND_INVALID_WORLD_ARGUMENT = LangText.of("Error.Command.Argument.InvalidWorld",
|
||||
LIGHT_GRAY.enclose(LIGHT_RED.enclose("Can not find world " + GENERIC_VALUE) + "!"));
|
||||
|
||||
public static final LangText ERROR_COMMAND_INVALID_NUMBER_ARGUMENT = LangText.of("Error.Command.Argument.InvalidNumber",
|
||||
LIGHT_GRAY.enclose(LIGHT_RED.enclose(GENERIC_VALUE) + " is not a valid number!"));
|
||||
|
||||
public static final LangText ERROR_COMMAND_INVALID_MATERIAL_ARGUMENT = LangText.of("Error.Command.Argument.InvalidMaterial",
|
||||
LIGHT_GRAY.enclose(LIGHT_RED.enclose(GENERIC_VALUE) + " is not a valid material!"));
|
||||
|
||||
public static final LangText ERROR_COMMAND_INVALID_ENCHANTMENT_ARGUMENT = LangText.of("Error.Command.Argument.InvalidEnchantment",
|
||||
LIGHT_GRAY.enclose(LIGHT_RED.enclose(GENERIC_VALUE) + " is not a valid enchantment!"));
|
||||
|
||||
public static final LangText ERROR_COMMAND_NOT_YOURSELF = LangText.of("Error.Command.NotYourself",
|
||||
RED.enclose("This command can not be used on yourself."));
|
||||
|
||||
public static final LangText ERROR_COMMAND_PLAYER_ONLY = LangText.of("Error.Command.PlayerOnly",
|
||||
RED.enclose("This command is for players only."));
|
||||
|
||||
public static final LangText ERROR_COMMAND_USAGE = LangText.of("Error.Command.Usage",
|
||||
TAG_NO_PREFIX,
|
||||
" ",
|
||||
RED.enclose("Error: ") + GRAY.enclose("Wrong arguments!"),
|
||||
RED.enclose("Usage: ") + YELLOW.enclose("/" + COMMAND_LABEL) + " " + ORANGE.enclose(COMMAND_USAGE),
|
||||
" "
|
||||
);
|
||||
|
||||
@Deprecated
|
||||
public static final LangText EDITOR_ACTION_EXIT = LangText.of("Editor.Action.Exit",
|
||||
TAG_NO_PREFIX,
|
||||
"",
|
||||
GRAY.enclose("Click " +
|
||||
CLICK.enclose(
|
||||
HOVER.enclose(GREEN.enclose("[Here]"), HoverEventType.SHOW_TEXT, GRAY.enclose("Click to cancel")),
|
||||
ClickEventType.RUN_COMMAND, "/" + Dialog.EXIT
|
||||
)
|
||||
+ " to leave input mode."),
|
||||
"");
|
||||
|
||||
public static final LangString DIALOG_HEADER = LangString.of("Dialog.Header",
|
||||
LIGHT_YELLOW.enclose(GENERIC_TIME));
|
||||
|
||||
public static final LangString DIALOG_DEFAULT_PROMPT = LangString.of("Dialog.DefaultPrompt",
|
||||
LIGHT_GRAY.enclose("Enter " + LIGHT_GREEN.enclose("[Value]")));
|
||||
|
||||
public static final LangText DIALOG_INFO_EXIT = LangText.of("Dialog.Info.Exit",
|
||||
TAG_NO_PREFIX,
|
||||
"",
|
||||
GRAY.enclose("Click " +
|
||||
CLICK.wrapRunCommand(
|
||||
HOVER.wrapShowText(GREEN.enclose("[Here]"), GRAY.enclose("Click to cancel.")),
|
||||
"/" + DialogManager.EXIT
|
||||
)
|
||||
+ " to leave input mode."),
|
||||
"");
|
||||
|
||||
@Deprecated
|
||||
public static final LangString EDITOR_INPUT_HEADER_MAIN = LangString.of("Editor.Input.Header.Main", GREEN.enclose(BOLD.enclose("Input Mode")));
|
||||
@Deprecated
|
||||
public static final LangString EDITOR_INPUT_HEADER_ERROR = LangString.of("Editor.Input.Header.Error", RED.enclose(BOLD.enclose("ERROR")));
|
||||
@Deprecated
|
||||
public static final LangString EDITOR_INPUT_ERROR_NOT_INTEGER = LangString.of("Editor.Input.Error.NotInteger", GRAY.enclose("Expecting " + RED.enclose("whole") + " number!"));
|
||||
@Deprecated
|
||||
public static final LangString EDITOR_INPUT_ERROR_GENERIC = LangString.of("Editor.Input.Error.Generic", GRAY.enclose("Invalid value!"));
|
||||
|
||||
|
||||
public static final LangString EDITOR_BUTTON_NAME = LangString.of("Editor.Button.Name",
|
||||
LIGHT_YELLOW.enclose(BOLD.enclose(GENERIC_NAME))
|
||||
);
|
||||
|
||||
public static final LangString EDITOR_BUTTON_DESCRIPTION = LangString.of("Editor.Button.Description",
|
||||
GRAY.enclose(GENERIC_ENTRY)
|
||||
);
|
||||
|
||||
public static final LangString EDITOR_BUTTON_CURRENT_DEFAULT_NAME = LangString.of("Editor.Button.Current.DefaultName",
|
||||
"Current"
|
||||
);
|
||||
|
||||
public static final LangString EDITOR_BUTTON_CURRENT_INFO = LangString.of("Editor.Button.Current.Info",
|
||||
LIGHT_YELLOW.enclose("● " + LIGHT_GRAY.enclose(GENERIC_NAME + ": ") + GENERIC_VALUE)
|
||||
);
|
||||
|
||||
public static final LangString EDITOR_BUTTON_CLICK_KEY = LangString.of("Editor.Button.ClickKey",
|
||||
LIGHT_YELLOW.enclose("[▶]") + " " + LIGHT_GRAY.enclose(GENERIC_NAME + " to " + LIGHT_YELLOW.enclose(GENERIC_VALUE) + ".")
|
||||
);
|
||||
|
||||
|
||||
@Deprecated
|
||||
public static final LangItem EDITOR_ITEM_CLOSE = LangItem.of("Editor.Generic.Close", LIGHT_RED.enclose(BOLD.enclose("Exit")));
|
||||
@Deprecated
|
||||
public static final LangItem EDITOR_ITEM_RETURN = LangItem.of("Editor.Generic.Return", LIGHT_GRAY.enclose(BOLD.enclose("Return")));
|
||||
@Deprecated
|
||||
public static final LangItem EDITOR_ITEM_NEXT_PAGE = LangItem.of("Editor.Generic.NextPage", LIGHT_GRAY.enclose("Next Page →"));
|
||||
@Deprecated
|
||||
public static final LangItem EDITOR_ITEM_PREVIOUS_PAGE = LangItem.of("Editor.Generic.PreviousPage", LIGHT_GRAY.enclose("← Previous Page"));
|
||||
|
||||
public static final LangUIButton EDITOR_ITEM_EXIT = LangUIButton.builder("Editor.Item.Exit", LIGHT_RED.enclose(BOLD.enclose("Exit"))).build();
|
||||
public static final LangUIButton EDITOR_ITEM_BACK = LangUIButton.builder("Editor.Item.Return", LIGHT_GRAY.enclose(BOLD.enclose("Return"))).build();
|
||||
public static final LangUIButton EDITOR_ITEM_NEXT = LangUIButton.builder("Editor.Item.NextPage", LIGHT_GRAY.enclose(UNBOLD.enclose("Next Page →"))).build();
|
||||
public static final LangUIButton EDITOR_ITEM_PREVIOUS = LangUIButton.builder("Editor.Item.PreviousPage", LIGHT_GRAY.enclose(UNBOLD.enclose("← Previous Page"))).build();
|
||||
|
||||
@NotNull
|
||||
public static String getYesOrNo(boolean value) {
|
||||
return (value ? OTHER_YES : OTHER_NO).getString();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String getEnabledOrDisabled(boolean value) {
|
||||
return (value ? OTHER_ENABLED : OTHER_DISABLED).getString();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String goodEntry(@NotNull String str) {
|
||||
return ENTRY_GOOD.getString().replace(GENERIC_ENTRY, str);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String badEntry(@NotNull String str) {
|
||||
return ENTRY_BAD.getString().replace(GENERIC_ENTRY, str);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String warnEntry(@NotNull String str) {
|
||||
return ENTRY_WARN.getString().replace(GENERIC_ENTRY, str);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package su.nightexpress.nightcore.core;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.Engine;
|
||||
|
||||
@Deprecated
|
||||
public class CoreLogger {
|
||||
|
||||
public static void info(@NotNull String text) {
|
||||
Engine.core().info(text);
|
||||
}
|
||||
|
||||
public static void warn(@NotNull String text) {
|
||||
Engine.core().warn(text);
|
||||
}
|
||||
|
||||
public static void error(@NotNull String text) {
|
||||
Engine.core().error(text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package su.nightexpress.nightcore.core;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCore;
|
||||
import su.nightexpress.nightcore.core.listener.CoreListener;
|
||||
import su.nightexpress.nightcore.dialog.Dialog;
|
||||
import su.nightexpress.nightcore.dialog.DialogListener;
|
||||
import su.nightexpress.nightcore.manager.AbstractManager;
|
||||
import su.nightexpress.nightcore.menu.MenuListener;
|
||||
import su.nightexpress.nightcore.menu.impl.AbstractMenu;
|
||||
import su.nightexpress.nightcore.ui.UIListener;
|
||||
import su.nightexpress.nightcore.ui.dialog.DialogManager;
|
||||
import su.nightexpress.nightcore.ui.menu.Menu;
|
||||
import su.nightexpress.nightcore.ui.menu.MenuRegistry;
|
||||
import su.nightexpress.nightcore.ui.menu.MenuViewer;
|
||||
|
||||
import java.util.HashSet;
|
||||
|
||||
public class CoreManager extends AbstractManager<NightCore> {
|
||||
|
||||
public CoreManager(@NotNull NightCore plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLoad() {
|
||||
this.addListener(new CoreListener(this.plugin));
|
||||
this.addListener(new DialogListener(this.plugin));
|
||||
this.addListener(new MenuListener(this.plugin));
|
||||
this.addListener(new UIListener(this.plugin));
|
||||
|
||||
this.addTask(this::tickDialogs, 1);
|
||||
this.addTask(this::tickMenus, 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShutdown() {
|
||||
Dialog.shutdown();
|
||||
DialogManager.shutdown();
|
||||
}
|
||||
|
||||
private void tickDialogs() {
|
||||
Dialog.checkTimeOut();
|
||||
DialogManager.tickDialogs();
|
||||
}
|
||||
|
||||
private void tickMenus() {
|
||||
new HashSet<>(AbstractMenu.PLAYER_MENUS.values()).forEach(menu -> {
|
||||
if (menu.getOptions().isReadyToRefresh()) {
|
||||
menu.flush();
|
||||
menu.getOptions().setLastAutoRefresh(System.currentTimeMillis());
|
||||
}
|
||||
});
|
||||
|
||||
// if (menu.isReadyToRefresh()) {
|
||||
// menu.flush();
|
||||
// menu.setAutoRefreshIn(TimeUtil.createFutureTimestamp(menu.getAutoRefreshInterval()));
|
||||
// }
|
||||
MenuRegistry.getViewers().stream().map(MenuViewer::getMenu).distinct().forEach(Menu::tick);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package su.nightexpress.nightcore.core;
|
||||
|
||||
import su.nightexpress.nightcore.util.wrapper.UniPermission;
|
||||
|
||||
public class CorePerms {
|
||||
|
||||
public static final UniPermission COMMAND_RELOAD = new UniPermission("nightcore.command.reload");
|
||||
public static final UniPermission COMMAND_CHECK_PERM = new UniPermission("nightcore.command.checkperm");
|
||||
public static final UniPermission COMMAND_DUMP_ITEM = new UniPermission("nightcore.command.dumpitem");
|
||||
|
||||
@Deprecated
|
||||
public static final UniPermission COMMAND_FLAGS = new UniPermission("nightcore.command.flags");
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package su.nightexpress.nightcore.core.command;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
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.util.ItemNbt;
|
||||
import su.nightexpress.nightcore.util.ItemTag;
|
||||
import su.nightexpress.nightcore.util.Players;
|
||||
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.*;
|
||||
|
||||
public class CoreCommands {
|
||||
|
||||
private static final String CMD_CHECKPERM = "checkperm";
|
||||
|
||||
private static final String ARG_PLAYER = "player";
|
||||
|
||||
public static void load(@NotNull NightCore core) {
|
||||
ChainedNode root = core.getRootNode();
|
||||
|
||||
if (Plugins.hasPermissionsProvider()) {
|
||||
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(DirectNode.builder(core, "dumpitem")
|
||||
.playerOnly()
|
||||
.permission(CorePerms.COMMAND_DUMP_ITEM)
|
||||
.description(CoreLang.COMMAND_DUMPITEM_DESC)
|
||||
.executes(CoreCommands::dumpItem)
|
||||
);
|
||||
|
||||
root.addChildren(ReloadCommand.builder(core, CorePerms.COMMAND_RELOAD));
|
||||
}
|
||||
|
||||
private static boolean checkPermissions(@NotNull CommandContext context, @NotNull ParsedArguments arguments) {
|
||||
Player player = arguments.getPlayerArgument(ARG_PLAYER);
|
||||
String builder =
|
||||
BOLD.wrap(LIGHT_YELLOW.wrap("Permissions report for ") + LIGHT_ORANGE.wrap(player.getName() + ":")) +
|
||||
TAG_LINE_BREAK +
|
||||
LIGHT_ORANGE.wrap("▪ " + LIGHT_YELLOW.wrap("Primary Group: ") + Players.getPrimaryGroup(player)) +
|
||||
TAG_LINE_BREAK +
|
||||
LIGHT_ORANGE.wrap("▪ " + LIGHT_YELLOW.wrap("All Groups: ") + String.join(", ", Players.getInheritanceGroups(player))) +
|
||||
TAG_LINE_BREAK +
|
||||
LIGHT_ORANGE.wrap("▪ " + LIGHT_YELLOW.wrap("Prefix: ") + Players.getRawPrefix(player)) +
|
||||
TAG_LINE_BREAK +
|
||||
LIGHT_ORANGE.wrap("▪ " + LIGHT_YELLOW.wrap("Suffix: ") + Players.getRawSuffix(player));
|
||||
NightMessage.create(builder).send(context.getSender());
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean dumpItem(@NotNull CommandContext context, @NotNull ParsedArguments arguments) {
|
||||
Player player = context.getPlayerOrThrow();
|
||||
ItemStack itemStack = player.getInventory().getItemInMainHand();
|
||||
ItemTag tag = ItemNbt.getTag(itemStack);
|
||||
|
||||
player.sendMessage("=".repeat(10) + " DUMP ITEM " + "=".repeat(10));
|
||||
player.sendMessage(tag == null ? "null": tag.getTag());
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package su.nightexpress.nightcore.core.listener;
|
||||
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.server.ServiceRegisterEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCore;
|
||||
import su.nightexpress.nightcore.integration.VaultHook;
|
||||
import su.nightexpress.nightcore.manager.AbstractListener;
|
||||
import su.nightexpress.nightcore.util.Plugins;
|
||||
|
||||
public class CoreListener extends AbstractListener<NightCore> {
|
||||
|
||||
public CoreListener(@NotNull NightCore plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onServiceRegister(ServiceRegisterEvent event) {
|
||||
if (Plugins.hasVault()) {
|
||||
VaultHook.onServiceRegisterEvent(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.database.connection.MySQLConnector;
|
||||
import su.nightexpress.nightcore.database.connection.SQLiteConnector;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
@Deprecated
|
||||
public abstract class AbstractConnector {
|
||||
|
||||
protected final NightCorePlugin plugin;
|
||||
protected final HikariConfig config;
|
||||
protected final HikariDataSource dataSource;
|
||||
|
||||
public AbstractConnector(@NotNull NightCorePlugin 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 NightCorePlugin 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,211 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.database.serialize.ItemStackSerializer;
|
||||
import su.nightexpress.nightcore.database.sql.SQLColumn;
|
||||
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.executor.*;
|
||||
import su.nightexpress.nightcore.database.sql.query.UpdateEntity;
|
||||
import su.nightexpress.nightcore.database.sql.query.UpdateQuery;
|
||||
import su.nightexpress.nightcore.manager.AbstractManager;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
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;
|
||||
protected final AbstractConnector connector;
|
||||
protected final Gson gson;
|
||||
|
||||
public AbstractDataHandler(@NotNull P plugin) {
|
||||
this(plugin, getDataConfig(plugin));
|
||||
}
|
||||
|
||||
public AbstractDataHandler(@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 NightCorePlugin plugin) {
|
||||
DatabaseConfig dataConfig = plugin.getDetails().getDatabaseConfig();
|
||||
if (dataConfig == null) {
|
||||
plugin.warn("The plugin didn't have database configuration. Fixing it now...");
|
||||
dataConfig = DatabaseConfig.read(plugin);
|
||||
}
|
||||
return dataConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLoad() {
|
||||
if (this.config.getSaveInterval() > 0) {
|
||||
this.addTask(this.plugin.createAsyncTask(this::onSave).setSecondsInterval(this.config.getSaveInterval() * 60));
|
||||
}
|
||||
|
||||
if (this.config.getSyncInterval() > 0 && this.getDatabaseType() != DatabaseType.SQLITE) {
|
||||
this.addTask(this.plugin.createAsyncTask(this::onSynchronize).setSecondsInterval(this.config.getSyncInterval()));
|
||||
this.plugin.info("Enabled data synchronization with " + config.getSyncInterval() + " seconds interval.");
|
||||
}
|
||||
|
||||
if (this.config.isPurgeEnabled() && this.config.getPurgePeriod() > 0) {
|
||||
this.onPurge();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShutdown() {
|
||||
this.onSave();
|
||||
this.getConnector().close();
|
||||
}
|
||||
|
||||
public abstract void onSynchronize();
|
||||
|
||||
public abstract void onSave();
|
||||
|
||||
public abstract void onPurge();
|
||||
|
||||
@NotNull
|
||||
public DatabaseConfig getConfig() {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DatabaseType getDatabaseType() {
|
||||
return this.config.getStorageType();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getTablePrefix() {
|
||||
return this.config.getTablePrefix();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AbstractConnector getConnector() {
|
||||
return this.connector;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected GsonBuilder registerAdapters(@NotNull GsonBuilder builder) {
|
||||
return builder.registerTypeAdapter(ItemStack.class, new ItemStackSerializer());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected final Connection getConnection() throws SQLException {
|
||||
return this.getConnector().getConnection();
|
||||
}
|
||||
|
||||
public void createTable(@NotNull String table, @NotNull List<SQLColumn> columns) {
|
||||
CreateTableExecutor.builder(table, this.getDatabaseType()).columns(columns).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public void renameTable(@NotNull String from, @NotNull String to) {
|
||||
RenameTableExecutor.builder(from, this.getDatabaseType()).renameTo(to).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public void addColumn(@NotNull String table, @NotNull SQLValue... columns) {
|
||||
AlterTableExecutor.builder(table, this.getDatabaseType()).addColumn(columns).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public void renameColumn(@NotNull String table, @NotNull SQLValue... columns) {
|
||||
AlterTableExecutor.builder(table, this.getDatabaseType()).renameColumn(columns).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public void dropColumn(@NotNull String table, @NotNull SQLColumn... columns) {
|
||||
AlterTableExecutor.builder(table, this.getDatabaseType()).dropColumn(columns).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public boolean hasColumn(@NotNull String table, @NotNull SQLColumn column) {
|
||||
return SQLQueries.hasColumn(this.getConnector(), table, column);
|
||||
}
|
||||
|
||||
public void insert(@NotNull String table, @NotNull List<SQLValue> values) {
|
||||
InsertQueryExecutor.builder(table).values(values).execute(this.getConnector());
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@Deprecated
|
||||
public void update(@NotNull String table, @NotNull List<SQLValue> values, @NotNull SQLCondition... conditions) {
|
||||
UpdateQueryExecutor.builder(table).values(values).where(conditions).execute(this.getConnector());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UpdateEntity createUpdateEntity(@NotNull List<SQLValue> values, @NotNull List<SQLCondition> conditions) {
|
||||
return UpdateEntity.create(values, conditions);
|
||||
}
|
||||
|
||||
public void executeUpdate(@NotNull String table, @NotNull List<SQLValue> values, @NotNull List<SQLCondition> conditions) {
|
||||
this.executeUpdate(UpdateQuery.create(table, values, conditions));
|
||||
}
|
||||
|
||||
public void executeUpdate(@NotNull UpdateQuery query) {
|
||||
SQLQueries.executeUpdate(this.connector, query);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public void delete(@NotNull String table, @NotNull SQLCondition... conditions) {
|
||||
DeleteQueryExecutor.builder(table).where(conditions).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public boolean contains(@NotNull String table, @NotNull SQLCondition... conditions) {
|
||||
return this.load(table, (resultSet -> true), Collections.emptyList(), Arrays.asList(conditions)).isPresent();
|
||||
}
|
||||
|
||||
public boolean contains(@NotNull String table, @NotNull List<SQLColumn> columns, @NotNull SQLCondition... conditions) {
|
||||
return this.load(table, (resultSet -> true), columns, Arrays.asList(conditions)).isPresent();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> Optional<T> load(@NotNull String table, @NotNull Function<ResultSet, T> function,
|
||||
@NotNull List<SQLColumn> columns,
|
||||
@NotNull List<SQLCondition> conditions) {
|
||||
List<T> list = this.load(table, function, columns, conditions, 1);
|
||||
return list.isEmpty() ? Optional.empty() : Optional.of(list.get(0));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> List<T> load(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction) {
|
||||
return this.load(table, dataFunction, -1);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> List<T> load(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction, int amount) {
|
||||
return this.load(table, dataFunction, Collections.emptyList(), amount);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> List<T> load(@NotNull String table,
|
||||
@NotNull Function<ResultSet, T> dataFunction,
|
||||
@NotNull List<SQLColumn> columns,
|
||||
int amount) {
|
||||
return this.load(table, dataFunction, columns, Collections.emptyList(), amount);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> List<T> load(@NotNull String table,
|
||||
@NotNull Function<ResultSet, T> dataFunction,
|
||||
@NotNull List<SQLColumn> columns,
|
||||
@NotNull List<SQLCondition> conditions,
|
||||
int amount) {
|
||||
return SelectQueryExecutor.builder(table, dataFunction).columns(columns).where(conditions).execute(this.getConnector());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Deprecated
|
||||
public abstract class AbstractUser<P extends NightCorePlugin> implements DataUser {
|
||||
|
||||
protected final P plugin;
|
||||
protected final UUID uuid;
|
||||
|
||||
protected String name;
|
||||
protected long dateCreated;
|
||||
protected long lastOnline;
|
||||
protected long cachedUntil;
|
||||
protected long autoSaveIn;
|
||||
protected long nextSyncIn;
|
||||
|
||||
public AbstractUser(@NotNull P plugin, @NotNull UUID uuid, @NotNull String name, long dateCreated, long lastOnline) {
|
||||
this.plugin = plugin;
|
||||
this.uuid = uuid;
|
||||
this.name = name;
|
||||
this.setDateCreated(dateCreated);
|
||||
this.setLastOnline(lastOnline);
|
||||
this.setCachedUntil(-1);
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
|
||||
}
|
||||
|
||||
public void onUnload() {
|
||||
|
||||
}
|
||||
|
||||
private long getTimestamp(double seconds) {
|
||||
return seconds < 0 ? -1L : System.currentTimeMillis() + (long) (1000D * seconds);
|
||||
}
|
||||
|
||||
public boolean isCacheExpired() {
|
||||
return this.getCachedUntil() > 0 && System.currentTimeMillis() >= this.getCachedUntil();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAutoSaveReady() {
|
||||
return this.getAutoSaveIn() > 0 && System.currentTimeMillis() >= this.getAutoSaveIn();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSyncReady() {
|
||||
return this.getNextSyncIn() >= 0 && System.currentTimeMillis() >= this.getNextSyncIn();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelAutoSave() {
|
||||
this.setAutoSaveIn(-1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelSynchronization() {
|
||||
this.setNextSyncIn(-1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getCachedUntil() {
|
||||
return cachedUntil;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCachedUntil(long cachedUntil) {
|
||||
this.cachedUntil = cachedUntil;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getAutoSaveIn() {
|
||||
return autoSaveIn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAutoSaveIn(double seconds) {
|
||||
this.autoSaveIn = this.getTimestamp(seconds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getNextSyncIn() {
|
||||
return nextSyncIn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setNextSyncIn(int seconds) {
|
||||
this.nextSyncIn = this.getTimestamp(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 this.plugin.getServer().getOfflinePlayer(this.getId());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final Player getPlayer() {
|
||||
return this.plugin.getServer().getPlayer(this.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "AbstractUser [uuid=" + this.uuid + ", name=" + this.name + ", lastOnline=" + this.lastOnline + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightDataPlugin;
|
||||
import su.nightexpress.nightcore.database.sql.SQLColumn;
|
||||
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.database.sql.query.UpdateEntity;
|
||||
import su.nightexpress.nightcore.database.sql.query.UpdateQuery;
|
||||
import su.nightexpress.nightcore.util.Lists;
|
||||
import su.nightexpress.nightcore.util.TimeUtil;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
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);
|
||||
protected static final SQLColumn COLUMN_USER_NAME = SQLColumn.of("name", ColumnType.STRING);
|
||||
protected static final SQLColumn COLUMN_USER_DATE_CREATED = SQLColumn.of("dateCreated", ColumnType.LONG);
|
||||
protected static final SQLColumn COLUMN_USER_LAST_ONLINE = SQLColumn.of("last_online", ColumnType.LONG);
|
||||
|
||||
protected final String tableUsers;
|
||||
|
||||
protected final Set<UUID> existIDs;
|
||||
protected final Set<String> existNames;
|
||||
|
||||
public AbstractUserDataHandler(@NotNull P plugin) {
|
||||
this(plugin, getDataConfig(plugin));
|
||||
}
|
||||
|
||||
public AbstractUserDataHandler(@NotNull P plugin, @NotNull DatabaseConfig config) {
|
||||
super(plugin, config);
|
||||
this.tableUsers = this.getTablePrefix() + "_users";
|
||||
this.existIDs = new HashSet<>();
|
||||
this.existNames = new HashSet<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLoad() {
|
||||
super.onLoad();
|
||||
this.createUserTable();
|
||||
this.cacheNamesAndIds();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShutdown() {
|
||||
super.onShutdown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSave() {
|
||||
//this.saveUsers(this.plugin.getUserManager().getLoaded());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPurge() {
|
||||
if (!SQLQueries.hasTable(this.getConnector(), this.tableUsers)) return;
|
||||
|
||||
LocalDateTime deadline = LocalDateTime.now().minusDays(this.getConfig().getPurgePeriod());
|
||||
long deadlineMs = TimeUtil.toEpochMillis(deadline);
|
||||
|
||||
this.delete(this.tableUsers, SQLCondition.smaller(COLUMN_USER_LAST_ONLINE.toValue(deadlineMs)));
|
||||
}
|
||||
|
||||
protected void createUserTable() {
|
||||
List<SQLColumn> 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);
|
||||
columns.addAll(this.getExtraColumns());
|
||||
|
||||
this.createTable(this.tableUsers, columns);
|
||||
}
|
||||
|
||||
public boolean isNameIdCacheEnabled() {
|
||||
return false;//CoreConfig.USER_CACHE_NAME_AND_UUID.get() && this.getDatabaseType() == DatabaseType.SQLITE;
|
||||
}
|
||||
|
||||
public void cacheNamesAndIds() {
|
||||
if (!this.isNameIdCacheEnabled()) return;
|
||||
|
||||
Function<ResultSet, Void> function = resultSet -> {
|
||||
try {
|
||||
this.existIDs.add(UUID.fromString(resultSet.getString(COLUMN_USER_ID.getName())));
|
||||
this.existNames.add(resultSet.getString(COLUMN_USER_NAME.getName()).toLowerCase());
|
||||
}
|
||||
catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
this.load(this.tableUsers, function, Arrays.asList(COLUMN_USER_ID, COLUMN_USER_NAME), Collections.emptyList(), -1);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected abstract List<SQLColumn> getExtraColumns();
|
||||
|
||||
@NotNull
|
||||
protected List<SQLColumn> getReadColumns() {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected abstract List<SQLValue> getSaveColumns(@NotNull U user);
|
||||
|
||||
@NotNull
|
||||
protected abstract Function<ResultSet, U> getUserFunction();
|
||||
|
||||
@NotNull
|
||||
public List<U> getUsers() {
|
||||
return this.load(this.tableUsers, this.getUserFunction(), Collections.emptyList(), Collections.emptyList(), -1);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public U getUser(@NotNull Player player) {
|
||||
return this.getUser(player.getUniqueId());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final U getUser(@NotNull String name) {
|
||||
return this.load(this.tableUsers, this.getUserFunction(), this.getReadColumns(),
|
||||
Collections.singletonList(SQLCondition.equal(COLUMN_USER_NAME.asLowerCase().toValue(name.toLowerCase())))
|
||||
).orElse(null);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final U getUser(@NotNull UUID uuid) {
|
||||
return this.load(this.tableUsers, this.getUserFunction(), this.getReadColumns(),
|
||||
Collections.singletonList(SQLCondition.equal(COLUMN_USER_ID.toValue(uuid)))
|
||||
).orElse(null);
|
||||
}
|
||||
|
||||
public boolean isUserExists(@NotNull String name) {
|
||||
if (this.isNameIdCacheEnabled()) {
|
||||
return this.existNames.contains(name.toLowerCase());
|
||||
}
|
||||
return this.contains(this.tableUsers, Collections.singletonList(COLUMN_USER_NAME), SQLCondition.equal(COLUMN_USER_NAME.asLowerCase().toValue(name.toLowerCase())));
|
||||
}
|
||||
|
||||
public boolean isUserExists(@NotNull UUID uuid) {
|
||||
if (this.isNameIdCacheEnabled()) {
|
||||
return this.existIDs.contains(uuid);
|
||||
}
|
||||
return this.contains(this.tableUsers, Collections.singletonList(COLUMN_USER_ID), SQLCondition.equal(COLUMN_USER_ID.toValue(uuid)));
|
||||
}
|
||||
|
||||
public void saveUser(@NotNull U user) {
|
||||
this.executeUpdate(UpdateQuery.create(this.tableUsers, this.createUpdateEntity(user)));
|
||||
}
|
||||
|
||||
public void saveUsers(@NotNull Collection<U> users) {
|
||||
this.executeUpdate(UpdateQuery.create(this.tableUsers, users.stream().map(this::createUpdateEntity).toList()));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UpdateEntity createUpdateEntity(@NotNull U user) {
|
||||
List<SQLValue> values = new ArrayList<>();
|
||||
values.add(COLUMN_USER_NAME.toValue(user.getName()));
|
||||
values.add(COLUMN_USER_DATE_CREATED.toValue(user.getDateCreated()));
|
||||
values.add(COLUMN_USER_LAST_ONLINE.toValue(user.getLastOnline()));
|
||||
values.addAll(this.getSaveColumns(user));
|
||||
|
||||
List<SQLCondition> conditions = Lists.newList(
|
||||
SQLCondition.equal(COLUMN_USER_ID.toValue(user.getId()))
|
||||
);
|
||||
|
||||
return this.createUpdateEntity(values, conditions);
|
||||
}
|
||||
|
||||
public void addUser(@NotNull U user) {
|
||||
List<SQLValue> values = new ArrayList<>();
|
||||
values.add(COLUMN_USER_ID.toValue(user.getId()));
|
||||
values.add(COLUMN_USER_NAME.toValue(user.getName()));
|
||||
values.add(COLUMN_USER_DATE_CREATED.toValue(user.getDateCreated()));
|
||||
values.add(COLUMN_USER_LAST_ONLINE.toValue(user.getLastOnline()));
|
||||
values.addAll(this.getSaveColumns(user));
|
||||
|
||||
this.insert(this.tableUsers, values);
|
||||
|
||||
this.existIDs.add(user.getId());
|
||||
this.existNames.add(user.getName());
|
||||
}
|
||||
|
||||
public void deleteUser(@NotNull UUID uuid) {
|
||||
this.delete(this.tableUsers, SQLCondition.equal(COLUMN_USER_ID.toValue(uuid)));
|
||||
|
||||
this.existIDs.clear();
|
||||
this.existNames.clear();
|
||||
this.cacheNamesAndIds();
|
||||
}
|
||||
|
||||
public void deleteUser(@NotNull DataUser user) {
|
||||
this.delete(this.tableUsers, SQLCondition.equal(COLUMN_USER_ID.toValue(user.getId())));
|
||||
|
||||
this.existIDs.remove(user.getId());
|
||||
this.existNames.remove(user.getName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightDataPlugin;
|
||||
import su.nightexpress.nightcore.manager.AbstractManager;
|
||||
import su.nightexpress.nightcore.core.CoreConfig;
|
||||
import su.nightexpress.nightcore.database.listener.UserListener;
|
||||
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;
|
||||
|
||||
@Deprecated
|
||||
public abstract class AbstractUserManager<P extends NightDataPlugin<U>, U extends DataUser> extends AbstractManager<P> {
|
||||
|
||||
private final UserdataConfig config;
|
||||
|
||||
private final Map<UUID, U> loadedById;
|
||||
private final Map<String, U> loadedByName;
|
||||
private final Map<UUID, U> scheduledSaves;
|
||||
|
||||
public AbstractUserManager(@NotNull P plugin) {
|
||||
super(plugin);
|
||||
this.config = UserdataConfig.read(plugin);
|
||||
this.loadedById = new ConcurrentHashMap<>();
|
||||
this.loadedByName = new ConcurrentHashMap<>();
|
||||
this.scheduledSaves = new ConcurrentHashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLoad() {
|
||||
this.addListener(new UserListener<>(this.plugin));
|
||||
this.addTask(this.plugin.createAsyncTask(this::saveScheduled).setTicksInterval(this.config.getSaveInterval()));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShutdown() {
|
||||
this.saveAll();
|
||||
this.getLoadedByIdMap().clear();
|
||||
this.getLoadedByNameMap().clear();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private AbstractUserDataHandler<?, U> getDataHandler() {
|
||||
return this.plugin.getData();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public abstract U createUserData(@NotNull UUID uuid, @NotNull String name);
|
||||
|
||||
public void loadOnlineUsers() {
|
||||
this.plugin.getServer().getOnlinePlayers().stream().map(Player::getUniqueId).forEach(id -> {
|
||||
U user = this.getUserData(id);
|
||||
if (user != null) this.cachePermanent(user);
|
||||
});
|
||||
}
|
||||
|
||||
public void saveScheduled() {
|
||||
if (this.scheduledSaves.isEmpty()) return;
|
||||
|
||||
Set<U> users = new HashSet<>();
|
||||
|
||||
this.scheduledSaves.values().forEach(user -> {
|
||||
if (user.isAutoSaveReady()) {
|
||||
users.add(user);
|
||||
}
|
||||
});
|
||||
|
||||
this.getDataHandler().saveUsers(users);
|
||||
|
||||
users.forEach(user -> {
|
||||
user.cancelAutoSave(); // Reset autosave timestamp.
|
||||
user.setNextSyncIn(this.config.getSaveSyncPause()); // Unlock synchronization only when all data was pushed to the database.
|
||||
});
|
||||
|
||||
this.scheduledSaves.values().removeAll(users);
|
||||
}
|
||||
|
||||
public void saveAll() {
|
||||
Set<U> users = new HashSet<>();
|
||||
users.addAll(this.scheduledSaves.values());
|
||||
users.addAll(this.getLoaded());
|
||||
this.getDataHandler().saveUsers(users);
|
||||
this.scheduledSaves.values().forEach(DataUser::cancelAutoSave);
|
||||
this.scheduledSaves.clear();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final U getUserData(@NotNull Player player) {
|
||||
UUID uuid = player.getUniqueId();
|
||||
|
||||
U user = this.getLoaded(uuid);
|
||||
if (user != null) return user;
|
||||
|
||||
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() + "'.");
|
||||
// }
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
return this.createUserData(uuid, player.getName());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final U getUserData(@NotNull String name) {
|
||||
Player player = Players.getPlayer(name);
|
||||
if (player != null) return this.getUserData(player);
|
||||
|
||||
U user = this.getLoaded(name);
|
||||
if (user != null) return user;
|
||||
|
||||
user = this.plugin.getData().getUser(name);
|
||||
if (user != null) {
|
||||
user.onLoad();
|
||||
//this.plugin.debug("Loaded by name from DB: " + user.getName());
|
||||
this.cacheTemporary(user);
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final U getUserData(@NotNull UUID uuid) {
|
||||
U user = this.getLoaded(uuid);
|
||||
if (user != null) return user;
|
||||
|
||||
user = this.plugin.getData().getUser(uuid);
|
||||
if (user != null) {
|
||||
user.onLoad();
|
||||
//this.plugin.debug("Loaded by UUID from DB: " + user.getName());
|
||||
this.cacheTemporary(user);
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
public final CompletableFuture<U> getUserDataAsync(@NotNull String name) {
|
||||
return CompletableFuture.supplyAsync(() -> this.getUserData(name));
|
||||
}
|
||||
|
||||
public final CompletableFuture<U> getUserDataAsync(@NotNull UUID uuid) {
|
||||
return CompletableFuture.supplyAsync(() -> this.getUserData(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)));
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void getUserDataAndPerform(@NotNull String name, Consumer<U> consumer) {
|
||||
this.manageUserSynchronized(name, consumer);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void getUserDataAndPerform(@NotNull UUID uuid, Consumer<U> consumer) {
|
||||
this.manageUserSynchronized(uuid, consumer);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void getUserDataAndPerformAsync(@NotNull String name, Consumer<U> consumer) {
|
||||
this.manageUser(name, consumer);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void getUserDataAndPerformAsync(@NotNull UUID uuid, Consumer<U> consumer) {
|
||||
this.manageUser(uuid, consumer);
|
||||
}
|
||||
|
||||
public final void unload(@NotNull Player player) {
|
||||
this.unload(player.getUniqueId());
|
||||
}
|
||||
|
||||
public final void unload(@NotNull UUID uuid) {
|
||||
U user = this.getLoadedByIdMap().get(uuid);
|
||||
if (user == null) return;
|
||||
|
||||
this.unload(user);
|
||||
}
|
||||
|
||||
public void unload(@NotNull U user) {
|
||||
Player player = user.getPlayer();
|
||||
if (player != null) {
|
||||
user.setName(player.getName());
|
||||
user.setLastOnline(System.currentTimeMillis());
|
||||
}
|
||||
if (this.isScheduledToSave(user)) {
|
||||
this.scheduledSaves.remove(user.getId());
|
||||
}
|
||||
this.plugin.runTaskAsync(task -> this.save(user));
|
||||
//this.scheduleSave(user);
|
||||
this.cacheTemporary(user);
|
||||
}
|
||||
|
||||
public void save(@NotNull U user) {
|
||||
this.plugin.getData().saveUser(user);
|
||||
}
|
||||
|
||||
public void scheduleSave(@NotNull U user) {
|
||||
user.setAutoSaveIn(this.config.getSaveDelay());
|
||||
user.cancelSynchronization();
|
||||
this.scheduledSaves.put(user.getId(), user);
|
||||
}
|
||||
|
||||
public boolean isScheduledToSave(@NotNull U user) {
|
||||
return this.scheduledSaves.containsKey(user.getId());
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void saveAsync(@NotNull U user) {
|
||||
this.scheduleSave(user);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<U> getAllUsers() {
|
||||
Map<UUID, U> users = new HashMap<>();
|
||||
this.getLoaded().forEach(user -> users.put(user.getId(), user));
|
||||
this.plugin.getData().getUsers().forEach(user -> {
|
||||
users.putIfAbsent(user.getId(), user);
|
||||
});
|
||||
return new HashSet<>(users.values());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<UUID, U> getLoadedByIdMap() {
|
||||
this.removeExpired(this.loadedById.values());
|
||||
|
||||
return this.loadedById;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<String, U> getLoadedByNameMap() {
|
||||
this.removeExpired(this.loadedByName.values());
|
||||
|
||||
return loadedByName;
|
||||
}
|
||||
|
||||
private void removeExpired(@NotNull Collection<U> collection) {
|
||||
collection.removeIf(user -> {
|
||||
if (user.isCacheExpired()) {
|
||||
user.onUnload();
|
||||
//this.plugin.debug("Cache expired: " + user.getName());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<U> getLoaded() {
|
||||
return new HashSet<>(this.getLoadedByIdMap().values());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public U getLoaded(@NotNull UUID uuid) {
|
||||
return this.getLoadedByIdMap().get(uuid);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public U getLoaded(@NotNull String name) {
|
||||
return this.getLoadedByNameMap().get(name.toLowerCase());
|
||||
}
|
||||
|
||||
public boolean isLoaded(@NotNull Player player) {
|
||||
return this.isLoaded(player.getUniqueId());
|
||||
}
|
||||
|
||||
public boolean isLoaded(@NotNull UUID id) {
|
||||
return this.getLoadedByIdMap().containsKey(id);
|
||||
}
|
||||
|
||||
public boolean isLoaded(@NotNull String name) {
|
||||
return this.getLoadedByNameMap().containsKey(name.toLowerCase());
|
||||
}
|
||||
|
||||
public boolean isCreated(@NotNull String name) {
|
||||
return this.plugin.getData().isUserExists(name);
|
||||
}
|
||||
|
||||
public boolean isCreated(@NotNull UUID uuid) {
|
||||
return this.plugin.getData().isUserExists(uuid);
|
||||
}
|
||||
|
||||
public void cacheTemporary(@NotNull U user) {
|
||||
user.setCachedUntil(System.currentTimeMillis() + CoreConfig.USER_CACHE_LIFETIME.get() * 1000L);
|
||||
this.cache(user);
|
||||
//this.plugin.debug("Temp user cache: " + user.getName());
|
||||
}
|
||||
|
||||
public void cachePermanent(@NotNull U user) {
|
||||
user.setCachedUntil(-1);
|
||||
this.cache(user);
|
||||
//this.plugin.debug("Permanent user cache: " + user.getName());
|
||||
}
|
||||
|
||||
private void cache(@NotNull U user) {
|
||||
this.getLoadedByIdMap().putIfAbsent(user.getId(), user);
|
||||
this.getLoadedByNameMap().putIfAbsent(user.getName().toLowerCase(), user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Deprecated
|
||||
public interface DataUser {
|
||||
|
||||
void onLoad();
|
||||
|
||||
void onUnload();
|
||||
|
||||
boolean isCacheExpired();
|
||||
|
||||
boolean isAutoSaveReady();
|
||||
|
||||
boolean isSyncReady();
|
||||
|
||||
long getCachedUntil();
|
||||
|
||||
long getAutoSaveIn();
|
||||
|
||||
long getNextSyncIn();
|
||||
|
||||
void cancelAutoSave();
|
||||
|
||||
void cancelSynchronization();
|
||||
|
||||
void setCachedUntil(long cachedUntil);
|
||||
|
||||
void setAutoSaveIn(double seconds);
|
||||
|
||||
void setNextSyncIn(int seconds);
|
||||
|
||||
@NotNull UUID getId();
|
||||
|
||||
@NotNull String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
long getDateCreated();
|
||||
|
||||
void setDateCreated(long dateCreated);
|
||||
|
||||
long getLastOnline();
|
||||
|
||||
void setLastOnline(long lastOnline);
|
||||
|
||||
boolean isOnline();
|
||||
|
||||
@NotNull OfflinePlayer getOfflinePlayer();
|
||||
|
||||
@Nullable Player getPlayer();
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.config.ConfigValue;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.util.StringUtil;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Deprecated
|
||||
public class DatabaseConfig {
|
||||
|
||||
@Deprecated private final int saveInterval;
|
||||
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 saveInterval,
|
||||
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.saveInterval = saveInterval;
|
||||
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 NightCorePlugin 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 saveInterval = ConfigValue.create(path + "Auto_Save_Interval", 20,
|
||||
"Sets how often (in minutes) plugin data of online players will be saved to the database.",
|
||||
"Set to '-1' to disable.")
|
||||
.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(
|
||||
saveInterval, syncInterval,
|
||||
databaseType, tablePrefix,
|
||||
purgeEnabled, purgePeriod,
|
||||
|
||||
mysqlUser, mysqlPassword, mysqlHost, mysqlBase, urlOptions,
|
||||
|
||||
sqliteFilename
|
||||
);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DatabaseType getStorageType() {
|
||||
return databaseType;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getTablePrefix() {
|
||||
return tablePrefix;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public int getSaveInterval() {
|
||||
return saveInterval;
|
||||
}
|
||||
|
||||
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,8 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
@Deprecated
|
||||
public enum DatabaseType {
|
||||
|
||||
MYSQL,
|
||||
SQLITE,
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightPlugin;
|
||||
import su.nightexpress.nightcore.config.ConfigValue;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
|
||||
@Deprecated
|
||||
public class UserdataConfig {
|
||||
|
||||
private final long cacheLifetime;
|
||||
|
||||
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 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').",
|
||||
"[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, saveInterval, saveDelay, saveSyncPause);
|
||||
}
|
||||
|
||||
public long getCacheLifetime() {
|
||||
return this.cacheLifetime;
|
||||
}
|
||||
|
||||
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,31 @@
|
||||
package su.nightexpress.nightcore.database.connection;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
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) {
|
||||
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());
|
||||
if (!config.getPassword().isBlank()) {
|
||||
this.config.setPassword(config.getPassword());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package su.nightexpress.nightcore.database.connection;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
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) {
|
||||
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,49 @@
|
||||
package su.nightexpress.nightcore.database.listener;
|
||||
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
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.database.AbstractUserManager;
|
||||
import su.nightexpress.nightcore.database.DataUser;
|
||||
import su.nightexpress.nightcore.manager.AbstractListener;
|
||||
|
||||
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;
|
||||
|
||||
public UserListener(@NotNull P plugin) {
|
||||
super(plugin);
|
||||
this.userManager = plugin.getUserManager();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onUserLogin(AsyncPlayerPreLoginEvent event) {
|
||||
if (event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) return;
|
||||
|
||||
UUID uuid = event.getUniqueId();
|
||||
U user;
|
||||
if (!this.userManager.isCreated(uuid)) {
|
||||
user = this.userManager.createUserData(uuid, event.getName());
|
||||
plugin.getData().addUser(user);
|
||||
//if (CoreConfig.USER_DEBUG_ENABLED.get()) {
|
||||
plugin.info("Created new data for: '" + uuid + "'");
|
||||
//}
|
||||
}
|
||||
else user = this.userManager.getUserData(uuid);
|
||||
|
||||
if (user != null) {
|
||||
this.userManager.cachePermanent(user);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onUserQuit(PlayerQuitEvent event) {
|
||||
this.userManager.unload(event.getPlayer());
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package su.nightexpress.nightcore.database.serialize;
|
||||
|
||||
import com.google.gson.*;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import su.nightexpress.nightcore.util.ItemNbt;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
@Deprecated
|
||||
public class ItemStackSerializer implements JsonSerializer<ItemStack>, JsonDeserializer<ItemStack> {
|
||||
|
||||
@Override
|
||||
public JsonElement serialize(ItemStack item, Type type, JsonSerializationContext context) {
|
||||
JsonObject object = new JsonObject();
|
||||
object.addProperty("data64", ItemNbt.compress(item));
|
||||
return object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
|
||||
JsonObject object = json.getAsJsonObject();
|
||||
return ItemNbt.decompress(object.get("data64").getAsString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package su.nightexpress.nightcore.database.sql;
|
||||
|
||||
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;
|
||||
private final String nameEscaped;
|
||||
private final ColumnType type;
|
||||
private final int length;
|
||||
|
||||
public SQLColumn(@NotNull String name, @NotNull ColumnType type, int length) {
|
||||
this(name, "`" + name + "`", type, length);
|
||||
}
|
||||
|
||||
public SQLColumn(@NotNull String name, @NotNull String nameEscaped, @NotNull ColumnType type, int length) {
|
||||
this.name = name;
|
||||
this.nameEscaped = nameEscaped;
|
||||
this.type = type;
|
||||
this.length = length;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLColumn of(@NotNull String name, @NotNull ColumnType type) {
|
||||
return SQLColumn.of(name, type, -1);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLColumn of(@NotNull String name, @NotNull ColumnType type, int length) {
|
||||
return new SQLColumn(name, type, length);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public SQLColumn asLowerCase() {
|
||||
String name = "LOWER(" + this.getName() + ")";
|
||||
|
||||
return new SQLColumn(name, name, this.getType(), this.getLength());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getNameEscaped() {
|
||||
return this.nameEscaped;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getNameLowercase() {
|
||||
return "LOWER(" + this.getName() + ")";
|
||||
}
|
||||
|
||||
|
||||
@NotNull
|
||||
public ColumnType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public int getLength() {
|
||||
return length;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String formatType(@NotNull DatabaseType databaseType) {
|
||||
return this.getType().getFormer().build(databaseType, this.getLength());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SQLValue toValue(@NotNull Object value) {
|
||||
return SQLValue.of(this, String.valueOf(value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package su.nightexpress.nightcore.database.sql;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
@Deprecated
|
||||
public class SQLCondition {
|
||||
|
||||
private final SQLValue value;
|
||||
private final Type type;
|
||||
|
||||
public SQLCondition(@NotNull SQLValue value, @NotNull Type type) {
|
||||
this.value = value;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLCondition of(@NotNull SQLValue value, @NotNull Type type) {
|
||||
return new SQLCondition(value, type);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLCondition equal(@NotNull SQLValue value) {
|
||||
return of(value, Type.EQUAL);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLCondition not(@NotNull SQLValue value) {
|
||||
return of(value, Type.NOT_EQUAL);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLCondition smaller(@NotNull SQLValue value) {
|
||||
return of(value, Type.SMALLER);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLCondition greater(@NotNull SQLValue value) {
|
||||
return of(value, Type.GREATER);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SQLValue getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SQLColumn getColumn() {
|
||||
return this.getValue().getColumn();
|
||||
}
|
||||
|
||||
public enum Type {
|
||||
GREATER(">"),
|
||||
SMALLER("<"),
|
||||
EQUAL("="),
|
||||
NOT_EQUAL("!=");
|
||||
|
||||
private final String operator;
|
||||
|
||||
Type(@NotNull String operator) {
|
||||
this.operator = operator;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getOperator() {
|
||||
return operator;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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;
|
||||
|
||||
protected SQLExecutor(@NotNull String table) {
|
||||
this.table = table;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getTable() {
|
||||
return "`" + this.table + "`";
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public abstract T execute(@NotNull AbstractConnector connector);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package su.nightexpress.nightcore.database.sql;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.query.UpdateEntity;
|
||||
import su.nightexpress.nightcore.database.sql.query.UpdateQuery;
|
||||
|
||||
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) {
|
||||
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 SQLColumn column) {
|
||||
String sql = "SELECT * FROM " + table;
|
||||
String columnName = column.getName();
|
||||
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 executeStatement(@NotNull AbstractConnector connector,
|
||||
@NotNull String sql) {
|
||||
executeStatement(connector, sql, Collections.emptySet());
|
||||
}
|
||||
|
||||
public static void executeStatement(@NotNull AbstractConnector connector,
|
||||
@NotNull String sql,
|
||||
@NotNull Collection<String> values1) {
|
||||
executeStatement(connector, sql, values1, Collections.emptySet());
|
||||
}
|
||||
|
||||
public static void executeStatement(@NotNull AbstractConnector connector,
|
||||
@NotNull String sql,
|
||||
@NotNull Collection<String> values1,
|
||||
@NotNull Collection<String> values2) {
|
||||
|
||||
try (Connection connection = connector.getConnection();
|
||||
PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
|
||||
int count = 1;
|
||||
for (String columnName : values1) {
|
||||
statement.setString(count++, columnName);
|
||||
}
|
||||
for (String columnValue : values2) {
|
||||
statement.setString(count++, columnValue);
|
||||
}
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void executeUpdate(@NotNull AbstractConnector connector, @NotNull UpdateQuery query) {
|
||||
executeUpdates(connector, query);
|
||||
}
|
||||
|
||||
public static void executeUpdates(@NotNull AbstractConnector connector, @NotNull UpdateQuery query) {
|
||||
if (query.isEmpty()) return;
|
||||
|
||||
List<UpdateEntity> entities = query.getEntities();
|
||||
//if (entities.isEmpty()) return;
|
||||
|
||||
//if (queries.isEmpty()) return;
|
||||
|
||||
// try (Connection connection = connector.getConnection()) {
|
||||
// for (UpdateQuery query : queries) {
|
||||
// try (PreparedStatement statement = connection.prepareStatement(query.getSQL())) {
|
||||
//
|
||||
// int count = 1;
|
||||
// for (String columnValue : query.getValues()) {
|
||||
// statement.setString(count++, columnValue);
|
||||
// }
|
||||
// for (String conditionValue : query.getWheres()) {
|
||||
// statement.setString(count++, conditionValue);
|
||||
// }
|
||||
//
|
||||
// statement.executeUpdate();
|
||||
// }
|
||||
// catch (SQLException exception) {
|
||||
// exception.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// catch (SQLException exception) {
|
||||
// exception.printStackTrace();
|
||||
// }
|
||||
|
||||
String sql = query.getSQL();//queries.get(0).getSQL();
|
||||
|
||||
try (Connection connection = connector.getConnection();
|
||||
PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
|
||||
int entityCount = 0;
|
||||
for (UpdateEntity entity : entities) {
|
||||
int paramCount = 1;
|
||||
|
||||
for (String columnValue : entity.getValues()) {
|
||||
statement.setString(paramCount++, columnValue);
|
||||
}
|
||||
for (String conditionValue : entity.getWheres()) {
|
||||
statement.setString(paramCount++, conditionValue);
|
||||
}
|
||||
statement.addBatch();
|
||||
entityCount++;
|
||||
|
||||
if (entityCount % 500 == 0 || entityCount == entities.size()) {
|
||||
statement.executeBatch();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> List<@NotNull T> executeQuery(@NotNull AbstractConnector connector,
|
||||
@NotNull String sql,
|
||||
@NotNull Collection<String> values,
|
||||
@NotNull Function<ResultSet, T> dataFunction,
|
||||
int amount) {
|
||||
|
||||
List<T> list = new ArrayList<>();
|
||||
try (Connection connection = connector.getConnection();
|
||||
PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
|
||||
int count = 1;
|
||||
for (String wValue : values) {
|
||||
statement.setString(count++, wValue);
|
||||
}
|
||||
|
||||
ResultSet resultSet = statement.executeQuery();
|
||||
while (resultSet.next() && (amount < 0 || list.size() < amount)) {
|
||||
list.add(dataFunction.apply(resultSet));
|
||||
}
|
||||
resultSet.close();
|
||||
}
|
||||
catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
list.removeIf(Objects::isNull);
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package su.nightexpress.nightcore.database.sql;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.db.sql.util.WhereOperator;
|
||||
|
||||
@Deprecated
|
||||
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 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() + " ?";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package su.nightexpress.nightcore.database.sql;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
@Deprecated
|
||||
public class SQLValue {
|
||||
|
||||
private final SQLColumn column;
|
||||
private final String value;
|
||||
|
||||
public SQLValue(@NotNull SQLColumn column, @NotNull String value) {
|
||||
this.column = column;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLValue of(@NotNull SQLColumn column, @NotNull String value) {
|
||||
return new SQLValue(column, value);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SQLColumn getColumn() {
|
||||
return column;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
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) -> {
|
||||
if (length < 1 || storageType == DatabaseType.SQLITE) {
|
||||
return storageType == DatabaseType.SQLITE ? "TEXT NOT NULL" : "MEDIUMTEXT NOT NULL";
|
||||
}
|
||||
return "varchar(" + length + ") CHARACTER SET utf8 NOT NULL";
|
||||
};
|
||||
|
||||
ColumnFormer INTEGER = (storageType, length) -> {
|
||||
if (length < 1 || storageType == DatabaseType.SQLITE) {
|
||||
return "INTEGER NOT NULL";
|
||||
}
|
||||
return "int(" + length + ") NOT NULL";
|
||||
};
|
||||
|
||||
ColumnFormer DOUBLE = (storageType, length) -> {
|
||||
return storageType == DatabaseType.SQLITE ? "REAL NOT NULL" : "double NOT NULL";
|
||||
};
|
||||
|
||||
ColumnFormer LONG = (storageType, length) -> {
|
||||
return length < 1 || storageType == DatabaseType.SQLITE ? "BIGINT NOT NULL" : "bigint(" + length + ") NOT NULL";
|
||||
};
|
||||
|
||||
ColumnFormer BOOLEAN = (storageType, length) -> {
|
||||
return storageType == DatabaseType.SQLITE ? "INTEGER NOT NULL" : "tinyint(1) NOT NULL";
|
||||
};
|
||||
|
||||
@NotNull String build(@NotNull DatabaseType databaseType, int length);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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);
|
||||
public static final ColumnType DOUBLE = new ColumnType(ColumnFormer.DOUBLE);
|
||||
public static final ColumnType LONG = new ColumnType(ColumnFormer.LONG);
|
||||
public static final ColumnType BOOLEAN = new ColumnType(ColumnFormer.BOOLEAN);
|
||||
public static final ColumnType STRING = new ColumnType(ColumnFormer.STRING);
|
||||
|
||||
private final ColumnFormer former;
|
||||
|
||||
public ColumnType(@NotNull ColumnFormer former) {
|
||||
this.former = former;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ColumnFormer getFormer() {
|
||||
return former;
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.DatabaseType;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.connection.SQLiteConnector;
|
||||
import su.nightexpress.nightcore.database.sql.SQLColumn;
|
||||
import su.nightexpress.nightcore.database.sql.SQLExecutor;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
import su.nightexpress.nightcore.database.sql.column.ColumnType;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Deprecated
|
||||
public final class AlterTableExecutor extends SQLExecutor<Void> {
|
||||
|
||||
private final DatabaseType databaseType;
|
||||
private final List<SQLValue> columns;
|
||||
private Type type;
|
||||
|
||||
private AlterTableExecutor(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
super(table);
|
||||
this.databaseType = databaseType;
|
||||
this.columns = new ArrayList<>();
|
||||
}
|
||||
|
||||
private enum Type {
|
||||
ADD_COLUMN, RENAME_COLUMN, DROP_COLUMN
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static AlterTableExecutor builder(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
return new AlterTableExecutor(table, databaseType);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor addColumn(@NotNull SQLValue... columns) {
|
||||
return this.addColumn(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor addColumn(@NotNull List<SQLValue> columns) {
|
||||
return this.columns(columns, Type.ADD_COLUMN);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor renameColumn(@NotNull SQLValue... columns) {
|
||||
return this.addColumn(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor renameColumn(@NotNull List<SQLValue> columns) {
|
||||
return this.columns(columns, Type.RENAME_COLUMN);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor dropColumn(@NotNull SQLColumn... columns) {
|
||||
return this.dropColumn(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor dropColumn(@NotNull List<SQLColumn> columns) {
|
||||
return this.columns(columns.stream().map(column -> column.toValue("dummy")).toList(), Type.DROP_COLUMN);
|
||||
}
|
||||
|
||||
private AlterTableExecutor columns(@NotNull List<SQLValue> values, @NotNull Type type) {
|
||||
this.columns.clear();
|
||||
this.columns.addAll(values);
|
||||
this.type = type;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
if (this.columns.isEmpty()) return null;
|
||||
|
||||
if (this.type == Type.ADD_COLUMN) {
|
||||
this.columns.forEach(value -> {
|
||||
if (SQLQueries.hasColumn(connector, this.getTable(), value.getColumn())) return;
|
||||
|
||||
String sql = "ALTER TABLE " + this.getTable() + " ADD "
|
||||
+ value.getColumn().getName() + " " + value.getColumn().formatType(this.databaseType);
|
||||
|
||||
if (connector instanceof SQLiteConnector || value.getColumn().getType() != ColumnType.STRING) {
|
||||
sql = sql + " DEFAULT '" + value.getValue() + "'";
|
||||
}
|
||||
|
||||
SQLQueries.executeStatement(connector, sql);
|
||||
});
|
||||
}
|
||||
else if (this.type == Type.RENAME_COLUMN) {
|
||||
this.columns.forEach(value -> {
|
||||
if (!SQLQueries.hasColumn(connector, this.getTable(), value.getColumn())) return;
|
||||
|
||||
String sql = "ALTER TABLE " + this.getTable() + " RENAME COLUMN " + value.getColumn().getName() + " TO " + value.getValue();
|
||||
SQLQueries.executeStatement(connector, sql);
|
||||
});
|
||||
}
|
||||
else if (this.type == Type.DROP_COLUMN) {
|
||||
this.columns.forEach(value -> {
|
||||
if (!SQLQueries.hasColumn(connector, this.getTable(), value.getColumn())) return;
|
||||
|
||||
String sql = "ALTER TABLE " + this.getTable() + " DROP COLUMN " + value.getColumn().getName();
|
||||
SQLQueries.executeStatement(connector, sql);
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.DatabaseType;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.SQLColumn;
|
||||
import su.nightexpress.nightcore.database.sql.SQLExecutor;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.column.ColumnFormer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
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;
|
||||
private final List<SQLColumn> columns;
|
||||
|
||||
private CreateTableExecutor(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
super(table);
|
||||
this.databaseType = databaseType;
|
||||
this.columns = new ArrayList<>();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CreateTableExecutor builder(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
return new CreateTableExecutor(table, databaseType);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public CreateTableExecutor columns(@NotNull SQLColumn... columns) {
|
||||
return this.columns(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public CreateTableExecutor columns(@NotNull List<SQLColumn> columns) {
|
||||
this.columns.clear();
|
||||
this.columns.addAll(columns);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
if (this.columns.isEmpty()) return null;
|
||||
|
||||
String id = "`id` " + ColumnFormer.INTEGER.build(this.databaseType, 11);
|
||||
if (this.databaseType == DatabaseType.SQLITE) {
|
||||
id += " PRIMARY KEY AUTOINCREMENT";
|
||||
}
|
||||
else {
|
||||
id += " PRIMARY KEY AUTO_INCREMENT";
|
||||
}
|
||||
|
||||
String columns = id + "," + this.columns.stream()
|
||||
.map(column -> column.getNameEscaped() + " " + column.formatType(this.databaseType))
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
String sql = "CREATE TABLE IF NOT EXISTS " + this.getTable() + "(" + columns + ");";
|
||||
|
||||
SQLQueries.executeStatement(connector, sql);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.SQLCondition;
|
||||
import su.nightexpress.nightcore.database.sql.SQLExecutor;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
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;
|
||||
|
||||
private DeleteQueryExecutor(@NotNull String table) {
|
||||
super(table);
|
||||
this.wheres = new ArrayList<>();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static DeleteQueryExecutor builder(@NotNull String table) {
|
||||
return new DeleteQueryExecutor(table);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DeleteQueryExecutor where(@NotNull SQLCondition... wheres) {
|
||||
return this.where(Arrays.asList(wheres));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DeleteQueryExecutor where(@NotNull List<SQLCondition> wheres) {
|
||||
this.wheres.clear();
|
||||
this.wheres.addAll(wheres);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
//if (this.wheres.isEmpty()) return null;
|
||||
|
||||
String whereCols = this.wheres.stream()
|
||||
.map(where -> where.getValue().getColumn().getNameEscaped() + " " + where.getType().getOperator() + " ?")
|
||||
.collect(Collectors.joining(" AND "));
|
||||
String sql = "DELETE FROM " + this.getTable() + (whereCols.isEmpty() ? "" : " WHERE " + whereCols);
|
||||
|
||||
List<String> whereVals = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList();
|
||||
|
||||
SQLQueries.executeStatement(connector, sql, whereVals);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.SQLColumn;
|
||||
import su.nightexpress.nightcore.database.sql.SQLExecutor;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
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;
|
||||
|
||||
private InsertQueryExecutor(@NotNull String table) {
|
||||
super(table);
|
||||
this.values = new ArrayList<>();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static InsertQueryExecutor builder(@NotNull String table) {
|
||||
return new InsertQueryExecutor(table);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public InsertQueryExecutor values(@NotNull SQLValue... values) {
|
||||
return this.values(Arrays.asList(values));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public InsertQueryExecutor values(@NotNull List<SQLValue> values) {
|
||||
this.values.clear();
|
||||
this.values.addAll(values);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
if (this.values.isEmpty()) return null;
|
||||
|
||||
String columns = this.values.stream().map(SQLValue::getColumn).map(SQLColumn::getNameEscaped).collect(Collectors.joining(","));
|
||||
String values = this.values.stream().map(value -> "?").collect(Collectors.joining(","));
|
||||
String sql = "INSERT INTO " + this.getTable() + "(" + columns + ") VALUES(" + values + ")";
|
||||
List<String> values2 = this.values.stream().map(SQLValue::getValue).toList();
|
||||
|
||||
SQLQueries.executeStatement(connector, sql, values2);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.DatabaseType;
|
||||
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;
|
||||
private String renameTo;
|
||||
|
||||
private RenameTableExecutor(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
super(table);
|
||||
this.databaseType = databaseType;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static RenameTableExecutor builder(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
return new RenameTableExecutor(table, databaseType);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public RenameTableExecutor renameTo(@NotNull String renameTo) {
|
||||
this.renameTo = renameTo;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
if (this.renameTo == null || this.renameTo.isEmpty()) return null;
|
||||
if (!SQLQueries.hasTable(connector, this.getTable())) return null;
|
||||
|
||||
StringBuilder sql = new StringBuilder();
|
||||
if (this.databaseType == DatabaseType.MYSQL) {
|
||||
sql.append("RENAME TABLE ").append(this.getTable()).append(" TO ").append(this.renameTo).append(";");
|
||||
}
|
||||
else {
|
||||
sql.append("ALTER TABLE ").append(this.getTable()).append(" RENAME TO ").append(this.renameTo);
|
||||
}
|
||||
SQLQueries.executeStatement(connector, sql.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.*;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
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;
|
||||
private final List<SQLCondition> wheres;
|
||||
private final Function<ResultSet, T> dataFunction;
|
||||
private int amount;
|
||||
|
||||
private SelectQueryExecutor(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction) {
|
||||
super(table);
|
||||
this.columns = new ArrayList<>();
|
||||
this.wheres = new ArrayList<>();
|
||||
this.dataFunction = dataFunction;
|
||||
this.amount = -1;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> SelectQueryExecutor<T> builder(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction) {
|
||||
return new SelectQueryExecutor<>(table, dataFunction);
|
||||
}
|
||||
|
||||
/*@NotNull
|
||||
public SelectQueryExecutor<T> all() {
|
||||
return this.columns(new SQLColumn("*", ColumnType.STRING, -1));
|
||||
}*/
|
||||
|
||||
@NotNull
|
||||
public SelectQueryExecutor<T> columns(@NotNull SQLColumn... columns) {
|
||||
return this.columns(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SelectQueryExecutor<T> columns(@NotNull List<SQLColumn> columns) {
|
||||
//if (columns.isEmpty()) return this.all();
|
||||
this.columns.clear();
|
||||
this.columns.addAll(columns);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SelectQueryExecutor<T> where(@NotNull SQLCondition... wheres) {
|
||||
return this.where(Arrays.asList(wheres));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SelectQueryExecutor<T> where(@NotNull List<SQLCondition> wheres) {
|
||||
this.wheres.clear();
|
||||
this.wheres.addAll(wheres);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SelectQueryExecutor<T> amount(int amount) {
|
||||
this.amount = amount;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public List<T> execute(@NotNull AbstractConnector connector) {
|
||||
String columns = this.columns.stream().map(SQLColumn::getNameEscaped).collect(Collectors.joining(","));
|
||||
if (columns.isEmpty()) columns = "*";
|
||||
|
||||
String wheres = this.wheres.stream().map(where -> where.getColumn().getNameEscaped() + " " + where.getType().getOperator() + " ?")
|
||||
.collect(Collectors.joining(" AND "));
|
||||
|
||||
String sql = "SELECT " + columns + " FROM " + this.getTable() + (wheres.isEmpty() ? "" : " WHERE " + wheres);
|
||||
|
||||
List<String> values = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList();
|
||||
|
||||
return SQLQueries.executeQuery(connector, sql, values, this.dataFunction, this.amount);
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.SQLCondition;
|
||||
import su.nightexpress.nightcore.database.sql.SQLExecutor;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
import su.nightexpress.nightcore.database.sql.query.UpdateQuery;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Deprecated
|
||||
public final class UpdateQueryExecutor extends SQLExecutor<Void> {
|
||||
|
||||
private final List<SQLValue> values;
|
||||
private final List<SQLCondition> wheres;
|
||||
|
||||
private UpdateQueryExecutor(@NotNull String table) {
|
||||
super(table);
|
||||
this.values = new ArrayList<>();
|
||||
this.wheres = new ArrayList<>();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static UpdateQueryExecutor builder(@NotNull String table) {
|
||||
return new UpdateQueryExecutor(table);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UpdateQueryExecutor values(@NotNull SQLValue... values) {
|
||||
return this.values(Arrays.asList(values));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UpdateQueryExecutor values(@NotNull List<SQLValue> values) {
|
||||
this.values.clear();
|
||||
this.values.addAll(values);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UpdateQueryExecutor where(@NotNull SQLCondition... wheres) {
|
||||
return this.where(Arrays.asList(wheres));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UpdateQueryExecutor where(@NotNull List<SQLCondition> wheres) {
|
||||
this.wheres.clear();
|
||||
this.wheres.addAll(wheres);
|
||||
return this;
|
||||
}
|
||||
|
||||
/*@Nullable
|
||||
public UpdateQuery createObject() {
|
||||
if (this.values.isEmpty()) return null;
|
||||
|
||||
String values = this.values.stream().map(value -> value.getColumn().getNameEscaped() + " = ?")
|
||||
.collect(Collectors.joining(","));
|
||||
|
||||
String wheres = this.wheres.stream().map(where -> where.getColumn().getNameEscaped() + " " + where.getType().getOperator() + " ?")
|
||||
.collect(Collectors.joining(" AND "));
|
||||
|
||||
String sql = "UPDATE " + this.getTable() + " SET " + values + (wheres.isEmpty() ? "" : " WHERE " + wheres);
|
||||
|
||||
List<String> values2 = this.values.stream().map(SQLValue::getValue).toList();
|
||||
List<String> whers2 = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList();
|
||||
|
||||
return new UpdateQuery(sql, values2, whers2);
|
||||
}*/
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
if (this.values.isEmpty()) return null;
|
||||
|
||||
String values = this.values.stream().map(value -> value.getColumn().getNameEscaped() + " = ?")
|
||||
.collect(Collectors.joining(","));
|
||||
|
||||
String wheres = this.wheres.stream().map(where -> where.getColumn().getNameEscaped() + " " + where.getType().getOperator() + " ?")
|
||||
.collect(Collectors.joining(" AND "));
|
||||
|
||||
String sql = "UPDATE " + this.getTable() + " SET " + values + (wheres.isEmpty() ? "" : " WHERE " + wheres);
|
||||
|
||||
List<String> values2 = this.values.stream().map(SQLValue::getValue).toList();
|
||||
List<String> whers2 = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList();
|
||||
|
||||
SQLQueries.executeStatement(connector, sql, values2, whers2);
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package su.nightexpress.nightcore.database.sql.query;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.sql.SQLCondition;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Deprecated
|
||||
public class UpdateEntity {
|
||||
|
||||
private final List<String> columnNames;
|
||||
private final List<String> values;
|
||||
private final List<String> whereColumns;
|
||||
private final List<String> wheres;
|
||||
|
||||
private UpdateEntity(@NotNull List<String> columnNames,
|
||||
@NotNull List<String> values,
|
||||
@NotNull List<String> whereColumns,
|
||||
@NotNull List<String> wheres) {
|
||||
this.columnNames = columnNames;
|
||||
this.values = values;
|
||||
this.whereColumns = whereColumns;
|
||||
this.wheres = wheres;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static UpdateEntity create(@NotNull List<SQLValue> values) {
|
||||
return create(values, Collections.emptyList());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static UpdateEntity create(@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());
|
||||
});
|
||||
|
||||
return new UpdateEntity(columnNames, columnValues, whereColumns, whereValues);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String createSQL(@NotNull String table) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("UPDATE ").append(table);
|
||||
builder.append(" SET ").append(String.join(",", this.columnNames));
|
||||
if (!this.whereColumns.isEmpty()) {
|
||||
builder.append(" WHERE ").append(String.join(" AND ", this.whereColumns));
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getColumnNames() {
|
||||
return columnNames;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getValues() {
|
||||
return values;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getWhereColumns() {
|
||||
return whereColumns;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getWheres() {
|
||||
return wheres;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package su.nightexpress.nightcore.database.sql.query;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.sql.SQLCondition;
|
||||
import su.nightexpress.nightcore.database.sql.SQLUtils;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Deprecated
|
||||
public class UpdateQuery /*extends AbstractQuery*/ {
|
||||
|
||||
private final List<UpdateEntity> entities;
|
||||
private final String table;
|
||||
|
||||
private String sql;
|
||||
|
||||
public UpdateQuery(@NotNull String table/*@NotNull String table, @NotNull String sql*/) {
|
||||
//super(table, sql);
|
||||
this.table = SQLUtils.escape(table);
|
||||
this.entities = new ArrayList<>();
|
||||
}
|
||||
|
||||
public UpdateQuery append(@NotNull UpdateEntity entity) {
|
||||
String entitySQL = entity.createSQL(this.table);
|
||||
if (this.sql == null) {
|
||||
this.sql = entitySQL;
|
||||
}
|
||||
else if (!entitySQL.equalsIgnoreCase(this.sql)) {
|
||||
throw new IllegalStateException("Can not add SQLEntity with a different signature!");
|
||||
}
|
||||
|
||||
this.entities.add(entity);
|
||||
return this;
|
||||
}
|
||||
|
||||
@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) {
|
||||
return create(table, UpdateEntity.create(values, conditions));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static UpdateQuery create(@NotNull String table, @NotNull UpdateEntity entity) {
|
||||
return new UpdateQuery(table).append(entity);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static UpdateQuery create(@NotNull String table, @NotNull Collection<UpdateEntity> entities) {
|
||||
UpdateQuery query = new UpdateQuery(table);
|
||||
entities.forEach(query::append);
|
||||
return query;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public boolean isEmpty() {
|
||||
return this.sql == null || this.table.isBlank() || this.sql.isBlank() || this.entities.isEmpty();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getSQL() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<UpdateEntity> getEntities() {
|
||||
return entities;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
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) {
|
||||
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.limit(1));
|
||||
return list.isEmpty() ? null : list.getFirst();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> List<T> select(@NotNull String table, @NotNull SelectQuery<T> query) {
|
||||
return SQLQueries.executeSelect(this.connector, table, query);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
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();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void onLoad() {
|
||||
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public 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,362 @@
|
||||
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();
|
||||
}
|
||||
|
||||
protected void onLoad(@NotNull U user) {
|
||||
|
||||
}
|
||||
|
||||
protected void onUnload(@NotNull U user) {
|
||||
|
||||
}
|
||||
|
||||
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);
|
||||
this.onLoad(user);
|
||||
}
|
||||
|
||||
private void unload(@NotNull U user) {
|
||||
user.onUnload();
|
||||
this.onUnload(user);
|
||||
|
||||
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 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)));
|
||||
}
|
||||
|
||||
public void manageUser(@NotNull Player player, Consumer<U> consumer) {
|
||||
this.manageUser(player, consumer, false);
|
||||
}
|
||||
|
||||
public void manageUserWithSave(@NotNull Player player, Consumer<U> consumer) {
|
||||
this.manageUser(player, consumer, true);
|
||||
}
|
||||
|
||||
private void manageUser(@NotNull Player player, Consumer<U> consumer, boolean save) {
|
||||
U user = this.getLoaded(player);
|
||||
if (user == null) return;
|
||||
|
||||
consumer.accept(user);
|
||||
if (save) this.save(user);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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) {
|
||||
U byName = this.loadedByNameMap.get(name.toLowerCase());
|
||||
if (byName != null) return byName;
|
||||
|
||||
Player player = Players.getPlayer(name);
|
||||
return player == null ? null : this.getLoaded(player.getUniqueId());
|
||||
}
|
||||
|
||||
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.getLoaded(name) != null;//this.loadedByNameMap.containsKey(name.toLowerCase());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
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.config.Writeable;
|
||||
import su.nightexpress.nightcore.util.StringUtil;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class DatabaseConfig implements Writeable {
|
||||
|
||||
public static final String DEF_FILE_NAME = "data.db";
|
||||
public static final String DEF_PATH = "Database.";
|
||||
|
||||
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());
|
||||
|
||||
FileConfig config = plugin.getConfig();
|
||||
FileConfig engineConf = plugin.getEngineConfig();
|
||||
|
||||
// ---------- MIGRATION - START ----------
|
||||
if (config.contains("Database")) {
|
||||
DatabaseConfig old = read(config, defPrefix);
|
||||
old.write(engineConf, "Database");
|
||||
//config.remove(DEF_PATH);
|
||||
if (!config.contains("Database.UserData")) {
|
||||
config.remove("Database");
|
||||
}
|
||||
}
|
||||
// ---------- MIGRATION - END ----------
|
||||
|
||||
return read(engineConf, defPrefix);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static DatabaseConfig read(@NotNull FileConfig config, @NotNull String defaultPrefix) {
|
||||
return read(config, DEF_PATH, defaultPrefix, DEF_FILE_NAME);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static DatabaseConfig read(@NotNull FileConfig config, @NotNull String path, @NotNull String defaultPrefix, @NotNull String defFileName) {
|
||||
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);
|
||||
|
||||
|
||||
boolean purgeEnabled = ConfigValue.create(path + ".Purge.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 + ".Purge.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
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(@NotNull FileConfig config, @NotNull String path) {
|
||||
config.set(path + ".Type", this.databaseType.name());
|
||||
config.set(path + ".Sync_Interval", this.syncInterval);
|
||||
config.set(path + ".Table_Prefix", this.tablePrefix);
|
||||
config.set(path + ".MySQL.Username", this.username);
|
||||
config.set(path + ".MySQL.Password", this.password);
|
||||
config.set(path + ".MySQL.Host", this.host);
|
||||
config.set(path + ".MySQL.Database", this.database);
|
||||
config.set(path + ".MySQL.Options", this.urlOptions);
|
||||
config.set(path + ".SQLite.FileName", this.filename);
|
||||
config.set(path + ".Purge.Enabled", this.purgeEnabled);
|
||||
config.set(path + ".Purge.For_Period", this.purgePeriod);
|
||||
}
|
||||
|
||||
@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,127 @@
|
||||
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.config.Writeable;
|
||||
|
||||
public class UserdataConfig implements Writeable {
|
||||
|
||||
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();
|
||||
FileConfig engineConf = plugin.getEngineConfig();
|
||||
|
||||
// ---------- MIGRATION - START ----------
|
||||
if (config.contains("Database.UserData")) {
|
||||
UserdataConfig old = read(config, "Database.UserData");
|
||||
old.write(engineConf, "UserData");
|
||||
config.remove("Database");
|
||||
}
|
||||
// ---------- MIGRATION - END ----------
|
||||
|
||||
return read(engineConf, "UserData");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static UserdataConfig read(@NotNull FileConfig config, @NotNull String path) {
|
||||
long cacheLifetime = ConfigValue.create(path + ".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(path + ".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(path + ".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(path + ".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(path + ".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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(@NotNull FileConfig config, @NotNull String path) {
|
||||
config.set(path + ".Cache.LifeTime", this.cacheLifetime);
|
||||
config.set(path + ".Cache.CleanUp_Interval", this.cacheCleanupInterval);
|
||||
config.set(path + ".Scheduled_Save_Interval", this.saveInterval);
|
||||
config.set(path + ".Scheduled_Save_Delay", this.saveDelay);
|
||||
config.set(path + ".Scheduled_Save_Sync_Pause", this.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;
|
||||
}
|
||||
}
|
||||
@@ -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,30 @@
|
||||
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 databaseConfig) {
|
||||
String host = databaseConfig.getHost();
|
||||
String database = databaseConfig.getDatabase();
|
||||
String options = databaseConfig.getUrlOptions();
|
||||
|
||||
return "jdbc:mysql://" + host + "/" + database + options;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setupConfig(@NotNull DatabaseConfig databaseConfig) {
|
||||
this.config.setUsername(databaseConfig.getUsername());
|
||||
if (!databaseConfig.getPassword().isBlank()) {
|
||||
this.config.setPassword(databaseConfig.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;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 326 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user