1
mirror of https://github.com/CarmJos/MineSQL.git synced 2026-06-04 16:43:03 +08:00

feat(proj): 项目完成,测试使用。

This commit is contained in:
2022-12-18 02:57:08 +08:00
parent 1557c14116
commit 5c30bea7eb
46 changed files with 1501 additions and 1497 deletions
+20 -12
View File
@@ -3,12 +3,11 @@
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">
<parent>
<artifactId>easysql-plugin</artifactId>
<artifactId>minesql-parent</artifactId>
<groupId>cc.carm.plugin</groupId>
<version>0.0.3-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<maven.compiler.source>${project.jdk.version}</maven.compiler.source>
<maven.compiler.target>${project.jdk.version}</maven.compiler.target>
@@ -17,11 +16,11 @@
<maven.javadoc.skip>true</maven.javadoc.skip>
<maven.deploy.skip>true</maven.deploy.skip>
</properties>
<artifactId>easysql-plugin-core</artifactId>
<artifactId>minesql-core</artifactId>
<name>EasySQL-Plugin-Core</name>
<name>MineSQL-Core</name>
<description>轻松(用)SQL的独立运行库插件的主要实现部分。</description>
<url>https://github.com/CarmJos/EasySQL-Plugin</url>
<url>https://github.com/CarmJos/MineSQL</url>
<developers>
<developer>
@@ -45,19 +44,19 @@
<issueManagement>
<system>GitHub Issues</system>
<url>https://github.com/CarmJos/EasySQL-Plugin/issues</url>
<url>https://github.com/CarmJos/MineSQL/issues</url>
</issueManagement>
<ciManagement>
<system>GitHub Actions</system>
<url>https://github.com/CarmJos/EasySQL-Plugin/actions/workflows/maven.yml</url>
<url>https://github.com/CarmJos/MineSQL/actions/workflows/maven.yml</url>
</ciManagement>
<dependencies>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>easysql-plugin-api</artifactId>
<artifactId>minesql-api</artifactId>
<version>${project.parent.version}</version>
<scope>compile</scope>
</dependency>
@@ -87,6 +86,18 @@
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cc.carm.lib</groupId>
<artifactId>easyplugin-utils</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cc.carm.lib</groupId>
<artifactId>easyconfiguration-yaml</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cc.carm.lib</groupId>
<artifactId>githubreleases4j</artifactId>
@@ -105,6 +116,7 @@
<scope>compile</scope>
</dependency>
<!--suppress VulnerableLibrariesLocal -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
@@ -133,10 +145,6 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
</plugins>
</build>
@@ -0,0 +1,144 @@
package cc.carm.plugin.minesql;
import cc.carm.lib.configuration.EasyConfiguration;
import cc.carm.lib.configuration.yaml.YAMLConfigProvider;
import cc.carm.lib.easyplugin.utils.JarResourceUtils;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.githubreleases4j.GithubReleases4J;
import cc.carm.plugin.minesql.api.source.SQLSourceConfig;
import cc.carm.plugin.minesql.command.EasySQLCommand;
import cc.carm.plugin.minesql.command.EasySQLHelpFormatter;
import cc.carm.plugin.minesql.conf.PluginConfiguration;
import cc.carm.plugin.minesql.conf.SQLSourceGroup;
import cc.carm.plugin.minesql.util.DBPropertiesUtil;
import co.aikar.commands.CommandManager;
import co.aikar.commands.InvalidCommandArgument;
import co.aikar.commands.Locales;
import com.google.common.collect.ImmutableList;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
public class MineSQLCore implements IMineSQL {
public static final String REPO_OWNER = "CarmJos";
public static final String REPO_NAME = "MineSQL";
protected final MineSQLPlatform platform;
protected final MineSQLRegistry registry;
protected final YAMLConfigProvider configProvider;
protected final PluginConfiguration config;
public MineSQLCore(MineSQLPlatform platform) {
this.platform = platform;
getLogger().info("加载配置文件...");
this.configProvider = EasyConfiguration.from(new File(platform.getPluginFolder(), "config.yml"));
this.config = new PluginConfiguration();
this.configProvider.initialize(this.config);
getLogger().info("初始化注册池...");
this.registry = new MineSQLRegistry(this);
}
public MineSQLPlatform getPlatform() {
return platform;
}
@Override
public @NotNull MineSQLRegistry getRegistry() {
return this.registry;
}
@Override
public @NotNull File getPluginFolder() {
return getPlatform().getPluginFolder();
}
@Override
public @NotNull Logger getLogger() {
return getPlatform().getLogger();
}
public PluginConfiguration getConfig() {
return config;
}
public YAMLConfigProvider getConfigProvider() {
return configProvider;
}
public @NotNull Map<String, SQLSourceConfig> readConfigurations() {
SQLSourceGroup group = getConfig().SOURCES.getNotNull();
Map<String, SQLSourceConfig> sources = new LinkedHashMap<>();
group.getSources().forEach((k, v) -> sources.put(k, v.createSource()));
return sources;
}
public @NotNull Map<String, Properties> readProperties() {
if (!getConfig().PROPERTIES.ENABLE.getNotNull()) return new HashMap<>();
String propertiesFolder = getConfig().PROPERTIES.FOLDER.get();
if (propertiesFolder == null || propertiesFolder.length() == 0) return new HashMap<>();
File file = new File(getPluginFolder(), propertiesFolder);
if (!file.exists() || !file.isDirectory()) {
try {
JarResourceUtils.copyFolderFromJar(
"db-properties", file, JarResourceUtils.CopyOption.COPY_IF_NOT_EXIST
);
} catch (Exception ex) {
getLogger().severe("初始化properties示例文件失败:" + ex.getMessage());
}
}
return DBPropertiesUtil.readFromFolder(file);
}
@SuppressWarnings("deprecation")
protected void initializeCommands(CommandManager<?, ?, ?, ?, ?, ?> commandManager) {
commandManager.enableUnstableAPI("help");
commandManager.setHelpFormatter(new EasySQLHelpFormatter(commandManager));
commandManager.getLocales().setDefaultLocale(Locales.SIMPLIFIED_CHINESE);
commandManager.getCommandContexts().registerContext(SQLManager.class, c -> {
String name = c.popFirstArg();
try {
return getRegistry().get(name);
} catch (NullPointerException exception) {
throw new InvalidCommandArgument("不存在名为 " + name + " 的数据库管理器。");
}
});
commandManager.getCommandCompletions().registerCompletion("sql-managers", c -> {
if (c.getIssuer().isPlayer()) return ImmutableList.of();
else return ImmutableList.copyOf(getRegistry().list().keySet());
});
commandManager.registerCommand(new EasySQLCommand(this));
}
public void checkUpdate(String currentVersion) {
Logger logger = getLogger();
Integer behindVersions = GithubReleases4J.getVersionBehind(REPO_OWNER, REPO_NAME, currentVersion);
String downloadURL = GithubReleases4J.getReleasesURL(REPO_OWNER, REPO_NAME);
if (behindVersions == null) {
logger.severe("检查更新失败,请您定期查看插件是否更新,避免安全问题。");
logger.severe("下载地址 " + downloadURL);
} else if (behindVersions < 0) {
logger.severe("检查更新失败! 当前版本未知,请您使用原生版本以避免安全问题。");
logger.severe("最新版下载地址 " + downloadURL);
} else if (behindVersions > 0) {
logger.warning("发现新版本! 目前已落后 " + behindVersions + " 个版本。");
logger.warning("最新版下载地址 " + downloadURL);
} else {
logger.info("检查完成,当前已是最新版本。");
}
}
}
@@ -1,52 +1,17 @@
package cc.carm.plugin.minesql;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.plugin.minesql.api.DBConfiguration;
import cc.carm.plugin.minesql.api.SQLRegistry;
import cc.carm.plugin.minesql.command.EasySQLCommand;
import cc.carm.plugin.minesql.command.EasySQLHelpFormatter;
import co.aikar.commands.CommandManager;
import co.aikar.commands.InvalidCommandArgument;
import co.aikar.commands.Locales;
import com.google.common.collect.ImmutableList;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.Properties;
import java.io.File;
import java.util.logging.Logger;
public interface MineSQLPlatform {
@NotNull SQLRegistry getRegistry();
@NotNull File getPluginFolder();
@NotNull Map<String, DBConfiguration> readConfigurations();
@NotNull Logger getLogger();
@NotNull Map<String, Properties> readProperties();
Logger getLogger();
default void initializeAPI(SQLRegistry registry) {
MineSQL.initializeAPI(registry);
}
@SuppressWarnings("deprecation")
default void initializeCommands(CommandManager<?, ?, ?, ?, ?, ?> commandManager) {
commandManager.enableUnstableAPI("help");
commandManager.setHelpFormatter(new EasySQLHelpFormatter(commandManager));
commandManager.getLocales().setDefaultLocale(Locales.SIMPLIFIED_CHINESE);
commandManager.getCommandContexts().registerContext(SQLManager.class, c -> {
String name = c.popFirstArg();
try {
return getRegistry().get(name);
} catch (NullPointerException exception) {
throw new InvalidCommandArgument("不存在名为 " + name + " 的数据库管理器。");
}
});
commandManager.getCommandCompletions().registerCompletion("sql-managers", c -> {
if (c.getIssuer().isPlayer()) return ImmutableList.of();
else return ImmutableList.copyOf(getRegistry().list().keySet());
});
commandManager.registerCommand(new EasySQLCommand());
}
@NotNull CommandManager<?, ?, ?, ?, ?, ?> getCommandManager();
}
@@ -3,9 +3,8 @@ package cc.carm.plugin.minesql;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery;
import cc.carm.lib.easysql.manager.SQLManagerImpl;
import cc.carm.lib.githubreleases4j.GithubReleases4J;
import cc.carm.plugin.minesql.api.DBConfiguration;
import cc.carm.plugin.minesql.api.SQLRegistry;
import cc.carm.plugin.minesql.api.source.SQLSourceConfig;
import cn.beecp.BeeDataSource;
import cn.beecp.BeeDataSourceConfig;
import com.google.common.collect.ImmutableMap;
@@ -18,40 +17,38 @@ import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.logging.Logger;
public class MineSQLRegistry implements SQLRegistry {
public static final String REPO_OWNER = "CarmJos";
public static final String REPO_NAME = "EasySQL-Plugin";
private static MineSQLRegistry instance;
protected ExecutorService executorPool;
protected MineSQLPlatform platform;
private final HashMap<String, SQLManagerImpl> sqlManagerRegistry = new HashMap<>();
protected MineSQLCore core;
private final HashMap<String, SQLManagerImpl> managers = new HashMap<>();
protected MineSQLRegistry(@NotNull MineSQLPlatform platform) {
this.platform = platform;
protected MineSQLRegistry(@NotNull MineSQLCore core) {
this.core = core;
MineSQLRegistry.instance = this;
this.executorPool = Executors.newFixedThreadPool(2, (r) -> {
Thread thread = new Thread(r, "EasySQLRegistry");
thread.setDaemon(true);
return thread;
});
Map<String, Properties> dbProperties = platform.readProperties();
Map<String, DBConfiguration> dbConfigurations = platform.readConfigurations();
Map<String, Properties> dbProperties = core.readProperties();
Map<String, SQLSourceConfig> dbConfigurations = core.readConfigurations();
if (dbProperties.isEmpty() && dbConfigurations.isEmpty()) {
platform.getLogger().warning("未检测到任何数据库配置,将不会创建任何SQLManager。");
core.getLogger().warning("未检测到任何数据库配置,将不会创建任何SQLManager。");
return;
}
dbProperties.forEach((id, properties) -> {
try {
SQLManagerImpl sqlManager = create(id, properties);
this.sqlManagerRegistry.put(id, sqlManager);
this.managers.put(id, sqlManager);
} catch (Exception exception) {
platform.getLogger().warning("初始化SQLManager(#" + id + ") 出错,请检查配置文件.");
core.getLogger().warning("初始化SQLManager(#" + id + ") 出错,请检查配置文件.");
exception.printStackTrace();
}
});
@@ -59,54 +56,86 @@ public class MineSQLRegistry implements SQLRegistry {
dbConfigurations.forEach((id, configuration) -> {
try {
SQLManagerImpl sqlManager = create(id, configuration);
this.sqlManagerRegistry.put(id, sqlManager);
this.managers.put(id, sqlManager);
} catch (Exception exception) {
platform.getLogger().warning("初始化SQLManager(#" + id + ") 出错,请检查配置文件.");
core.getLogger().warning("初始化SQLManager(#" + id + ") 出错,请检查配置文件.");
exception.printStackTrace();
}
});
}
public void shutdownAll() {
this.managers.forEach((k, manager) -> {
getCore().getLogger().info(" 正在关闭数据库 " + k + "...");
shutdown(manager, activeQueries -> {
getCore().getLogger().info(" 数据库 " + k + " 仍有有 " + activeQueries + " 条活动查询");
if (manager.getDataSource() instanceof BeeDataSource
&& this.core.getConfig().SETTINGS.FORCE_CLOSE.getNotNull()) {
getCore().getLogger().info(" 将强制关闭全部活跃链接...");
BeeDataSource dataSource = (BeeDataSource) manager.getDataSource();
dataSource.close(); //Close bee connection pool
}
});
});
this.managers.clear();
}
protected HashMap<String, SQLManagerImpl> getManagers() {
return managers;
}
public ExecutorService getExecutor() {
return executorPool;
}
public static MineSQLRegistry getInstance() {
return instance;
}
public MineSQLCore getCore() {
return core;
}
@Override
public @NotNull SQLManagerImpl get(@Nullable String id) throws NullPointerException {
return Objects.requireNonNull(this.sqlManagerRegistry.get(id), "并不存在ID为 #" + id + " 的SQLManager.");
return Objects.requireNonNull(this.managers.get(id), "并不存在ID为 #" + id + " 的SQLManager.");
}
@Override
public @NotNull Optional<@Nullable SQLManagerImpl> getOptional(@Nullable String id) {
return Optional.of(this.sqlManagerRegistry.get(id));
return Optional.of(this.managers.get(id));
}
@Override
@Unmodifiable
public @NotNull Map<String, SQLManagerImpl> list() {
return ImmutableMap.copyOf(this.sqlManagerRegistry);
return ImmutableMap.copyOf(this.managers);
}
@Override
public @NotNull SQLManagerImpl create(@NotNull String name, @NotNull DBConfiguration configuration) throws Exception {
public @NotNull SQLManagerImpl create(@NotNull String name, @NotNull SQLSourceConfig conf) {
BeeDataSourceConfig config = new BeeDataSourceConfig();
config.setDriverClassName(configuration.getDriverClassName());
config.setJdbcUrl(configuration.getUrlPrefix() + configuration.getUrl());
Optional.ofNullable(configuration.getUsername()).ifPresent(config::setUsername);
Optional.ofNullable(configuration.getPassword()).ifPresent(config::setPassword);
config.setDriverClassName(conf.getDriverClassName());
config.setJdbcUrl(conf.getJdbcURL());
Optional.ofNullable(conf.getUsername()).ifPresent(config::setUsername);
Optional.ofNullable(conf.getPassword()).ifPresent(config::setPassword);
Optional.ofNullable(configuration.getPoolName()).ifPresent(config::setPoolName);
Optional.ofNullable(configuration.getMaxPoolSize()).ifPresent(config::setMaxActive);
Optional.ofNullable(configuration.getMaxActive()).ifPresent(config::setMaxActive);
Optional.ofNullable(conf.getSettings().getPoolName()).ifPresent(config::setPoolName);
Optional.ofNullable(conf.getSettings().getMaxPoolSize()).ifPresent(config::setMaxActive);
Optional.ofNullable(conf.getSettings().getMaxActive()).ifPresent(config::setMaxActive);
Optional.ofNullable(configuration.getIdleTimeout()).ifPresent(config::setIdleTimeout);
Optional.ofNullable(configuration.getMaxWaitTime()).ifPresent(config::setMaxWait);
Optional.ofNullable(configuration.getMaxHoldTime()).ifPresent(config::setHoldTimeout);
Optional.ofNullable(conf.getSettings().getIdleTimeout()).ifPresent(config::setIdleTimeout);
Optional.ofNullable(conf.getSettings().getMaxWaitTime()).ifPresent(config::setMaxWait);
Optional.ofNullable(conf.getSettings().getMaxHoldTime()).ifPresent(config::setHoldTimeout);
Optional.ofNullable(configuration.getAutoCommit()).ifPresent(config::setDefaultAutoCommit);
Optional.ofNullable(configuration.getReadOnly()).ifPresent(config::setDefaultReadOnly);
Optional.ofNullable(configuration.getSchema()).ifPresent(config::setDefaultSchema);
Optional.ofNullable(conf.getSettings().getAutoCommit()).ifPresent(config::setDefaultAutoCommit);
Optional.ofNullable(conf.getSettings().getReadOnly()).ifPresent(config::setDefaultReadOnly);
Optional.ofNullable(conf.getSettings().getSchema()).ifPresent(config::setDefaultSchema);
Optional.ofNullable(configuration.getValidationSQL()).ifPresent(config::setValidTestSql);
Optional.ofNullable(configuration.getValidationTimeout()).ifPresent(config::setValidTestTimeout);
Optional.ofNullable(configuration.getValidationInterval()).ifPresent(config::setValidAssumeTime);
Optional.ofNullable(conf.getSettings().getValidationSQL()).ifPresent(config::setValidTestSql);
Optional.ofNullable(conf.getSettings().getValidationTimeout()).ifPresent(config::setValidTestTimeout);
Optional.ofNullable(conf.getSettings().getValidationInterval()).ifPresent(config::setValidAssumeTime);
return create(name, config);
}
@@ -135,39 +164,4 @@ public class MineSQLRegistry implements SQLRegistry {
}
}
protected HashMap<String, SQLManagerImpl> getManagers() {
return sqlManagerRegistry;
}
public ExecutorService getExecutor() {
return executorPool;
}
public static MineSQLRegistry getInstance() {
return instance;
}
public MineSQLPlatform getPlatform() {
return platform;
}
public void checkUpdate(String currentVersion) {
Logger logger = getInstance().getPlatform().getLogger();
getExecutor().execute(() -> {
Integer behindVersions = GithubReleases4J.getVersionBehind(REPO_OWNER, REPO_NAME, currentVersion);
String downloadURL = GithubReleases4J.getReleasesURL(REPO_OWNER, REPO_NAME);
if (behindVersions == null) {
logger.severe("检查更新失败,请您定期查看插件是否更新,避免安全问题。");
logger.severe("下载地址 " + downloadURL);
} else if (behindVersions < 0) {
logger.severe("检查更新失败! 当前版本未知,请您使用原生版本以避免安全问题。");
logger.severe("最新版下载地址 " + downloadURL);
} else if (behindVersions > 0) {
logger.warning("发现新版本! 目前已落后 " + behindVersions + " 个版本。");
logger.warning("最新版下载地址 " + downloadURL);
} else {
logger.info("检查完成,当前已是最新版本。");
}
});
}
}
@@ -2,6 +2,7 @@ package cc.carm.plugin.minesql.command;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery;
import cc.carm.plugin.minesql.MineSQLCore;
import cc.carm.plugin.minesql.MineSQLRegistry;
import cc.carm.plugin.minesql.util.VersionReader;
import co.aikar.commands.BaseCommand;
@@ -15,9 +16,15 @@ import java.util.UUID;
@SuppressWarnings("unused")
@CommandAlias("EasySQL")
@Description("EasySQL-Plugin的主指令,用于开发者进行调试,只允许后台执行。")
@Description("MineSQL的主指令,用于开发者进行调试,只允许后台执行。")
public class EasySQLCommand extends BaseCommand {
protected final MineSQLCore core;
public EasySQLCommand(MineSQLCore core) {
this.core = core;
}
@HelpCommand
@Syntax("&9[页码或子指令名称]")
@Description("查看指定数据源的统计信息与当前仍未关闭的查询。")
@@ -49,7 +56,7 @@ public class EasySQLCommand extends BaseCommand {
issuer.sendMessage("§8 - &f数据库驱动 h2-database §9" + reader.get("h2-driver"));
issuer.sendMessage("§r正在检查插件更新,请稍候...");
MineSQLRegistry.getInstance().checkUpdate(pluginVersion);
core.checkUpdate(pluginVersion);
}
@Subcommand("list")
@@ -10,7 +10,7 @@ public class EasySQLHelpFormatter extends CommandHelpFormatter {
@Override
public void printHelpHeader(CommandHelp help, CommandIssuer issuer) {
issuer.sendMessage("§3§lEasySQL-Plugin §7指令帮助");
issuer.sendMessage("§3§lMineSQL §7指令帮助");
}
@Override
@@ -27,7 +27,7 @@ public class EasySQLHelpFormatter extends CommandHelpFormatter {
@Override
public void printSearchHeader(CommandHelp help, CommandIssuer issuer) {
issuer.sendMessage("§3§lEasySQL-Plugin §7指令帮助查询");
issuer.sendMessage("§3§lMineSQL §7指令帮助查询");
}
@Override
@@ -41,7 +41,7 @@ public class EasySQLHelpFormatter extends CommandHelpFormatter {
@Override
public void printDetailedHelpHeader(CommandHelp help, CommandIssuer issuer, HelpEntry entry) {
issuer.sendMessage("§3§lEasySQL-Plugin §7指令帮助 §8(§f" + entry.getCommand() + "§8)");
issuer.sendMessage("§3§lMineSQL §7指令帮助 §8(§f" + entry.getCommand() + "§8)");
}
@Override
@@ -0,0 +1,70 @@
package cc.carm.plugin.minesql.conf;
import cc.carm.lib.configuration.core.ConfigurationRoot;
import cc.carm.lib.configuration.core.annotation.HeaderComment;
import cc.carm.lib.configuration.core.value.ConfigValue;
import cc.carm.lib.configuration.core.value.type.ConfiguredValue;
public class PluginConfiguration extends ConfigurationRoot {
@HeaderComment("排错模式,一般留给开发者检查问题,平常使用无需开启。")
public ConfigValue<Boolean> DEBUG = ConfiguredValue.of(Boolean.class, false);
@HeaderComment({
"统计数据设定",
"该选项用于帮助开发者统计插件版本与使用情况,且绝不会影响性能与使用体验。",
"当然,您也可以选择在这里关闭,或在plugins/bStats下的配置文件中关闭所有插件的统计信息。"
})
public ConfigValue<Boolean> METRICS = ConfiguredValue.of(Boolean.class, true);
@HeaderComment({
"检查更新设定",
"该选项用于插件判断是否要检查更新,若您不希望插件检查更新并提示您,可以选择关闭。",
"检查更新为异步操作,绝不会影响性能与使用体验。"
})
public ConfigValue<Boolean> UPDATE_CHECKER = ConfiguredValue.of(Boolean.class, true);
@HeaderComment({"插件注册池配置"})
public SettingsConfig SETTINGS = new SettingsConfig();
@HeaderComment({
"Properties 数据库配置文件配置",
"相关配置介绍(BeeCP) https://github.com/Chris2018998/BeeCP/wiki/Configuration--List#配置列表"
})
public PropertiesConfig PROPERTIES = new PropertiesConfig();
@HeaderComment({
"数据库源配置",
"目前支持的驱动类型(type)有 mariadb、mysql、h2-file(文件数据库) 与 h2-mem(内存临时数据库)。",
"详细配置介绍请查看 https://github.com/CarmJos/MineSQL/.doc/README.md"
})
public ConfigValue<SQLSourceGroup> SOURCES = ConfigValue.builder()
.asValue(SQLSourceGroup.class).fromSection()
.parseValue((w, d) -> SQLSourceGroup.parse(w))
.serializeValue(SQLSourceGroup::serialize)
.build();
public static class PropertiesConfig extends ConfigurationRoot {
@HeaderComment("该选项用于启用 Properties 配置读取,若您不希望插件启用 Properties 文件配置,可以选择关闭。")
public ConfigValue<Boolean> ENABLE = ConfiguredValue.of(Boolean.class, true);
@HeaderComment({
"文件夹路径,将读取该文件夹下的所有 .properties 文件,并以文件名为数据管理器名称。",
"读取时,将排除以 “.” 开头的文件与非 .properties 文件。",
"默认为 \"db-properties/\" 相对路径,指向“plugins/MineSQL/db-properties/”;",
"该选项也支持绝对路径,但使用绝对路径时,请务必注意权限问题。"
})
public ConfigValue<String> FOLDER = ConfiguredValue.of(String.class, "db-properties/");
}
public static class SettingsConfig extends ConfigurationRoot {
@HeaderComment({"在插件卸载时是否强制关闭活跃链接"})
public ConfigValue<Boolean> FORCE_CLOSE = ConfiguredValue.of(Boolean.class, true);
}
}
@@ -0,0 +1,88 @@
package cc.carm.plugin.minesql.conf;
import cc.carm.lib.configuration.core.source.ConfigurationWrapper;
import cc.carm.plugin.minesql.MineSQL;
import cc.carm.plugin.minesql.api.SQLDriverType;
import cc.carm.plugin.minesql.api.conf.SQLDriverConfig;
import cc.carm.plugin.minesql.api.conf.drivers.H2MemConfig;
import cc.carm.plugin.minesql.api.conf.impl.FileBasedConfig;
import cc.carm.plugin.minesql.api.conf.impl.RemoteAuthConfig;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
public class SQLSourceGroup {
protected final LinkedHashMap<String, SQLDriverConfig> sources;
public SQLSourceGroup(LinkedHashMap<String, SQLDriverConfig> sources) {
this.sources = sources;
}
public Map<String, SQLDriverConfig> getSources() {
return Collections.unmodifiableMap(sources);
}
public @NotNull Map<String, Object> serialize() {
Map<String, Object> data = new LinkedHashMap<>();
this.sources.forEach((k, v) -> data.put(k, v.serialize()));
return data;
}
public static @NotNull SQLSourceGroup parse(ConfigurationWrapper<?> rootSection) {
LinkedHashMap<String, SQLDriverConfig> configs = new LinkedHashMap<>();
for (String name : rootSection.getKeys(false)) {
if (!rootSection.isConfigurationSection(name)) continue;
ConfigurationWrapper<?> section = rootSection.getConfigurationSection(name);
if (section == null) continue;
SQLDriverConfig conf = parse(name, section);
if (conf != null) configs.put(name, conf);
}
return new SQLSourceGroup(configs);
}
public static @Nullable SQLDriverConfig parse(String name, ConfigurationWrapper<?> section) {
@Nullable String driverString = section.getString("type");
@Nullable SQLDriverType driverType = SQLDriverType.parse(driverString);
if (driverType == null) {
MineSQL.getLogger().severe("驱动类型 " + driverString + " 不存在于预设中," + " 请检查配置文件 sources." + name + "");
return null;
}
switch (driverType) {
case MYSQL:
case MARIADB: {
String host = section.getString("host");
int port = section.getInt("port", 0);
String database = section.getString("database");
if (host == null || database == null || !(port > 0 && port <= 65535)) {
MineSQL.getLogger().severe("数据库连接配置有误," + " 请检查配置文件 sources." + name + "");
return null;
}
String username = section.getString("username");
String password = section.getString("password");
String extra = section.getString("extra");
return new RemoteAuthConfig(driverType, host, port, database, username, password, extra);
}
case H2_MEM: {
return new H2MemConfig(section.getString("database"));
}
case H2_FILE: {
String filePath = section.getString("file");
if (filePath == null) {
MineSQL.getLogger().severe("数据库文件地址配置有误," + " 请检查配置文件 sources." + name + "");
return null;
}
return new FileBasedConfig(SQLDriverType.H2_FILE, filePath);
}
}
return null;
}
}
@@ -1,22 +0,0 @@
package cc.carm.plugin.minesql.configuration;
import cc.carm.plugin.minesql.api.DBConfiguration;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
public interface PluginConfiguration {
boolean isDebugEnabled();
boolean isMetricsEnabled();
boolean isUpdateCheckerEnabled();
boolean isPropertiesEnabled();
String getPropertiesFolder();
@NotNull Map<String, DBConfiguration> getDBConfigurations();
}
@@ -1,105 +0,0 @@
package cc.carm.plugin.minesql.util;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@SuppressWarnings("ResultOfMethodCallIgnored")
public class JarResourceUtils {
public static final char JAR_SEPARATOR = '/';
public static @Nullable String[] readResource(@Nullable InputStream resourceStream) {
if (resourceStream == null) return null;
try (Scanner scanner = new Scanner(resourceStream, "UTF-8")) {
List<String> contents = new ArrayList<>();
while (scanner.hasNextLine()) {
contents.add(scanner.nextLine());
}
return contents.toArray(new String[0]);
} catch (Exception e) {
return null;
}
}
public static void copyFolderFromJar(String folderName, File destFolder, CopyOption option)
throws IOException {
copyFolderFromJar(folderName, destFolder, option, null);
}
public static void copyFolderFromJar(String folderName, File destFolder,
CopyOption option, PathTrimmer trimmer) throws IOException {
if (!destFolder.exists())
destFolder.mkdirs();
byte[] buffer = new byte[1024];
File fullPath;
String path = JarResourceUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
if (trimmer != null)
path = trimmer.trim(path);
try {
if (!path.startsWith("file"))
path = "file://" + path;
fullPath = new File(new URI(path));
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(fullPath));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (!entry.getName().startsWith(folderName + JAR_SEPARATOR))
continue;
String fileName = entry.getName();
if (fileName.charAt(fileName.length() - 1) == JAR_SEPARATOR) {
File file = new File(destFolder + File.separator + fileName);
if (file.isFile()) {
file.delete();
}
file.mkdirs();
continue;
}
File file = new File(destFolder + File.separator + fileName);
if (option == CopyOption.COPY_IF_NOT_EXIST && file.exists())
continue;
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
if (!file.exists())
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
zis.closeEntry();
zis.close();
}
public enum CopyOption {
COPY_IF_NOT_EXIST, REPLACE_IF_EXIST
}
@FunctionalInterface
public interface PathTrimmer {
String trim(String original);
}
}
+6 -11
View File
@@ -1,11 +1,6 @@
&3 ______ _____ ____ _ &f_____ _ _
&3| ____| / ____|/ __ \| | &f| __ \| | (_)
&3| |__ __ _ ___ _ _| (___ | | | | | &f| |__) | |_ _ __ _ _ _ __
&3| __| / _` / __| | | |\___ \| | | | | &f| ___/| | | | |/ _` | | '_ \
&3| |___| (_| \__ \ |_| |____) | |__| | |____ &f| | | | |_| | (_| | | | | |
&3|______\__,_|___/\__, |_____/ \___\_\______| &f|_| |_|\__,_|\__, |_|_| |_|
&3 __/ | &f __/ |
&3 |___/ &f|___/
&f 查看更多信息请访问项目主页&f https://github.com/CarmJos/EasySQL-Plugin
&d __ ____ &f________ __
&d / |/ (_)__ ___ &f/ __/ __ \ / /
&d / /|_/ / / _ \/ -_)&f\ \/ /_/ / / /__
&d/_/ /_/_/_//_/\__/&f___/\___\_\/____/
&8# &dMine&fSQL &8&o(EasySQL-Plugin) &7v&f${project.version}
&8- &7查看更多信息请访问项目主页&f https://github.com/CarmJos/MineSQL
-44
View File
@@ -1,44 +0,0 @@
version: ${project.version} #配置文件版本,若与插件版本不同请记得检查配置文件内容
debug: false
# 统计数据设定
# 改选项用于帮助开发者统计插件版本与使用情况,且绝不会影响性能与使用体验。
# 当然,您也可以选择在这里关闭,或在plugins/bStats下的配置文件中关闭。
metrics: true
# 检查更新设定
# 该选项用于插件判断是否要检查更新,若您不希望插件检查更新并提示您,可以选择关闭。
# 检查更新为异步操作,绝不会影响性能与使用体验。
check-update: true
# 启用 Properties 文件配置
# 相关配置介绍(BeeCP) https://github.com/Chris2018998/BeeCP/wiki/Configuration--List#配置列表
properties:
# 该选项用于启用 Properties 配置读取,若您不希望插件启用 Properties 文件配置,可以选择关闭。
enable: true
# 文件夹路径,将读取该文件夹下的所有 .properties 文件,并以文件名为数据管理器名称。
# 读取时,将排除以 “.” 开头的文件与非 .properties 文件。
# 默认为 "db-properties/" 相对路径,指向“plugins/EasySQL-Plugin/db-properties/”;
# 该选项也支持绝对路径,但使用绝对路径时,请务必注意权限问题。
folder: "db-properties/"
# 数据库源配置
# 目前支持的驱动类型(driver-type)有 mariadb、mysql 与 h2(文件数据库) 。
databases:
"example-mariadb": # 数据库源名称 不可包含“.” 以“example-”开头的数据源不会被加载
driver-type: mariadb
host: 127.0.0.1 # 数据库地址
port: 3306 # 数据库端口
username: minecraft # 数据库用户名
password: password #数据库连接密码
database: minecraft #数据库名
"example-h2": # 数据库源名称 不可包含“.” 以“example-”开头的数据源不会被加载
driver-type: h2 #数据库驱动类型,目前支持 mariadb, mysql, h2
file: "example.db" #数据库文件路径,相对于“plugins/EasySQL-Plugin/db-files/”
username: minecraft # 数据库用户名
password: password #数据库连接密码
database: minecraft #数据库名
+5 -5
View File
@@ -1,11 +1,11 @@
# suppress inspection "SpellCheckingInspection" for whole file
plugin=${project.version}
api=${easysql.version}
api=${deps.easysql.version}
beecp=${beecp.version}
beecp=${deps.beecp.version}
mysql-driver=${mysql-driver.version}
mariadb-driver=${mariadb-driver.version}
h2-driver=${h2-driver.version}
mysql-driver=${deps.mysql-driver.version}
mariadb-driver=${deps.mariadb-driver.version}
h2-driver=${deps.h2-driver.version}