Merge pull request #675 from Rsl1122/4.4.2

Pull Request for 4.4.2
This commit is contained in:
Rsl1122 2018-08-08 12:55:31 +03:00 committed by GitHub
commit 724942ae54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
225 changed files with 8022 additions and 3734 deletions

2
.gitignore vendored
View File

@ -3,6 +3,8 @@ Plan.iml
PlanPluginBridge.iml
.sonar/
*.db
# Shell files
*.sh

View File

@ -27,7 +27,7 @@
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@ -71,15 +71,20 @@
<relocation>
<pattern>com.maxmind</pattern>
<shadedPattern>plan.com.maxmind</shadedPattern>
<excludes>
<exclude>org.apache.logging.**</exclude>
</excludes>
</relocation>
<relocation>
<pattern>com.fasterxml</pattern>
<shadedPattern>plan.com.fasterxml</shadedPattern>
</relocation>
<relocation>
<pattern>com.zaxxer</pattern>
<shadedPattern>plan.com.zaxxer</shadedPattern>
</relocation>
<relocation>
<pattern>org.slf4j</pattern>
<shadedPattern>plan.org.slf4j</shadedPattern>
<excludes>
<exclude>org.apache.logging.**</exclude>
<exclude>org.slf4j.Logger</exclude>
</excludes>
</relocation>
</relocations>
@ -91,7 +96,7 @@
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<version>3.0.2</version>
<configuration>
<excludes>
<exclude>**/test/*</exclude>
@ -104,7 +109,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
<version>0.8.0</version>
</plugin>
<plugin>
<artifactId>maven-checkstyle-plugin</artifactId>
@ -180,10 +185,6 @@
<artifactId>bungeecord-chat</artifactId>
<groupId>net.md-5</groupId>
</exclusion>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
<exclusion>
<artifactId>asm</artifactId>
<groupId>org.ow2.asm</groupId>
@ -197,7 +198,7 @@
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<version>1.12.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
@ -285,7 +286,7 @@
<dependency>
<groupId>org.spongepowered</groupId>
<artifactId>spongeapi</artifactId>
<version>LATEST</version>
<version>7.0.0</version>
<scope>provided</scope>
<exclusions>
<exclusion>
@ -328,10 +329,6 @@
<artifactId>flow-noise</artifactId>
<groupId>com.flowpowered</groupId>
</exclusion>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
<exclusion>
<artifactId>jsr305</artifactId>
<groupId>com.google.code.findbugs</groupId>
@ -373,7 +370,7 @@
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.21.0</version>
<version>3.21.0.1</version>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -6,6 +6,7 @@
<artifactId>Plan</artifactId>
<version>4.3.0-SNAPSHOT</version>
<packaging>jar</packaging>
<repositories>
<repository>
<id>bungeecord-repo</id>
@ -24,6 +25,7 @@
<url>https://repo.spongepowered.org/maven</url>
</repository>
</repositories>
<dependencies>
<!-- Framework for easier plugin development -->
<dependency>
@ -37,6 +39,7 @@
<artifactId>PlanPluginBridge</artifactId>
<version>4.3.0-SNAPSHOT</version>
</dependency>
<!-- Paper API -->
<dependency>
<groupId>com.destroystokyo.paper</groupId>
@ -48,7 +51,7 @@
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<version>1.12.2-R0.1-SNAPSHOT</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
@ -70,37 +73,36 @@
<dependency>
<groupId>org.spongepowered</groupId>
<artifactId>spongeapi</artifactId>
<version>LATEST</version>
<version>7.0.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<!-- String Replacer -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.3</version>
</dependency>
<!-- HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- Connection Pool -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.1.0</version>
</dependency>
<!-- Geo IP -->
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.9.0</version>
</dependency>
<!-- Connection Pool -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- Mockito (Test Dependency) -->
<dependency>
@ -111,11 +113,10 @@
<scope>test</scope>
</dependency>
<!-- SQLite (Test Dependency) -->
<!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.21.0</version>
<version>3.21.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
@ -155,7 +156,7 @@
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@ -200,15 +201,20 @@
<relocation>
<pattern>com.maxmind</pattern>
<shadedPattern>plan.com.maxmind</shadedPattern>
<excludes>
<exclude>org.apache.logging.**</exclude>
</excludes>
</relocation>
<relocation>
<pattern>com.fasterxml</pattern>
<shadedPattern>plan.com.fasterxml</shadedPattern>
</relocation>
<relocation>
<pattern>com.zaxxer</pattern>
<shadedPattern>plan.com.zaxxer</shadedPattern>
</relocation>
<relocation>
<pattern>org.slf4j</pattern>
<shadedPattern>plan.org.slf4j</shadedPattern>
<excludes>
<exclude>org.apache.logging.**</exclude>
<exclude>org.slf4j.Logger</exclude>
</excludes>
</relocation>
</relocations>
@ -222,7 +228,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<version>3.0.2</version>
<configuration>
<excludes>
<exclude>**/test/*</exclude>
@ -235,7 +241,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
<version>0.8.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>

View File

@ -22,10 +22,10 @@ package com.djrapitops.plan;
import com.djrapitops.plan.api.exceptions.EnableException;
import com.djrapitops.plan.command.PlanCommand;
import com.djrapitops.plan.system.BukkitSystem;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.processing.importing.ImporterManager;
import com.djrapitops.plan.system.processing.importing.importers.OfflinePlayerImporter;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.system.settings.theme.PlanColorScheme;
import com.djrapitops.plan.utilities.metrics.BStats;
import com.djrapitops.plugin.BukkitPlugin;
@ -48,6 +48,7 @@ import java.util.logging.Logger;
public class Plan extends BukkitPlugin implements PlanPlugin {
private BukkitSystem system;
private Locale locale;
/**
* Used to get the plugin-instance singleton.
@ -58,11 +59,6 @@ public class Plan extends BukkitPlugin implements PlanPlugin {
return (Plan) StaticHolder.getInstance(Plan.class);
}
/**
* OnEnable method.
* <p>
* - Enables the plugin's subsystems.
*/
@Override
public void onEnable() {
super.onEnable();
@ -70,6 +66,7 @@ public class Plan extends BukkitPlugin implements PlanPlugin {
Benchmark.start("Enable");
system = new BukkitSystem(this);
system.enable();
locale = system.getLocaleSystem().getLocale();
ImporterManager.registerImporter(new OfflinePlayerImporter());
@ -79,7 +76,7 @@ public class Plan extends BukkitPlugin implements PlanPlugin {
Log.debug("Verbose debug messages are enabled.");
Benchmark.stop("Enable", "Enable");
Log.logDebug("Enable");
Log.info(Locale.get(Msg.ENABLED).toString());
Log.info(locale.getString(PluginLang.ENABLED));
} catch (AbstractMethodError e) {
Log.error("Plugin ran into AbstractMethodError - Server restart is required. Likely cause is updating the jar without a restart.");
} catch (EnableException e) {
@ -109,7 +106,7 @@ public class Plan extends BukkitPlugin implements PlanPlugin {
public void onDisable() {
system.disable();
Log.info(Locale.get(Msg.DISABLED).toString());
Log.info(locale.getString(PluginLang.DISABLED));
Benchmark.pluginDisabled(Plan.class);
DebugLog.pluginDisabled(Plan.class);
}

View File

@ -7,8 +7,8 @@ package com.djrapitops.plan;
import com.djrapitops.plan.api.exceptions.EnableException;
import com.djrapitops.plan.command.PlanBungeeCommand;
import com.djrapitops.plan.system.BungeeSystem;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.settings.theme.PlanColorScheme;
import com.djrapitops.plugin.BungeePlugin;
import com.djrapitops.plugin.StaticHolder;
@ -29,6 +29,7 @@ import java.util.logging.Logger;
public class PlanBungee extends BungeePlugin implements PlanPlugin {
private BungeeSystem system;
private Locale locale;
public static PlanBungee getInstance() {
return (PlanBungee) StaticHolder.getInstance(PlanBungee.class);
@ -40,8 +41,9 @@ public class PlanBungee extends BungeePlugin implements PlanPlugin {
try {
system = new BungeeSystem(this);
system.enable();
locale = system.getLocaleSystem().getLocale();
Log.info(Locale.get(Msg.ENABLED).toString());
Log.info(locale.getString(PluginLang.ENABLED));
} catch (AbstractMethodError e) {
Log.error("Plugin ran into AbstractMethodError - Server restart is required. Likely cause is updating the jar without a restart.");
} catch (EnableException e) {
@ -63,7 +65,7 @@ public class PlanBungee extends BungeePlugin implements PlanPlugin {
public void onDisable() {
system.disable();
Log.info(Locale.get(Msg.DISABLED).toString());
Log.info(locale.getString(PluginLang.DISABLED));
Benchmark.pluginDisabled(PlanBungee.class);
DebugLog.pluginDisabled(PlanBungee.class);
}

View File

@ -4,6 +4,7 @@
*/
package com.djrapitops.plan;
import com.djrapitops.plan.system.PlanSystem;
import com.djrapitops.plugin.IPlugin;
import com.djrapitops.plugin.api.Check;
import com.djrapitops.plugin.settings.ColorScheme;
@ -60,4 +61,6 @@ public interface PlanPlugin extends IPlugin {
@Override
boolean isReloading();
PlanSystem getSystem();
}

View File

@ -3,8 +3,8 @@ package com.djrapitops.plan;
import com.djrapitops.plan.api.exceptions.EnableException;
import com.djrapitops.plan.command.PlanCommand;
import com.djrapitops.plan.system.SpongeSystem;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.settings.theme.PlanColorScheme;
import com.djrapitops.plugin.SpongePlugin;
import com.djrapitops.plugin.StaticHolder;
@ -23,7 +23,7 @@ import org.spongepowered.api.plugin.Plugin;
import java.io.File;
import java.io.InputStream;
@Plugin(id = "plan", name = "Plan", version = "4.4.1", description = "Player Analytics Plugin by Rsl1122", authors = {"Rsl1122"})
@Plugin(id = "plan", name = "Plan", version = "4.4.2", description = "Player Analytics Plugin by Rsl1122", authors = {"Rsl1122"})
public class PlanSponge extends SpongePlugin implements PlanPlugin {
@Inject
@ -33,6 +33,7 @@ public class PlanSponge extends SpongePlugin implements PlanPlugin {
@ConfigDir(sharedRoot = false)
private File dataFolder;
private SpongeSystem system;
private Locale locale;
@Listener
public void onServerStart(GameStartedServerEvent event) {
@ -54,6 +55,9 @@ public class PlanSponge extends SpongePlugin implements PlanPlugin {
system = new SpongeSystem(this);
try {
system.enable();
locale = system.getLocaleSystem().getLocale();
Log.info(locale.getString(PluginLang.ENABLED));
} catch (AbstractMethodError e) {
Log.error("Plugin ran into AbstractMethodError - Server restart is required. Likely cause is updating the jar without a restart.");
} catch (EnableException e) {
@ -77,7 +81,7 @@ public class PlanSponge extends SpongePlugin implements PlanPlugin {
system.disable();
}
Log.info(Locale.get(Msg.DISABLED).toString());
Log.info(locale.getString(PluginLang.DISABLED));
Benchmark.pluginDisabled(PlanSponge.class);
DebugLog.pluginDisabled(PlanSponge.class);
}

View File

@ -1,11 +1,11 @@
package com.djrapitops.plan.command;
import com.djrapitops.plan.PlanBungee;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.command.commands.*;
import com.djrapitops.plan.command.commands.manage.ManageConDebugCommand;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.TreeCmdNode;
@ -21,37 +21,36 @@ import com.djrapitops.plugin.command.defaultcmds.StatusCommand;
*/
public class PlanBungeeCommand extends TreeCmdNode {
/**
* CommandExecutor class Constructor.
* <p>
* Initializes Subcommands
*
* @param plugin Current instance of Plan
*/
public PlanBungeeCommand(PlanBungee plugin) {
public PlanBungeeCommand(PlanPlugin plugin) {
super("planbungee", Permissions.MANAGE.getPermission(), CommandType.CONSOLE, null);
super.setColorScheme(plugin.getColorScheme());
setInDepthHelp(Locale.get(Msg.CMD_HELP_PLAN).toArray());
RegisterCommand registerCommand = new RegisterCommand();
setNodeGroups(
new CommandNode[]{
new NetworkCommand(),
new ListServersCommand(plugin),
new ListCommand(),
},
new CommandNode[]{
registerCommand,
new WebUserCommand(plugin, registerCommand, this),
},
new CommandNode[]{
new ManageConDebugCommand(),
new BungeeSetupToggleCommand(),
new ReloadCommand(plugin),
new DisableCommand(),
new StatusCommand<>(plugin, Permissions.MANAGE.getPermission(), plugin.getColorScheme()),
Locale locale = plugin.getSystem().getLocaleSystem().getLocale();
setInDepthHelp(locale.getArray(DeepHelpLang.PLAN));
RegisterCommand registerCommand = new RegisterCommand(plugin);
CommandNode[] analyticsGroup = {
new NetworkCommand(plugin),
new ListServersCommand(plugin),
new ListPlayersCommand(plugin),
};
CommandNode[] webGroup = {
registerCommand,
new WebUserCommand(plugin, registerCommand, this),
};
CommandNode[] manageGroup = {
new ManageConDebugCommand(plugin),
new BungeeSetupToggleCommand(plugin),
new ReloadCommand(plugin),
new DisableCommand(plugin),
new StatusCommand<>(plugin, Permissions.MANAGE.getPermission(), plugin.getColorScheme()),
// (Settings.ALLOW_UPDATE.isTrue() ? new UpdateCommand() : null)
}
};
setNodeGroups(
analyticsGroup,
webGroup,
manageGroup
);
}
}

View File

@ -2,10 +2,10 @@ package com.djrapitops.plan.command;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.command.commands.*;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.TreeCmdNode;
@ -25,31 +25,33 @@ public class PlanCommand extends TreeCmdNode {
super("plan", "", CommandType.CONSOLE, null);
super.setDefaultCommand("inspect");
super.setColorScheme(plugin.getColorScheme());
setInDepthHelp(Locale.get(Msg.CMD_HELP_PLAN).toArray());
RegisterCommand registerCommand = new RegisterCommand();
setNodeGroups(
new CommandNode[]{
new InspectCommand(),
new QInspectCommand(plugin),
new SearchCommand(),
new ListCommand(),
new AnalyzeCommand(),
new NetworkCommand(),
new ListServersCommand(plugin)
},
new CommandNode[]{
new WebUserCommand(plugin, registerCommand, this),
registerCommand
},
new CommandNode[]{
new InfoCommand(plugin),
new ReloadCommand(plugin),
new ManageCommand(plugin, this),
new StatusCommand<>(plugin, Permissions.MANAGE.getPermission(), plugin.getColorScheme()),
(Settings.DEV_MODE.isTrue() ? new DevCommand() : null),
Locale locale = plugin.getSystem().getLocaleSystem().getLocale();
setInDepthHelp(locale.getArray(DeepHelpLang.PLAN));
RegisterCommand registerCommand = new RegisterCommand(plugin);
CommandNode[] analyticsGroup = {
new InspectCommand(plugin),
new QInspectCommand(plugin),
new SearchCommand(plugin),
new ListPlayersCommand(plugin),
new AnalyzeCommand(plugin),
new NetworkCommand(plugin),
new ListServersCommand(plugin)
};
CommandNode[] webGroup = {
new WebUserCommand(plugin, registerCommand, this),
registerCommand
};
CommandNode[] manageGroup = {
new InfoCommand(plugin),
new ReloadCommand(plugin),
new ManageCommand(plugin, this),
new StatusCommand<>(plugin, Permissions.MANAGE.getPermission(), plugin.getColorScheme()),
(Settings.DEV_MODE.isTrue() ? new DevCommand(plugin) : null),
// (Settings.ALLOW_UPDATE.isTrue() ? new UpdateCommand() : null)
}
);
};
setNodeGroups(analyticsGroup, webGroup, manageGroup);
}
}

View File

@ -1,5 +1,6 @@
package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.api.exceptions.connection.WebException;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.system.database.databases.Database;
@ -7,10 +8,13 @@ import com.djrapitops.plan.system.info.InfoSystem;
import com.djrapitops.plan.system.info.connection.ConnectionSystem;
import com.djrapitops.plan.system.info.server.Server;
import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.processing.Processing;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.system.webserver.WebServerSystem;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
@ -30,23 +34,27 @@ import java.util.UUID;
*/
public class AnalyzeCommand extends CommandNode {
public AnalyzeCommand() {
private final Locale locale;
public AnalyzeCommand(PlanPlugin plugin) {
super("analyze|analyse|analysis|a", Permissions.ANALYZE.getPermission(), CommandType.CONSOLE);
setShortHelp(Locale.get(Msg.CMD_USG_ANALYZE).parse());
setInDepthHelp(Locale.get(Msg.CMD_HELP_ANALYZE).toArray());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.ANALYZE));
setInDepthHelp(locale.getArray(DeepHelpLang.ANALYZE));
setArguments("[server/id]");
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
sender.sendMessage(Locale.get(Msg.CMD_INFO_FETCH_DATA).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_START));
Processing.submitNonCritical(() -> {
try {
Server server = getServer(args).orElseGet(ServerInfo::getServer);
UUID serverUUID = server.getUuid();
InfoSystem.getInstance().generateAnalysisPage(serverUUID);
sendWebUserNotificationIfNecessary(sender);
sendLink(server, sender);
@ -60,17 +68,17 @@ public class AnalyzeCommand extends CommandNode {
private void sendLink(Server server, ISender sender) {
String target = "/server/" + server.getName();
String url = ConnectionSystem.getAddress() + target;
String message = Locale.get(Msg.CMD_INFO_LINK).toString();
sender.sendMessage(Locale.get(Msg.CMD_HEADER_ANALYZE).toString());
String linkPrefix = locale.getString(CommandLang.LINK_PREFIX);
sender.sendMessage(locale.getString(CommandLang.HEADER_ANALYSIS));
// Link
boolean console = !CommandUtils.isPlayer(sender);
if (console) {
sender.sendMessage(message + url);
sender.sendMessage(linkPrefix + url);
} else {
sender.sendMessage(message);
sender.sendLink(" ", Locale.get(Msg.CMD_INFO_CLICK_ME).toString(), url);
sender.sendMessage(linkPrefix);
sender.sendLink(" ", locale.getString(CommandLang.LINK_CLICK_ME), url);
}
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
sender.sendMessage(">");
}
private void sendWebUserNotificationIfNecessary(ISender sender) {
@ -78,7 +86,7 @@ public class AnalyzeCommand extends CommandNode {
boolean senderHasWebUser = Database.getActive().check().doesWebUserExists(sender.getName());
if (!senderHasWebUser) {
sender.sendMessage("§e[Plan] You might not have a web user, use /plan register <password>");
sender.sendMessage("§e" + locale.getString(CommandLang.NO_WEB_USER_NOTIFY));
}
}
}

View File

@ -4,7 +4,12 @@
*/
package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.info.connection.ConnectionSystem;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
@ -19,9 +24,15 @@ import com.djrapitops.plugin.command.ISender;
*/
public class BungeeSetupToggleCommand extends CommandNode {
public BungeeSetupToggleCommand() {
private final Locale locale;
public BungeeSetupToggleCommand(PlanPlugin plugin) {
super("setup", Permissions.MANAGE.getPermission(), CommandType.ALL);
setShortHelp("Toggle Setup mode for Bungee");
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.SETUP));
setInDepthHelp(locale.getArray(DeepHelpLang.SETUP));
}
@Override
@ -34,7 +45,7 @@ public class BungeeSetupToggleCommand extends CommandNode {
} else {
connectionSystem.setSetupAllowed(true);
}
String msg = !setupAllowed ? "§aSet-up is now Allowed" : "§cSet-up is now Forbidden";
String msg = locale.getString(!setupAllowed ? CommandLang.SETUP_ALLOWED : CommandLang.CONNECT_FORBIDDEN);
sender.sendMessage(msg);
}
}

View File

@ -4,13 +4,17 @@
*/
package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.utilities.Verify;
import java.util.Arrays;
/**
* Command used for testing functions that are too difficult to unit test.
*
@ -18,15 +22,21 @@ import com.djrapitops.plugin.utilities.Verify;
*/
public class DevCommand extends CommandNode {
public DevCommand() {
private final Locale locale;
public DevCommand(PlanPlugin plugin) {
super("dev", "plan.*", CommandType.PLAYER_OR_ARGS);
setShortHelp("Test Plugin functions not testable with unit tests.");
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.get(CmdHelpLang.DEV).toString());
setArguments("<feature>");
}
@Override
public void onCommand(ISender sender, String cmd, String[] args) {
Verify.isTrue(args.length >= 1, () -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString()));
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ONE_ARG, Arrays.toString(this.getArguments()))));
sender.sendMessage("No features currently implemented in the command.");
}

View File

@ -1,22 +1,30 @@
package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
public class DisableCommand extends CommandNode {
public DisableCommand() {
private final Locale locale;
public DisableCommand(PlanPlugin plugin) {
super("disable", "plan.reload", CommandType.ALL);
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.DISABLE));
setInDepthHelp(locale.getArray(DeepHelpLang.DISABLE));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
PlanPlugin.getInstance().onDisable();
sender.sendMessage(
"§aPlan systems are now disabled. " +
"You can still use /planbungee reload to restart the plugin."
);
sender.sendMessage(locale.getString(CommandLang.DISABLE_DISABLED));
}
}

View File

@ -3,14 +3,15 @@ package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.info.connection.ConnectionSystem;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.GenericLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.system.update.VersionCheckSystem;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.settings.ColorScheme;
/**
* This SubCommand is used to view the version and the database type in use.
@ -21,29 +22,33 @@ import com.djrapitops.plugin.settings.ColorScheme;
public class InfoCommand extends CommandNode {
private final PlanPlugin plugin;
private final Locale locale;
public InfoCommand(PlanPlugin plugin) {
super("info", Permissions.INFO.getPermission(), CommandType.CONSOLE);
setShortHelp(Locale.get(Msg.CMD_USG_INFO).toString());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.get(CmdHelpLang.INFO).toString());
this.plugin = plugin;
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
ColorScheme cs = plugin.getColorScheme();
String mColor = cs.getMainColor();
String sColor = cs.getSecondaryColor();
String tColor = cs.getTertiaryColor();
String ball = Locale.get(Msg.CMD_CONSTANT_LIST_BALL).toString();
String yes = locale.getString(GenericLang.YES);
String no = locale.getString(GenericLang.NO);
String upToDate = VersionCheckSystem.isNewVersionAvailable() ? "Update Available" : "Up to date";
String updateAvailable = VersionCheckSystem.isNewVersionAvailable() ? yes : no;
String connectedToBungee = ConnectionSystem.getInstance().isServerAvailable() ? yes : no;
String[] messages = {
Locale.get(Msg.CMD_HEADER_INFO).toString(),
ball + mColor + " Version: " + sColor + plugin.getVersion(),
ball + mColor + " Up to date: " + sColor + upToDate,
ball + mColor + " Active Database: " + tColor + Database.getActive().getConfigName(),
ball + mColor + " Connected to Bungee: " + tColor + (ConnectionSystem.getInstance().isServerAvailable() ? "Yes" : "No"),
Locale.get(Msg.CMD_CONSTANT_FOOTER).toString()
locale.getString(CommandLang.HEADER_INFO),
"",
locale.getString(CommandLang.INFO_VERSION, plugin.getVersion()),
locale.getString(CommandLang.INFO_UPDATE, updateAvailable),
locale.getString(CommandLang.INFO_DATABASE, Database.getActive().getName()),
locale.getString(CommandLang.INFO_BUNGEE_CONNECTION, connectedToBungee),
"",
">"
};
sender.sendMessage(messages);
}

View File

@ -1,12 +1,15 @@
package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.processing.Processing;
import com.djrapitops.plan.system.processing.processors.info.InspectCacheRequestProcessor;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.system.webserver.WebServer;
import com.djrapitops.plan.utilities.MiscUtils;
import com.djrapitops.plan.utilities.uuid.UUIDUtility;
@ -28,17 +31,26 @@ import java.util.UUID;
*/
public class InspectCommand extends CommandNode {
public InspectCommand() {
private final Locale locale;
public InspectCommand(PlanPlugin plugin) {
super("inspect", Permissions.INSPECT.getPermission(), CommandType.PLAYER_OR_ARGS);
setArguments("<player>");
setShortHelp(Locale.get(Msg.CMD_USG_INSPECT).toString());
setInDepthHelp(Locale.get(Msg.CMD_HELP_INSPECT).toArray());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.INSPECT));
setInDepthHelp(locale.getArray(DeepHelpLang.INSPECT));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
String playerName = MiscUtils.getPlayerName(args, sender);
if (playerName == null) {
sender.sendMessage(locale.getString(CommandLang.FAIL_NO_PERMISSION));
}
runInspectTask(playerName, sender);
}
@ -49,18 +61,18 @@ public class InspectCommand extends CommandNode {
try {
UUID uuid = UUIDUtility.getUUIDOf(playerName);
if (uuid == null) {
sender.sendMessage(Locale.get(Msg.CMD_FAIL_USERNAME_NOT_VALID).toString());
sender.sendMessage(locale.getString(CommandLang.FAIL_USERNAME_NOT_VALID));
return;
}
Database activeDB = Database.getActive();
if (!activeDB.check().isPlayerRegistered(uuid)) {
sender.sendMessage(Locale.get(Msg.CMD_FAIL_USERNAME_NOT_KNOWN).toString());
sender.sendMessage(locale.getString(CommandLang.FAIL_USERNAME_NOT_KNOWN));
return;
}
checkWebUserAndNotify(activeDB, sender);
Processing.submit(new InspectCacheRequestProcessor(uuid, sender, playerName));
Processing.submit(new InspectCacheRequestProcessor(uuid, sender, playerName, locale));
} catch (DBOpException e) {
if (e.isFatal()) {
sender.sendMessage("§cFatal database exception occurred: " + e.getMessage());
@ -80,7 +92,7 @@ public class InspectCommand extends CommandNode {
boolean senderHasWebUser = activeDB.check().doesWebUserExists(sender.getName());
if (!senderHasWebUser) {
sender.sendMessage("§e[Plan] You might not have a web user, use /plan register <password>");
sender.sendMessage("§e" + locale.getString(CommandLang.NO_WEB_USER_NOTIFY));
}
}
}

View File

@ -1,9 +1,12 @@
package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.info.connection.ConnectionSystem;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.CommandUtils;
@ -15,12 +18,17 @@ import com.djrapitops.plugin.command.ISender;
* @author Rsl1122
* @since 3.5.2
*/
public class ListCommand extends CommandNode {
public class ListPlayersCommand extends CommandNode {
public ListCommand() {
private final Locale locale;
public ListPlayersCommand(PlanPlugin plugin) {
super("players|pl|playerlist|list", Permissions.INSPECT_OTHER.getPermission(), CommandType.CONSOLE);
setShortHelp(Locale.get(Msg.CMD_USG_LIST).toString());
setInDepthHelp(Locale.get(Msg.CMD_HELP_LIST).toArray());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.PLAYERS));
setInDepthHelp(locale.getArray(DeepHelpLang.PLAYERS));
}
@Override
@ -29,18 +37,18 @@ public class ListCommand extends CommandNode {
}
private void sendListMsg(ISender sender) {
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).parse());
sender.sendMessage(locale.getString(CommandLang.HEADER_PLAYERS));
// Link
String url = ConnectionSystem.getAddress() + "/players/";
String message = Locale.get(Msg.CMD_INFO_LINK).toString();
String linkPrefix = locale.getString(CommandLang.LINK_PREFIX);
boolean console = !CommandUtils.isPlayer(sender);
if (console) {
sender.sendMessage(message + url);
sender.sendMessage(linkPrefix + url);
} else {
sender.sendMessage(message);
sender.sendLink(" ", Locale.get(Msg.CMD_INFO_CLICK_ME).toString(), url);
sender.sendMessage(linkPrefix);
sender.sendLink(" ", locale.getString(CommandLang.LINK_CLICK_ME), url);
}
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
sender.sendMessage(">");
}
}

View File

@ -4,9 +4,11 @@ import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.info.server.Server;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
@ -23,27 +25,30 @@ import java.util.List;
public class ListServersCommand extends CommandNode {
private final PlanPlugin plugin;
private final Locale locale;
public ListServersCommand(PlanPlugin plugin) {
super("servers|serverlist|listservers|sl|ls", Permissions.MANAGE.getPermission(), CommandType.CONSOLE);
setShortHelp("List servers in the network");
this.plugin = plugin;
this.locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.SERVERS));
setInDepthHelp(locale.getArray(DeepHelpLang.SERVERS));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
try {
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString() + mCol + " Servers");
sender.sendMessage(locale.getString(CommandLang.HEADER_SERVERS));
List<Server> servers = Database.getActive().fetch().getServers();
for (Server server : servers) {
sender.sendMessage(" " + tCol + server.getId() + sCol + " : " + server.getName() + " : " + server.getWebAddress());
}
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
sender.sendMessage(">");
} catch (DBOpException e) {
sender.sendMessage("§cDatabase Exception occurred.");
Log.toLog(this.getClass(), e);

View File

@ -2,9 +2,10 @@ package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.command.commands.manage.*;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.TreeCmdNode;
@ -19,23 +20,26 @@ public class ManageCommand extends TreeCmdNode {
public ManageCommand(PlanPlugin plugin, CommandNode parent) {
super("manage|m", Permissions.MANAGE.getPermission(), CommandType.CONSOLE, parent);
setShortHelp(Locale.get(Msg.CMD_USG_MANAGE).toString());
setInDepthHelp(Locale.get(Msg.CMD_HELP_MANAGE).toArray());
Locale locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.MANAGE));
setInDepthHelp(locale.getArray(DeepHelpLang.MANAGE));
super.setColorScheme(plugin.getColorScheme());
setNodeGroups(
new CommandNode[]{
new ManageMoveCommand(),
new ManageBackupCommand(),
new ManageMoveCommand(plugin),
new ManageBackupCommand(plugin),
new ManageRestoreCommand(plugin),
new ManageRemoveCommand(),
new ManageRemoveCommand(plugin),
new ManageHotSwapCommand(plugin),
new ManageClearCommand(),
new ManageClearCommand(plugin),
},
new CommandNode[]{
new ManageSetupCommand(),
new ManageConDebugCommand(),
new ManageImportCommand(),
new ManageDisableCommand()
new ManageSetupCommand(plugin),
new ManageConDebugCommand(plugin),
new ManageImportCommand(plugin),
new ManageDisableCommand(plugin)
}
);
}

View File

@ -1,9 +1,12 @@
package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.info.connection.ConnectionSystem;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.CommandUtils;
@ -16,9 +19,15 @@ import com.djrapitops.plugin.command.ISender;
*/
public class NetworkCommand extends CommandNode {
public NetworkCommand() {
private final Locale locale;
public NetworkCommand(PlanPlugin plugin) {
super("network|n|netw", Permissions.ANALYZE.getPermission(), CommandType.CONSOLE);
setShortHelp("View the network page");
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.NETWORK));
setInDepthHelp(locale.getArray(DeepHelpLang.NETWORK));
}
@Override
@ -27,18 +36,18 @@ public class NetworkCommand extends CommandNode {
}
private void sendNetworkMsg(ISender sender) {
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).parse());
sender.sendMessage(locale.getString(CommandLang.HEADER_NETWORK));
// Link
String url = ConnectionSystem.getAddress() + "/network/";
String message = Locale.get(Msg.CMD_INFO_LINK).toString();
String linkPrefix = locale.getString(CommandLang.LINK_PREFIX);
boolean console = !CommandUtils.isPlayer(sender);
if (console) {
sender.sendMessage(message + url);
sender.sendMessage(linkPrefix + url);
} else {
sender.sendMessage(message);
sender.sendLink(" ", Locale.get(Msg.CMD_INFO_CLICK_ME).toString(), url);
sender.sendMessage(linkPrefix);
sender.sendLink(" ", locale.getString(CommandLang.LINK_CLICK_ME), url);
}
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
sender.sendMessage(">");
}
}

View File

@ -12,16 +12,18 @@ import com.djrapitops.plan.data.store.mutators.formatting.Formatter;
import com.djrapitops.plan.data.store.mutators.formatting.Formatters;
import com.djrapitops.plan.data.store.objects.DateHolder;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.locale.lang.GenericLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.utilities.MiscUtils;
import com.djrapitops.plan.utilities.uuid.UUIDUtility;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.RunnableFactory;
@ -38,7 +40,7 @@ import java.util.UUID;
*/
public class QInspectCommand extends CommandNode {
private final PlanPlugin plugin;
private final Locale locale;
/**
* Class Constructor.
@ -48,16 +50,22 @@ public class QInspectCommand extends CommandNode {
public QInspectCommand(PlanPlugin plugin) {
super("qinspect", Permissions.QUICK_INSPECT.getPermission(), CommandType.PLAYER_OR_ARGS);
setArguments("<player>");
setShortHelp(Locale.get(Msg.CMD_USG_QINSPECT).toString());
setInDepthHelp(Locale.get(Msg.CMD_HELP_QINSPECT).toArray());
this.plugin = plugin;
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.QINSPECT));
setInDepthHelp(locale.getArray(DeepHelpLang.QINSPECT));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
String playerName = MiscUtils.getPlayerName(args, sender, Permissions.QUICK_INSPECT_OTHER);
if (playerName == null) {
sender.sendMessage(locale.getString(CommandLang.FAIL_NO_PERMISSION));
return;
}
runInspectTask(playerName, sender);
}
@ -68,13 +76,13 @@ public class QInspectCommand extends CommandNode {
try {
UUID uuid = UUIDUtility.getUUIDOf(playerName);
if (uuid == null) {
sender.sendMessage(Locale.get(Msg.CMD_FAIL_USERNAME_NOT_VALID).toString());
sender.sendMessage(locale.getString(CommandLang.FAIL_USERNAME_NOT_VALID));
return;
}
PlayerContainer container = Database.getActive().fetch().getPlayerContainer(uuid);
if (!container.getValue(PlayerKeys.REGISTERED).isPresent()) {
sender.sendMessage(Locale.get(Msg.CMD_FAIL_USERNAME_NOT_KNOWN).toString());
sender.sendMessage(locale.getString(CommandLang.FAIL_USERNAME_NOT_KNOWN));
return;
}
@ -96,36 +104,34 @@ public class QInspectCommand extends CommandNode {
private void sendMessages(ISender sender, PlayerContainer player) {
long now = System.currentTimeMillis();
ColorScheme colorScheme = plugin.getColorScheme();
String colM = colorScheme.getMainColor();
String colS = colorScheme.getSecondaryColor();
String colT = colorScheme.getTertiaryColor();
Formatter<DateHolder> timestamp = Formatters.year();
Formatter<Long> length = Formatters.timeAmount();
sender.sendMessage(Locale.get(Msg.CMD_HEADER_INSPECT).toString() + ": " + colT + player.getValue(PlayerKeys.NAME).orElse("Unknown"));
String playerName = player.getValue(PlayerKeys.NAME).orElse(locale.getString(GenericLang.UNKNOWN));
ActivityIndex activityIndex = player.getActivityIndex(now);
Long registered = player.getValue(PlayerKeys.REGISTERED).orElse(0L);
Long lastSeen = player.getValue(PlayerKeys.LAST_SEEN).orElse(0L);
List<GeoInfo> geoInfo = player.getValue(PlayerKeys.GEO_INFO).orElse(new ArrayList<>());
Optional<GeoInfo> mostRecentGeoInfo = new GeoInfoMutator(geoInfo).mostRecent();
String loginLocation = mostRecentGeoInfo.isPresent() ? mostRecentGeoInfo.get().getGeolocation() : "-";
String geolocation = mostRecentGeoInfo.isPresent() ? mostRecentGeoInfo.get().getGeolocation() : "-";
SessionsMutator sessionsMutator = SessionsMutator.forContainer(player);
sender.sendMessage(colM + " Activity Index: " + colS + activityIndex.getFormattedValue() + " | " + activityIndex.getGroup());
sender.sendMessage(colM + " Registered: " + colS + timestamp.apply(() -> registered));
sender.sendMessage(colM + " Last Seen: " + colS + timestamp.apply(() -> lastSeen));
sender.sendMessage(colM + " Logged in from: " + colS + loginLocation);
sender.sendMessage(colM + " Playtime: " + colS + length.apply(sessionsMutator.toPlaytime()));
sender.sendMessage(colM + " Longest Session: " + colS + length.apply(sessionsMutator.toLongestSessionLength()));
sender.sendMessage(colM + " Times Kicked: " + colS + player.getValue(PlayerKeys.KICK_COUNT).orElse(0));
sender.sendMessage("");
sender.sendMessage(colM + " Player Kills : " + colS + sessionsMutator.toPlayerKillCount());
sender.sendMessage(colM + " Mob Kills : " + colS + sessionsMutator.toMobKillCount());
sender.sendMessage(colM + " Deaths : " + colS + sessionsMutator.toDeathCount());
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
String[] messages = new String[]{
locale.getString(CommandLang.HEADER_INSPECT, playerName),
locale.getString(CommandLang.QINSPECT_ACTIVITY_INDEX, activityIndex.getFormattedValue(), activityIndex.getGroup()),
locale.getString(CommandLang.QINSPECT_REGISTERED, timestamp.apply(() -> registered)),
locale.getString(CommandLang.QINSPECT_LAST_SEEN, timestamp.apply(() -> lastSeen)),
locale.getString(CommandLang.QINSPECT_GEOLOCATION, geolocation),
locale.getString(CommandLang.QINSPECT_PLAYTIME, length.apply(sessionsMutator.toPlaytime())),
locale.getString(CommandLang.QINSPECT_LONGEST_SESSION, length.apply(sessionsMutator.toLongestSessionLength())),
locale.getString(CommandLang.QINSPECT_TIMES_KICKED, player.getValue(PlayerKeys.KICK_COUNT).orElse(0)),
"",
locale.getString(CommandLang.QINSPECT_PLAYER_KILLS, sessionsMutator.toPlayerKillCount()),
locale.getString(CommandLang.QINSPECT_MOB_KILLS, sessionsMutator.toMobKillCount()),
locale.getString(CommandLang.QINSPECT_DEATHS, sessionsMutator.toDeathCount()),
">"
};
sender.sendMessage(messages);
}
}

View File

@ -1,10 +1,13 @@
package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.data.WebUser;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.utilities.PassEncryptUtil;
import com.djrapitops.plugin.api.Check;
import com.djrapitops.plugin.api.utility.log.Log;
@ -33,18 +36,22 @@ public class RegisterCommand extends CommandNode {
private final String notEnoughArgsMsg;
private final String hashErrorMsg;
private final Locale locale;
public RegisterCommand() {
public RegisterCommand(PlanPlugin plugin) {
// No Permission Requirement
super("register", "", CommandType.PLAYER_OR_ARGS);
setShortHelp(Locale.get(Msg.CMD_USG_WEB_REGISTER).toString());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setArguments("<password>", "[name]", "[lvl]");
setInDepthHelp(Locale.get(Msg.CMD_HELP_WEB_REGISTER).toArray());
setShortHelp(locale.getString(CmdHelpLang.WEB_REGISTER));
setInDepthHelp(locale.getArray(DeepHelpLang.WEB_REGISTER));
if (Check.isBukkitAvailable()) {
setupFilter();
}
notEnoughArgsMsg = Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse("(3) " + Arrays.toString(getArguments()));
notEnoughArgsMsg = locale.getString(CommandLang.FAIL_REQ_ARGS, 3, Arrays.toString(getArguments()));
hashErrorMsg = "§cPassword hash error.";
}
@ -52,7 +59,6 @@ public class RegisterCommand extends CommandNode {
public void onCommand(ISender sender, String commandLabel, String[] args) {
try {
if (CommandUtils.isPlayer(sender)) {
Log.info(sender.getName() + " issued WebUser register command.");
playerRegister(args, sender);
} else {
consoleRegister(args, sender, notEnoughArgsMsg);
@ -86,7 +92,7 @@ public class RegisterCommand extends CommandNode {
} else if (sender.hasPermission(Permissions.MANAGE_WEB.getPermission())) {
consoleRegister(args, sender, notEnoughArgsMsg);
} else {
sender.sendMessage(Locale.get(Msg.CMD_FAIL_NO_PERMISSION).parse());
sender.sendMessage(locale.getString(CommandLang.FAIL_NO_PERMISSION));
}
}
@ -110,9 +116,9 @@ public class RegisterCommand extends CommandNode {
RunnableFactory.createNew(new AbsRunnable("Register WebUser Task") {
@Override
public void run() {
final String existsMsg = "§cUser Already Exists!";
final String existsMsg = locale.getString(CommandLang.FAIL_WEB_USER_EXISTS);
final String userName = webUser.getName();
final String successMsg = "§aAdded a new user (" + userName + ") successfully!";
final String successMsg = locale.getString(CommandLang.WEB_USER_REGISTER_SUCCESS);
try {
Database database = Database.getActive();
boolean userExists = database.check().doesWebUserExists(userName);
@ -122,7 +128,7 @@ public class RegisterCommand extends CommandNode {
}
database.save().webUser(webUser);
sender.sendMessage(successMsg);
Log.info("Registered new user: " + userName + " Perm level: " + webUser.getPermLevel());
Log.info(locale.getString(CommandLang.WEB_USER_REGISTER_NOTIFY, userName, webUser.getPermLevel()));
} catch (Exception e) {
Log.toLog(this.getClass(), e);
} finally {

View File

@ -1,9 +1,11 @@
package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
@ -18,11 +20,16 @@ import com.djrapitops.plugin.command.ISender;
public class ReloadCommand extends CommandNode {
private final PlanPlugin plugin;
private final Locale locale;
public ReloadCommand(PlanPlugin plugin) {
super("reload", Permissions.MANAGE.getPermission(), CommandType.CONSOLE);
setShortHelp(Locale.get(Msg.CMD_USG_RELOAD).toString());
super("reload", Permissions.RELOAD.getPermission(), CommandType.CONSOLE);
this.plugin = plugin;
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.RELOAD));
setInDepthHelp(locale.getArray(DeepHelpLang.RELOAD));
}
@Override
@ -31,8 +38,8 @@ public class ReloadCommand extends CommandNode {
plugin.reloadPlugin(true);
} catch (Exception e) {
Log.toLog(this.getClass(), e);
sender.sendMessage("§cSomething went wrong during reload of the plugin, a restart is recommended.");
sender.sendMessage(locale.getString(CommandLang.RELOAD_FAILED));
}
sender.sendMessage(Locale.get(Msg.CMD_INFO_RELOAD_COMPLETE).toString());
sender.sendMessage(locale.getString(CommandLang.RELOAD_COMPLETE));
}
}

View File

@ -1,9 +1,13 @@
package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.utilities.MiscUtils;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
@ -25,18 +29,24 @@ import java.util.List;
*/
public class SearchCommand extends CommandNode {
public SearchCommand() {
private final Locale locale;
public SearchCommand(PlanPlugin plugin) {
super("search", Permissions.SEARCH.getPermission(), CommandType.PLAYER_OR_ARGS);
setShortHelp(Locale.get(Msg.CMD_USG_SEARCH).toString());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setArguments("<text>");
setInDepthHelp(Locale.get(Msg.CMD_HELP_SEARCH).toArray());
setShortHelp(locale.getString(CmdHelpLang.SEARCH));
setInDepthHelp(locale.getArray(DeepHelpLang.SEARCH));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
Verify.isTrue(args.length >= 1, () -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString()));
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ONE_ARG, Arrays.toString(this.getArguments()))));
sender.sendMessage(Locale.get(Msg.CMD_INFO_SEARCHING).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_START));
runSearchTask(args, sender);
}
@ -46,19 +56,18 @@ public class SearchCommand extends CommandNode {
@Override
public void run() {
try {
List<String> names = MiscUtils.getMatchingPlayerNames(args[0]);
String searchTerm = args[0];
List<String> names = MiscUtils.getMatchingPlayerNames(searchTerm);
boolean empty = Verify.isEmpty(names);
sender.sendMessage(Locale.get(Msg.CMD_HEADER_SEARCH) + args[0] + " (" + (empty ? 0 : names.size()) + ")");
sender.sendMessage(locale.getString(CommandLang.HEADER_SEARCH, empty ? 0 : names.size(), searchTerm));
// Results
if (empty) {
sender.sendMessage(Locale.get(Msg.CMD_INFO_NO_RESULTS).parse(Arrays.toString(args)));
} else {
sender.sendMessage(Locale.get(Msg.CMD_INFO_RESULTS).toString() + FormatUtils.collectionToStringNoBrackets(names));
if (!empty) {
sender.sendMessage(FormatUtils.collectionToStringNoBrackets(names));
}
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
sender.sendMessage(">");
} catch (DBOpException e) {
sender.sendMessage("§cDatabase error occurred: " + e.getMessage());
Log.toLog(this.getClass(), e);

View File

@ -1,5 +1,6 @@
package com.djrapitops.plan.command.commands;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.api.exceptions.connection.*;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.command.commands.manage.ManageConDebugCommand;
@ -9,9 +10,12 @@ import com.djrapitops.plan.system.info.InfoSystem;
import com.djrapitops.plan.system.info.request.UpdateCancelRequest;
import com.djrapitops.plan.system.info.request.UpdateRequest;
import com.djrapitops.plan.system.info.server.Server;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.system.update.VersionCheckSystem;
import com.djrapitops.plan.system.update.VersionInfo;
import com.djrapitops.plan.system.webserver.WebServerSystem;
@ -35,23 +39,22 @@ import java.util.UUID;
*/
public class UpdateCommand extends CommandNode {
public UpdateCommand() {
private final Locale locale;
public UpdateCommand(PlanPlugin plugin) {
super("update", Permissions.MANAGE.getPermission(), CommandType.ALL);
locale = plugin.getSystem().getLocaleSystem().getLocale();
setArguments("[-u]/[cancel]");
setShortHelp("Get change log link or update plugin.");
setInDepthHelp(
"/plan update",
" Used to update the plugin on the next shutdown\n",
" /plan update - get change log link",
" /plan update -u - Schedule update to happen on all network servers that are online next time they reboot.",
" /plan update cancel - Cancel scheduled update on servers that haven't rebooted yet."
);
setShortHelp(locale.getString(CmdHelpLang.UPDATE));
setInDepthHelp(locale.getArray(DeepHelpLang.UPDATE));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
if (!VersionCheckSystem.isNewVersionAvailable()) {
sender.sendMessage("§aYou're running the latest version of Plan.");
sender.sendMessage("§a" + locale.getString(PluginLang.VERSION_NEWEST));
return;
}
@ -59,21 +62,19 @@ public class UpdateCommand extends CommandNode {
String downloadUrl = available.getDownloadUrl();
if (!available.isTrusted()) {
sender.sendMessage("§cVersion download url did not start with " +
"https://github.com/Rsl1122/Plan-PlayerAnalytics/releases/ " +
"and might not be trusted. You can download this version manually here (Direct download):");
sender.sendMessage(locale.getString(CommandLang.UPDATE_WRONG_URL, "https://github.com/Rsl1122/Plan-PlayerAnalytics/releases/"));
sender.sendLink(downloadUrl, downloadUrl);
return;
}
if (args.length == 0) {
String message = "Change Log v" + available.getVersion().toString() + ": ";
String message = locale.getString(CommandLang.UPDATE_CHANGE_LOG, available.getVersion().toString());
String url = available.getChangeLogUrl();
if (CommandUtils.isConsole(sender)) {
sender.sendMessage(message + url);
} else {
sender.sendMessage(message);
sender.sendLink(" ", Locale.get(Msg.CMD_INFO_CLICK_ME).toString(), url);
sender.sendLink(" ", locale.getString(CommandLang.LINK_CLICK_ME), url);
}
return;
}
@ -100,7 +101,7 @@ public class UpdateCommand extends CommandNode {
private void handleCancel(ISender sender) {
try {
cancel(sender, Database.getActive().fetch().getServers());
sender.sendMessage("§aCancel operation performed.");
sender.sendMessage(locale.getString(CommandLang.UPDATE_CANCEL_SUCCESS));
} catch (DBOpException e) {
sender.sendMessage("§cDatabase error occurred, cancel could not be performed.");
Log.toLog(this.getClass().getName(), e);
@ -108,10 +109,10 @@ public class UpdateCommand extends CommandNode {
}
private void handleUpdate(ISender sender, String[] args) {
sender.sendMessage("§aYou can cancel the update on servers that haven't rebooted yet with /plan update cancel.");
sender.sendMessage("Checking that all servers are online..");
sender.sendMessage(locale.getString(CommandLang.UPDATE_NOTIFY_CANCEL));
sender.sendMessage(locale.getString(CommandLang.UPDATE_ONLINE_CHECK));
if (!checkNetworkStatus(sender)) {
sender.sendMessage("§cNot all servers were online or accessible, you can still update available servers using /plan -update -force");
sender.sendMessage(locale.getString(CommandLang.UPDATE_FAIL_NOT_ONLINE));
// If -force, continue, otherwise return.
if (args.length < 2 || !"-force".equals(args[1])) {
return;
@ -128,15 +129,15 @@ public class UpdateCommand extends CommandNode {
private void update(ISender sender, List<Server> servers, String[] args) {
for (Server server : servers) {
if (update(sender, server)) {
sender.sendMessage("§a" + server.getName() + " scheduled for update.");
sender.sendMessage(locale.getString(CommandLang.UPDATE_SCHEDULED, server.getName()));
} else {
if (args.length > 1 && "-force".equals(args[1])) {
sender.sendMessage("§e" + server.getName() + " failed to update, -force specified, continuing update.");
sender.sendMessage(locale.getString(CommandLang.UPDATE_FAIL_FORCED));
continue;
}
sender.sendMessage("§cUpdate failed on a server, cancelling update on all servers..");
sender.sendMessage(locale.getString(CommandLang.UPDATE_FAIL_CANCEL));
cancel(sender, servers);
sender.sendMessage("§cUpdate cancelled.");
sender.sendMessage(locale.getString(CommandLang.UPDATE_CANCELLED));
break;
}
}
@ -146,7 +147,6 @@ public class UpdateCommand extends CommandNode {
for (Server server : servers) {
cancel(sender, server);
}
}
private void cancel(ISender sender, Server server) {
@ -219,12 +219,12 @@ public class UpdateCommand extends CommandNode {
String accessAddress = WebServerSystem.getInstance().getWebServer().getAccessAddress();
boolean success = true;
for (Server server : bukkitServers.values()) {
if (!ManageConDebugCommand.testServer(sender, accessAddress, server)) {
if (!ManageConDebugCommand.testServer(sender, accessAddress, server, locale)) {
success = false;
}
}
Server bungee = bungeeInformation.get();
if (!ManageConDebugCommand.testServer(sender, accessAddress, bungee)) {
if (!ManageConDebugCommand.testServer(sender, accessAddress, bungee, locale)) {
success = false;
}
return success;

View File

@ -5,9 +5,10 @@ import com.djrapitops.plan.command.commands.webuser.WebCheckCommand;
import com.djrapitops.plan.command.commands.webuser.WebDeleteCommand;
import com.djrapitops.plan.command.commands.webuser.WebLevelCommand;
import com.djrapitops.plan.command.commands.webuser.WebListUsersCommand;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.TreeCmdNode;
@ -22,16 +23,19 @@ public class WebUserCommand extends TreeCmdNode {
public WebUserCommand(PlanPlugin plugin, RegisterCommand register, CommandNode parent) {
super("webuser|web", Permissions.MANAGE_WEB.getPerm(), CommandType.CONSOLE, parent);
setShortHelp(Locale.get(Msg.CMD_USG_WEB).toString());
super.setColorScheme(plugin.getColorScheme());
setInDepthHelp(Locale.get(Msg.CMD_HELP_WEB).toArray());
Locale locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.WEB));
setInDepthHelp(locale.getArray(DeepHelpLang.WEB));
setNodeGroups(
new CommandNode[]{
register,
new WebLevelCommand(plugin),
new WebListUsersCommand(plugin),
new WebCheckCommand(),
new WebDeleteCommand()
new WebCheckCommand(plugin),
new WebDeleteCommand(plugin)
}
);
}

View File

@ -1,14 +1,18 @@
package com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.api.exceptions.database.DBException;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.data.store.mutators.formatting.Formatters;
import com.djrapitops.plan.system.database.DBSystem;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.database.databases.sql.SQLiteDB;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
@ -29,9 +33,15 @@ import java.util.UUID;
*/
public class ManageBackupCommand extends CommandNode {
public ManageBackupCommand() {
private final Locale locale;
public ManageBackupCommand(PlanPlugin plugin) {
super("backup", Permissions.MANAGE.getPermission(), CommandType.CONSOLE);
setShortHelp(Locale.get(Msg.CMD_USG_MANAGE_BACKUP).toString());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.MANAGE_BACKUP));
setInDepthHelp(locale.getArray(DeepHelpLang.MANAGE_BACKUP));
setArguments("<DB>");
}
@ -40,21 +50,19 @@ public class ManageBackupCommand extends CommandNode {
public void onCommand(ISender sender, String commandLabel, String[] args) {
try {
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse(Arrays.toString(this.getArguments()))));
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ONE_ARG, Arrays.toString(this.getArguments()))));
String dbName = args[0].toLowerCase();
boolean isCorrectDB = Verify.equalsOne(dbName, "sqlite", "mysql");
Verify.isTrue(isCorrectDB,
() -> new IllegalArgumentException(Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + dbName));
() -> new IllegalArgumentException(locale.getString(ManageLang.FAIL_INCORRECT_DB, dbName)));
Database database = DBSystem.getActiveDatabaseByName(dbName);
Verify.nullCheck(database, NullPointerException::new);
runBackupTask(sender, args, database);
} catch (DBInitException | NullPointerException e) {
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString());
} catch (DBInitException e) {
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
}
}
@ -64,12 +72,12 @@ public class ManageBackupCommand extends CommandNode {
public void run() {
try {
Log.debug("Backup", "Start");
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_START));
createNewBackup(args[0], database);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_COPY_SUCCESS).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_SUCCESS));
} catch (Exception e) {
Log.toLog(ManageBackupCommand.class, e);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
} finally {
Log.logDebug("Backup");
this.cancel();
@ -89,7 +97,7 @@ public class ManageBackupCommand extends CommandNode {
try {
String timeStamp = Formatters.iso8601NoClock().apply(System::currentTimeMillis);
String fileName = dbName + "-backup-" + timeStamp;
backupDB = new SQLiteDB(fileName);
backupDB = new SQLiteDB(fileName, () -> locale);
Collection<UUID> uuids = copyFromDB.fetch().getSavedUUIDs();
if (uuids.isEmpty()) {
return;

View File

@ -1,12 +1,16 @@
package com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.system.database.DBSystem;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
@ -15,6 +19,8 @@ import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.RunnableFactory;
import com.djrapitops.plugin.utilities.Verify;
import java.util.Arrays;
/**
* This manage SubCommand is used to clear a database of all data.
*
@ -23,27 +29,31 @@ import com.djrapitops.plugin.utilities.Verify;
*/
public class ManageClearCommand extends CommandNode {
public ManageClearCommand() {
super("clear", Permissions.MANAGE.getPermission(), CommandType.PLAYER_OR_ARGS);
setShortHelp(Locale.get(Msg.CMD_USG_MANAGE_CLEAR).toString());
setArguments("<DB>", "[-a]");
setInDepthHelp(Locale.get(Msg.CMD_HELP_MANAGE_CLEAR).toArray());
private final Locale locale;
public ManageClearCommand(PlanPlugin plugin) {
super("clear", Permissions.MANAGE.getPermission(), CommandType.PLAYER_OR_ARGS);
locale = plugin.getSystem().getLocaleSystem().getLocale();
setArguments("<DB>", "[-a]");
setShortHelp(locale.getString(CmdHelpLang.MANAGE_CLEAR));
setInDepthHelp(locale.getArray(DeepHelpLang.MANAGE_CLEAR));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString()));
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ONE_ARG, Arrays.toString(this.getArguments()))));
String dbName = args[0].toLowerCase();
boolean isCorrectDB = "sqlite".equals(dbName) || "mysql".equals(dbName);
Verify.isTrue(isCorrectDB,
() -> new IllegalArgumentException(Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + dbName));
() -> new IllegalArgumentException(locale.getString(ManageLang.FAIL_INCORRECT_DB, dbName)));
if (!Verify.contains("-a", args)) {
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_CONFIRM).parse(Locale.get(Msg.MANAGE_NOTIFY_REMOVE).parse(args[0])));
sender.sendMessage(locale.getString(ManageLang.CONFIRMATION, locale.getString(ManageLang.CONFIRM_REMOVAL, dbName)));
return;
}
@ -51,7 +61,7 @@ public class ManageClearCommand extends CommandNode {
Database database = DBSystem.getActiveDatabaseByName(dbName);
runClearTask(sender, database);
} catch (DBInitException e) {
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
}
}
@ -60,18 +70,13 @@ public class ManageClearCommand extends CommandNode {
@Override
public void run() {
try {
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_START));
database.remove().everything();
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_CLEAR_SUCCESS).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_SUCCESS));
} catch (DBOpException e) {
if (e.isFatal()) {
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString()
+ " Error was fatal, so all information may not have been removed.");
} else {
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
}
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
Log.toLog(this.getClass(), e);
} finally {
this.cancel();

View File

@ -7,9 +7,15 @@ import com.djrapitops.plan.system.info.InfoSystem;
import com.djrapitops.plan.system.info.request.CheckConnectionRequest;
import com.djrapitops.plan.system.info.server.Server;
import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.processing.Processing;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.webserver.WebServerSystem;
import com.djrapitops.plugin.api.Check;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
@ -26,39 +32,18 @@ import java.util.UUID;
*/
public class ManageConDebugCommand extends CommandNode {
public ManageConDebugCommand() {
private final Locale locale;
public ManageConDebugCommand(PlanPlugin plugin) {
super("con", Permissions.MANAGE.getPermission(), CommandType.ALL);
setShortHelp("Debug Bukkit-Bungee Connections");
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(Check.isBungeeAvailable() ? CmdHelpLang.CON : CmdHelpLang.MANAGE_CON));
setInDepthHelp(locale.getArray(DeepHelpLang.MANAGE_CON));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
if (!WebServerSystem.isWebServerEnabled()) {
sender.sendMessage("§cWebServer is not enabled on this server.");
return;
}
Processing.submitNonCritical(() -> testServers(sender));
}
private void testServers(ISender sender) {
List<Server> servers = Database.getActive().fetch().getServers();
if (servers.isEmpty()) {
sender.sendMessage("§cNo Servers found in the database.");
}
String accessAddress = WebServerSystem.getInstance().getWebServer().getAccessAddress();
UUID thisServer = ServerInfo.getServerUUID();
for (Server server : servers) {
if (thisServer.equals(server.getUuid())) {
continue;
}
testServer(sender, accessAddress, server);
}
}
public static boolean testServer(ISender sender, String accessAddress, Server server) {
public static boolean testServer(ISender sender, String accessAddress, Server server, Locale locale) {
String address = server.getWebAddress().toLowerCase();
boolean usingHttps = address.startsWith("https");
boolean local = address.contains("localhost")
@ -74,28 +59,55 @@ public class ManageConDebugCommand extends CommandNode {
} catch (ForbiddenException | BadRequestException | InternalErrorException e) {
sender.sendMessage(getMsgFor(address, usingHttps, local, false, false));
sender.sendMessage("§eOdd Exception: " + e.getClass().getSimpleName());
sender.sendMessage(locale.getString(ManageLang.CON_EXCEPTION, e.getClass().getSimpleName()));
} catch (UnauthorizedServerException e) {
sender.sendMessage(getMsgFor(address, usingHttps, local, true, false));
sender.sendMessage("§eFail reason: Unauthorized. Server might be using different database.");
sender.sendMessage(locale.getString(ManageLang.CON_UNAUTHORIZED));
} catch (ConnectionFailException e) {
sender.sendMessage(getMsgFor(address, usingHttps, local, false, false));
sender.sendMessage("§eFail reason: " + e.getCause().getClass().getSimpleName() + " " + e.getCause().getMessage());
sender.sendMessage(locale.getString(ManageLang.CON_GENERIC_FAIL) + e.getCause().getClass().getSimpleName() + " " + e.getCause().getMessage());
if (!local) {
sender.sendMessage("§eNon-local address, check that port is open");
sender.sendMessage(locale.getString(ManageLang.CON_EXTERNAL_URL));
}
} catch (GatewayException e) {
sender.sendMessage(getMsgFor(address, usingHttps, local, true, false));
} catch (NotFoundException e) {
sender.sendMessage(getMsgFor(address, usingHttps, local, false, false));
sender.sendMessage("§eFail reason: Older Plan version on receiving server");
sender.sendMessage(locale.getString(ManageLang.CON_OLD_VERSION));
} catch (WebException e) {
sender.sendMessage(getMsgFor(address, usingHttps, local, false, false));
sender.sendMessage("§eOdd Exception: " + e.getClass().getSimpleName());
sender.sendMessage(locale.getString(ManageLang.CON_EXCEPTION, e.getClass().getSimpleName()));
}
return false;
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
if (!WebServerSystem.isWebServerEnabled()) {
sender.sendMessage(locale.getString(CommandLang.CONNECT_WEBSERVER_NOT_ENABLED));
return;
}
Processing.submitNonCritical(() -> testServers(sender));
}
private void testServers(ISender sender) {
List<Server> servers = Database.getActive().fetch().getServers();
if (servers.isEmpty()) {
sender.sendMessage(locale.getString(ManageLang.CON_NO_SERVERS));
}
String accessAddress = WebServerSystem.getInstance().getWebServer().getAccessAddress();
UUID thisServer = ServerInfo.getServerUUID();
for (Server server : servers) {
if (thisServer.equals(server.getUuid())) {
continue;
}
testServer(sender, accessAddress, server, locale);
}
}
private static String getMsgFor(String address, boolean usingHttps, boolean local, boolean successTo, boolean successFrom) {
ColorScheme cs = PlanPlugin.getInstance().getColorScheme();
String tCol = cs.getTertiaryColor();

View File

@ -1,9 +1,12 @@
package com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.listeners.bukkit.PlayerOnlineListener;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
@ -18,27 +21,31 @@ import java.util.Arrays;
* @since 4.0.4
*/
public class ManageDisableCommand extends CommandNode {
/**
* Class Constructor.
*/
public ManageDisableCommand() {
private final Locale locale;
public ManageDisableCommand(PlanPlugin plugin) {
super("disable", Permissions.MANAGE.getPermission(), CommandType.PLAYER_OR_ARGS);
setShortHelp("Disable a feature temporarily");
locale = plugin.getSystem().getLocaleSystem().getLocale();
setArguments("<feature>");
setShortHelp(locale.getString(CmdHelpLang.MANAGE_DISABLE));
setInDepthHelp(locale.getArray(DeepHelpLang.MANAGE_DISABLE));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse(Arrays.toString(this.getArguments()))));
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ONE_ARG, Arrays.toString(this.getArguments()))));
switch (args[0].toLowerCase()) {
case "kickcount":
PlayerOnlineListener.setCountKicks(false);
sender.sendMessage("§aDisabled Kick Counting temporarily until next plugin reload.");
sender.sendMessage(locale.getString(CommandLang.FEATURE_DISABLED, "Kick Counting"));
break;
default:
sender.sendMessage("§eDefine a feature to disable! (currently supports only kickCount)");
sender.sendMessage(locale.getString(CommandLang.FAIL_NO_SUCH_FEATURE, "'kickcount'"));
}
}
}

View File

@ -3,16 +3,20 @@ package com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.database.DBSystem;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.utilities.Verify;
import java.util.Arrays;
/**
* This manage SubCommand is used to swap to a different database and reload the
* plugin if the connection to the new database can be established.
@ -23,44 +27,41 @@ import com.djrapitops.plugin.utilities.Verify;
public class ManageHotSwapCommand extends CommandNode {
private final PlanPlugin plugin;
private final Locale locale;
public ManageHotSwapCommand(PlanPlugin plugin) {
super("hotswap", Permissions.MANAGE.getPermission(), CommandType.PLAYER_OR_ARGS);
setShortHelp(Locale.get(Msg.CMD_USG_MANAGE_HOTSWAP).toString());
setArguments("<DB>");
setInDepthHelp(Locale.get(Msg.CMD_HELP_MANAGE_HOTSWAP).toArray());
this.plugin = plugin;
locale = plugin.getSystem().getLocaleSystem().getLocale();
setArguments("<DB>");
setShortHelp(locale.getString(CmdHelpLang.MANAGE_HOTSWAP));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString()));
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ONE_ARG, Arrays.toString(this.getArguments()))));
String dbName = args[0].toLowerCase();
boolean isCorrectDB = Verify.equalsOne(dbName, "sqlite", "mysql");
Verify.isTrue(isCorrectDB,
() -> new IllegalArgumentException(Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + dbName));
() -> new IllegalArgumentException(locale.getString(ManageLang.FAIL_INCORRECT_DB, dbName)));
Verify.isFalse(dbName.equals(Database.getActive().getConfigName()),
() -> new IllegalArgumentException(Locale.get(Msg.MANAGE_FAIL_SAME_DB).toString()));
() -> new IllegalArgumentException(locale.getString(ManageLang.FAIL_SAME_DB)));
try {
final Database database = DBSystem.getActiveDatabaseByName(dbName);
Verify.nullCheck(database, NullPointerException::new);
Database database = DBSystem.getActiveDatabaseByName(dbName);
if (!database.isOpen()) {
return;
}
} catch (NullPointerException e) {
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString());
return;
} catch (Exception e) {
Log.toLog(this.getClass(), e);
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
return;
}

View File

@ -1,10 +1,14 @@
package com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.processing.importing.ImporterManager;
import com.djrapitops.plan.system.processing.importing.importers.Importer;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
@ -22,22 +26,27 @@ import java.util.Arrays;
*/
public class ManageImportCommand extends CommandNode {
public ManageImportCommand() {
private final Locale locale;
public ManageImportCommand(PlanPlugin plugin) {
super("import", Permissions.MANAGE.getPermission(), CommandType.CONSOLE);
setShortHelp(Locale.get(Msg.CMD_USG_MANAGE_IMPORT).toString());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setArguments("<plugin>/list", "[import args]");
setInDepthHelp(Locale.get(Msg.CMD_HELP_MANAGE_IMPORT).toArray());
setShortHelp(locale.getString(CmdHelpLang.MANAGE_IMPORT));
setInDepthHelp(locale.getArray(DeepHelpLang.MANAGE_IMPORT));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse(Arrays.toString(this.getArguments()))));
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ARGS, "1+", Arrays.toString(this.getArguments()))));
String importArg = args[0];
if (importArg.equals("list")) {
sender.sendMessage("Importers: ");
sender.sendMessage(locale.getString(ManageLang.IMPORTERS));
ImporterManager.getImporters().stream()
.map(Importer::getNames)
.map(list -> list.get(0))
@ -47,7 +56,7 @@ public class ManageImportCommand extends CommandNode {
Importer importer = ImporterManager.getImporter(importArg);
if (importer == null) {
sender.sendMessage("§eImporter '" + importArg + "' doesn't exist");
sender.sendMessage(locale.getString(ManageLang.FAIL_IMPORTER_NOT_FOUND, importArg));
return;
}

View File

@ -1,10 +1,14 @@
package com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.database.DBSystem;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
@ -25,32 +29,38 @@ import java.util.Arrays;
*/
public class ManageMoveCommand extends CommandNode {
public ManageMoveCommand() {
private final Locale locale;
public ManageMoveCommand(PlanPlugin plugin) {
super("move", Permissions.MANAGE.getPermission(), CommandType.PLAYER_OR_ARGS);
setShortHelp(Locale.get(Msg.CMD_USG_MANAGE_MOVE).toString());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setArguments("<fromDB>", "<toDB>", "[-a]");
setShortHelp(locale.getString(CmdHelpLang.MANAGE_MOVE));
setInDepthHelp(locale.getArray(DeepHelpLang.MANAGE_MOVE));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
Verify.isTrue(args.length >= 2,
() -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse(Arrays.toString(this.getArguments()))));
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ARGS, 2, Arrays.toString(this.getArguments()))));
String fromDB = args[0].toLowerCase();
boolean isCorrectDB = Verify.equalsOne(fromDB, "sqlite", "mysql");
Verify.isTrue(isCorrectDB,
() -> new IllegalArgumentException(Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + fromDB));
() -> new IllegalArgumentException(locale.getString(ManageLang.FAIL_INCORRECT_DB, fromDB)));
String toDB = args[1].toLowerCase();
isCorrectDB = Verify.equalsOne(toDB, "sqlite", "mysql");
Verify.isTrue(isCorrectDB,
() -> new IllegalArgumentException(Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + fromDB));
() -> new IllegalArgumentException(locale.getString(ManageLang.FAIL_INCORRECT_DB, toDB)));
Verify.isFalse(fromDB.equalsIgnoreCase(toDB),
() -> new IllegalArgumentException(Locale.get(Msg.MANAGE_FAIL_SAME_DB).toString()));
() -> new IllegalArgumentException(locale.getString(ManageLang.FAIL_SAME_DB)));
if (!Verify.contains("-a", args)) {
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_CONFIRM).parse(Locale.get(Msg.MANAGE_NOTIFY_OVERWRITE).parse(args[0])));
sender.sendMessage(locale.getString(ManageLang.CONFIRMATION, locale.getString(ManageLang.CONFIRM_OVERWRITE, toDB)));
return;
}
@ -60,7 +70,7 @@ public class ManageMoveCommand extends CommandNode {
runMoveTask(fromDatabase, toDatabase, sender);
} catch (Exception e) {
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
}
}
@ -69,19 +79,19 @@ public class ManageMoveCommand extends CommandNode {
@Override
public void run() {
try {
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_START));
fromDatabase.backup().backup(toDatabase);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_MOVE_SUCCESS).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_SUCCESS));
boolean movingToCurrentDB = toDatabase.getConfigName().equalsIgnoreCase(Database.getActive().getConfigName());
if (movingToCurrentDB) {
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_CONFIG_REMINDER).toString());
sender.sendMessage(locale.getString(ManageLang.HOTSWAP_REMINDER, toDatabase.getConfigName()));
}
} catch (Exception e) {
Log.toLog(this.getClass(), e);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
} finally {
this.cancel();
}

View File

@ -1,10 +1,14 @@
package com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.utilities.MiscUtils;
import com.djrapitops.plan.utilities.uuid.UUIDUtility;
import com.djrapitops.plugin.api.utility.log.Log;
@ -15,6 +19,7 @@ import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.RunnableFactory;
import com.djrapitops.plugin.utilities.Verify;
import java.util.Arrays;
import java.util.UUID;
/**
@ -25,20 +30,30 @@ import java.util.UUID;
*/
public class ManageRemoveCommand extends CommandNode {
public ManageRemoveCommand() {
private final Locale locale;
public ManageRemoveCommand(PlanPlugin plugin) {
super("remove|delete", Permissions.MANAGE.getPermission(), CommandType.PLAYER_OR_ARGS);
setShortHelp(Locale.get(Msg.CMD_USG_MANAGE_REMOVE).toString());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setArguments("<player>", "[-a]");
setInDepthHelp(Locale.get(Msg.CMD_HELP_MANAGE_REMOVE).toArray());
setShortHelp(locale.getString(CmdHelpLang.MANAGE_REMOVE));
setInDepthHelp(locale.getArray(DeepHelpLang.MANAGE_REMOVE));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString()));
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ONE_ARG, Arrays.toString(this.getArguments()))));
String playerName = MiscUtils.getPlayerName(args, sender, Permissions.MANAGE);
if (playerName == null) {
sender.sendMessage(locale.getString(CommandLang.FAIL_NO_PERMISSION));
return;
}
runRemoveTask(playerName, sender, args);
}
@ -50,29 +65,29 @@ public class ManageRemoveCommand extends CommandNode {
UUID uuid = UUIDUtility.getUUIDOf(playerName);
if (uuid == null) {
sender.sendMessage(Locale.get(Msg.CMD_FAIL_USERNAME_NOT_VALID).toString());
sender.sendMessage(locale.getString(CommandLang.FAIL_USERNAME_NOT_VALID));
return;
}
Database database = Database.getActive();
if (!database.check().isPlayerRegistered(uuid)) {
sender.sendMessage(Locale.get(Msg.CMD_FAIL_USERNAME_NOT_KNOWN).toString());
sender.sendMessage(locale.getString(CommandLang.FAIL_USERNAME_NOT_KNOWN));
return;
}
if (!Verify.contains("-a", args)) {
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_CONFIRM).parse(Locale.get(Msg.MANAGE_NOTIFY_REMOVE).parse(database.getName())));
sender.sendMessage(locale.getString(ManageLang.CONFIRMATION, locale.getString(ManageLang.CONFIRM_REMOVAL, database.getName())));
return;
}
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_START));
database.remove().player(uuid);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_REMOVE_SUCCESS).parse(playerName, Database.getActive().getConfigName()));
sender.sendMessage(locale.getString(ManageLang.PROGRESS_SUCCESS));
} catch (DBOpException e) {
Log.toLog(this.getClass(), e);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
} finally {
this.cancel();
}

View File

@ -4,9 +4,12 @@ import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.database.DBSystem;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.database.databases.sql.SQLiteDB;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
@ -27,51 +30,59 @@ import java.util.Arrays;
public class ManageRestoreCommand extends CommandNode {
private final PlanPlugin plugin;
private final Locale locale;
public ManageRestoreCommand(PlanPlugin plugin) {
super("restore", Permissions.MANAGE.getPermission(), CommandType.CONSOLE);
setShortHelp(Locale.get(Msg.CMD_USG_MANAGE_RESTORE).toString());
setArguments("<Filename.db>", "<dbTo>", "[-a]");
this.plugin = plugin;
locale = plugin.getSystem().getLocaleSystem().getLocale();
setArguments("<Filename.db>", "<dbTo>", "[-a]");
setShortHelp(locale.getString(CmdHelpLang.MANAGE_RESTORE));
setInDepthHelp(locale.getArray(DeepHelpLang.MANAGE_RESTORE));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
Verify.isTrue(args.length >= 2,
() -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse(Arrays.toString(this.getArguments()))));
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ARGS, 2, Arrays.toString(this.getArguments()))));
String db = args[1].toLowerCase();
boolean isCorrectDB = Verify.equalsOne(db, "sqlite", "mysql");
String backupDbName = args[0];
String dbName = args[1].toLowerCase();
boolean isCorrectDB = Verify.equalsOne(dbName, "sqlite", "mysql");
Verify.isTrue(isCorrectDB,
() -> new IllegalArgumentException(Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB).toString()));
if (!Verify.contains("-a", args)) {
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_CONFIRM).parse(Locale.get(Msg.MANAGE_NOTIFY_REWRITE).parse(args[1])));
return;
}
() -> new IllegalArgumentException(locale.getString(ManageLang.FAIL_INCORRECT_DB, dbName)));
try {
final Database database = DBSystem.getActiveDatabaseByName(db);
Database database = DBSystem.getActiveDatabaseByName(dbName);
Verify.isFalse(backupDbName.contains("database") && database instanceof SQLiteDB,
() -> new IllegalArgumentException(locale.getString(ManageLang.FAIL_SAME_DB)));
runRestoreTask(args, sender, database);
if (!Verify.contains("-a", args)) {
sender.sendMessage(locale.getString(ManageLang.CONFIRMATION, locale.getString(ManageLang.CONFIRM_OVERWRITE, database.getName())));
return;
}
runRestoreTask(backupDbName, sender, database);
} catch (Exception e) {
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
}
}
private void runRestoreTask(String[] args, ISender sender, final Database database) {
private void runRestoreTask(String backupDbName, ISender sender, final Database database) {
RunnableFactory.createNew(new AbsRunnable("RestoreTask") {
@Override
public void run() {
try {
String backupDBName = args[0];
String backupDBName = backupDbName;
boolean containsDBFileExtension = backupDBName.endsWith(".db");
File backupDBFile = new File(plugin.getDataFolder(), backupDBName + (containsDBFileExtension ? "" : ".db"));
if (!backupDBFile.exists()) {
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_FILE_NOT_FOUND) + " " + args[0]);
sender.sendMessage(locale.getString(ManageLang.FAIL_FILE_NOT_FOUND, backupDBFile.getAbsolutePath()));
return;
}
@ -79,17 +90,17 @@ public class ManageRestoreCommand extends CommandNode {
backupDBName = backupDBName.substring(0, backupDBName.length() - 3);
}
SQLiteDB backupDB = new SQLiteDB(backupDBName);
SQLiteDB backupDB = new SQLiteDB(backupDBName, () -> locale);
backupDB.init();
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_START));
database.backup().restore(backupDB);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_COPY_SUCCESS).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_SUCCESS));
} catch (Exception e) {
Log.toLog(this.getClass(), e);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
} finally {
this.cancel();
}

View File

@ -1,12 +1,15 @@
package com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.api.exceptions.connection.*;
import com.djrapitops.plan.system.info.InfoSystem;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.DeepHelpLang;
import com.djrapitops.plan.system.processing.Processing;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.system.webserver.WebServerSystem;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
@ -14,6 +17,8 @@ import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.utilities.Verify;
import java.util.Arrays;
/**
* This manage SubCommand is used to request settings from Bungee so that connection can be established.
*
@ -22,25 +27,30 @@ import com.djrapitops.plugin.utilities.Verify;
*/
public class ManageSetupCommand extends CommandNode {
public ManageSetupCommand() {
private final Locale locale;
public ManageSetupCommand(PlanPlugin plugin) {
super("setup", Permissions.MANAGE.getPermission(), CommandType.PLAYER_OR_ARGS);
setShortHelp("Set-Up Bungee connection");
locale = plugin.getSystem().getLocaleSystem().getLocale();
setArguments("<BungeeAddress>");
setInDepthHelp(Locale.get(Msg.CMD_HELP_MANAGE_HOTSWAP).toArray());
setShortHelp(locale.getString(CmdHelpLang.MANAGE_SETUP));
setInDepthHelp(locale.getArray(DeepHelpLang.MANAGE_SETUP));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString()));
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ONE_ARG, Arrays.toString(this.getArguments()))));
if (!WebServerSystem.isWebServerEnabled()) {
sender.sendMessage("§cWebServer is not enabled on this server! Make sure it enables on boot!");
sender.sendMessage(locale.getString(CommandLang.CONNECT_WEBSERVER_NOT_ENABLED));
return;
}
String address = args[0].toLowerCase();
if (!address.startsWith("http") || address.endsWith("://")) {
sender.sendMessage("§cMake sure you're using the full address (Starts with http:// or https://) - Check Bungee enable log for the full address.");
sender.sendMessage(locale.getString(CommandLang.CONNECT_URL_MISTAKE));
return;
}
if (address.endsWith("/")) {
@ -58,22 +68,22 @@ public class ManageSetupCommand extends CommandNode {
InfoSystem.getInstance().requestSetUp(address);
sender.sendMessage("§aConnection successful, Plan may restart in a few seconds..");
sender.sendMessage(locale.getString(CommandLang.CONNECT_SUCCESS));
} catch (ForbiddenException e) {
sender.sendMessage("§eConnection succeeded, but Bungee has set-up mode disabled - use '/planbungee setup' to enable it.");
sender.sendMessage(locale.getString(CommandLang.CONNECT_FORBIDDEN));
} catch (BadRequestException e) {
sender.sendMessage("§eConnection succeeded, but Receiving server was a Bukkit server. Use Bungee address instead.");
sender.sendMessage(locale.getString(CommandLang.CONNECT_BAD_REQUEST));
} catch (UnauthorizedServerException e) {
sender.sendMessage("§eConnection succeeded, but Receiving server didn't authorize this server. Contact Discord for support");
sender.sendMessage(locale.getString(CommandLang.CONNECT_UNAUTHORIZED));
} catch (ConnectionFailException e) {
sender.sendMessage("§eConnection failed: " + e.getMessage());
sender.sendMessage(locale.getString(CommandLang.CONNECT_FAIL, e.getMessage()));
} catch (InternalErrorException e) {
sender.sendMessage("§eConnection succeeded. " + e.getMessage() + ", check possible ErrorLog on receiving server's debug page.");
sender.sendMessage(locale.getString(CommandLang.CONNECT_INTERNAL_ERROR, e.getMessage()));
} catch (GatewayException e) {
sender.sendMessage("§eConnection succeeded, but Bungee failed to connect to this server. Use Connection debug commands for more.");
sender.sendMessage(locale.getString(CommandLang.CONNECT_GATEWAY));
} catch (WebException e) {
Log.toLog(this.getClass(), e);
sender.sendMessage("§cConnection to Bungee WebServer failed: More info in the error log.");
sender.sendMessage(locale.getString(CommandLang.CONNECT_FAIL, e.toString()));
}
});
}

View File

@ -1,10 +1,13 @@
package com.djrapitops.plan.command.commands.webuser;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.data.WebUser;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
@ -23,16 +26,21 @@ import java.util.Arrays;
*/
public class WebCheckCommand extends CommandNode {
public WebCheckCommand() {
private final Locale locale;
public WebCheckCommand(PlanPlugin plugin) {
super("check", Permissions.MANAGE_WEB.getPerm(), CommandType.PLAYER_OR_ARGS);
setShortHelp(Locale.get(Msg.CMD_USG_WEB_CHECK).toString());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.WEB_CHECK));
setArguments("<username>");
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse(Arrays.toString(this.getArguments()))));
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ONE_ARG, Arrays.toString(this.getArguments()))));
Database database = Database.getActive();
String user = args[0];
@ -42,14 +50,14 @@ public class WebCheckCommand extends CommandNode {
public void run() {
try {
if (!database.check().doesWebUserExists(user)) {
sender.sendMessage("§c[Plan] User Doesn't exist.");
sender.sendMessage(locale.getString(CommandLang.FAIL_WEB_USER_NOT_EXISTS));
return;
}
WebUser info = database.fetch().getWebUser(user);
sender.sendMessage(info.getName() + ": Permission level: " + info.getPermLevel());
} catch (Exception ex) {
Log.toLog(this.getClass(), ex);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).parse());
sender.sendMessage(locale.getString(CommandLang.WEB_USER_LIST, info.getName(), info.getPermLevel()));
} catch (Exception e) {
Log.toLog(this.getClass(), e);
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
} finally {
this.cancel();
}

View File

@ -1,9 +1,12 @@
package com.djrapitops.plan.command.commands.webuser;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
@ -22,21 +25,26 @@ import java.util.Arrays;
*/
public class WebDeleteCommand extends CommandNode {
public WebDeleteCommand() {
private final Locale locale;
public WebDeleteCommand(PlanPlugin plugin) {
super("delete|remove", Permissions.MANAGE_WEB.getPerm(), CommandType.PLAYER_OR_ARGS);
setShortHelp(Locale.get(Msg.CMD_USG_WEB_DELETE).toString());
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.WEB_DELETE));
setArguments("<username>");
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
Verify.isTrue(args.length >= 1,
() -> new IllegalArgumentException(Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse(Arrays.toString(this.getArguments()))));
() -> new IllegalArgumentException(locale.getString(CommandLang.FAIL_REQ_ONE_ARG, Arrays.toString(this.getArguments()))));
Database database = Database.getActive();
String user = args[0];
RunnableFactory.createNew(new AbsRunnable("Webuser Delete Task: " + user) {
RunnableFactory.createNew("Webuser Delete Task: " + user, new AbsRunnable() {
@Override
public void run() {
try {
@ -45,10 +53,10 @@ public class WebDeleteCommand extends CommandNode {
return;
}
database.remove().webUser(user);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_SUCCESS).parse());
} catch (Exception ex) {
Log.toLog(this.getClass(), ex);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).parse());
sender.sendMessage(locale.getString(ManageLang.PROGRESS_SUCCESS));
} catch (Exception e) {
Log.toLog(this.getClass(), e);
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
} finally {
this.cancel();
}

View File

@ -1,13 +1,13 @@
package com.djrapitops.plan.command.commands.webuser;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.settings.ColorScheme;
/**
* Subcommand for info about permission levels.
@ -17,31 +17,19 @@ import com.djrapitops.plugin.settings.ColorScheme;
*/
public class WebLevelCommand extends CommandNode {
private final PlanPlugin plugin;
private final Locale locale;
public WebLevelCommand(PlanPlugin plugin) {
super("level", Permissions.MANAGE_WEB.getPerm(), CommandType.CONSOLE);
setShortHelp(Locale.get(Msg.CMD_USG_WEB_LEVEL).toString());
this.plugin = plugin;
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.WEB_LEVEL));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
ColorScheme cs = plugin.getColorScheme();
String sCol = cs.getSecondaryColor();
String cmdBall = Locale.get(Msg.CMD_CONSTANT_LIST_BALL).parse();
String cmdFooter = Locale.get(Msg.CMD_CONSTANT_FOOTER).parse();
String[] messages = new String[]{
cmdFooter,
cmdBall + sCol + "0: Access all pages",
cmdBall + sCol + "1: Access '/players' and all inspect pages",
cmdBall + sCol + "2: Access inspect page with the same username as the webuser",
cmdBall + sCol + "3+: No permissions",
cmdFooter
};
sender.sendMessage(messages);
sender.sendMessage(locale.getArray(CommandLang.WEB_PERMISSION_LEVELS));
}
}

View File

@ -3,15 +3,16 @@ package com.djrapitops.plan.command.commands.webuser;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.data.WebUser;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.CmdHelpLang;
import com.djrapitops.plan.system.locale.lang.CommandLang;
import com.djrapitops.plan.system.locale.lang.ManageLang;
import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.utilities.comparators.WebUserComparator;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.command.CommandNode;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.RunnableFactory;
@ -25,32 +26,32 @@ import java.util.List;
*/
public class WebListUsersCommand extends CommandNode {
private final PlanPlugin plugin;
private final Locale locale;
public WebListUsersCommand(PlanPlugin plugin) {
super("list", Permissions.MANAGE_WEB.getPerm(), CommandType.CONSOLE);
setShortHelp("List registered web users & permission levels.");
this.plugin = plugin;
locale = plugin.getSystem().getLocaleSystem().getLocale();
setShortHelp(locale.getString(CmdHelpLang.WEB_LIST));
}
@Override
public void onCommand(ISender sender, String commandLabel, String[] args) {
RunnableFactory.createNew(new AbsRunnable("Webuser List Task") {
RunnableFactory.createNew(new AbsRunnable("Web user List Task") {
@Override
public void run() {
try {
ColorScheme cs = plugin.getColorScheme();
String mCol = cs.getMainColor();
List<WebUser> users = Database.getActive().fetch().getWebUsers();
users.sort(new WebUserComparator());
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).parse() + mCol + " WebUsers (" + users.size() + ")");
sender.sendMessage(locale.getString(CommandLang.HEADER_WEB_USERS, users.size()));
for (WebUser user : users) {
sender.sendMessage(" " + user.getPermLevel() + " : " + user.getName());
sender.sendMessage(locale.getString(CommandLang.WEB_USER_LIST, user.getName(), user.getPermLevel()));
}
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).parse());
} catch (Exception ex) {
Log.toLog(this.getClass(), ex);
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).parse());
sender.sendMessage(">");
} catch (Exception e) {
Log.toLog(this.getClass(), e);
sender.sendMessage(locale.getString(ManageLang.PROGRESS_FAIL, e.getMessage()));
} finally {
this.cancel();
}

View File

@ -10,7 +10,7 @@ import com.djrapitops.plan.utilities.FormatUtils;
import com.djrapitops.plan.utilities.SHA256Hash;
import com.google.common.base.Objects;
import java.io.UnsupportedEncodingException;
import java.io.Serializable;
import java.net.InetAddress;
import java.security.NoSuchAlgorithmException;
@ -19,7 +19,7 @@ import java.security.NoSuchAlgorithmException;
*
* @author Rsl1122
*/
public class GeoInfo implements DateHolder {
public class GeoInfo implements DateHolder, Serializable {
private final String ip;
private final String geolocation;
@ -27,7 +27,7 @@ public class GeoInfo implements DateHolder {
private final long date;
public GeoInfo(InetAddress address, String geolocation, long lastUsed)
throws UnsupportedEncodingException, NoSuchAlgorithmException {
throws NoSuchAlgorithmException {
this(FormatUtils.formatIP(address), geolocation, lastUsed, new SHA256Hash(address.getHostAddress()).create());
}

View File

@ -2,6 +2,7 @@ package com.djrapitops.plan.data.container;
import com.djrapitops.plan.data.store.objects.DateHolder;
import java.io.Serializable;
import java.util.Objects;
import java.util.UUID;
@ -11,7 +12,7 @@ import java.util.UUID;
*
* @author Rsl1122
*/
public class PlayerKill implements DateHolder {
public class PlayerKill implements DateHolder, Serializable {
private final UUID victim;
private final long date;

View File

@ -16,6 +16,10 @@ import java.util.*;
*/
public class Session extends DataContainer implements DateHolder {
private long sessionStart;
private WorldTimes worldTimes;
private List<PlayerKill> playerKills;
private int mobKills;
private int deaths;
private long afkTime;
@ -29,18 +33,22 @@ public class Session extends DataContainer implements DateHolder {
* @param gm Starting GameMode.
*/
public Session(UUID uuid, long sessionStart, String world, String gm) {
this.sessionStart = sessionStart;
worldTimes = new WorldTimes(world, gm, sessionStart);
playerKills = new ArrayList<>();
mobKills = 0;
deaths = 0;
afkTime = 0;
putRawData(SessionKeys.UUID, uuid);
putRawData(SessionKeys.START, sessionStart);
putRawData(SessionKeys.WORLD_TIMES, new WorldTimes(world, gm));
putRawData(SessionKeys.PLAYER_KILLS, new ArrayList<>());
putSupplier(SessionKeys.START, this::getSessionStart);
putSupplier(SessionKeys.WORLD_TIMES, this::getWorldTimes);
putSupplier(SessionKeys.PLAYER_KILLS, this::getPlayerKills);
putRawData(SessionKeys.PLAYER_DEATHS, new ArrayList<>());
putSupplier(SessionKeys.MOB_KILL_COUNT, () -> mobKills);
putSupplier(SessionKeys.DEATH_COUNT, () -> deaths);
putSupplier(SessionKeys.AFK_TIME, () -> afkTime);
putSupplier(SessionKeys.MOB_KILL_COUNT, this::getMobKills);
putSupplier(SessionKeys.DEATH_COUNT, this::getDeaths);
putSupplier(SessionKeys.AFK_TIME, this::getAfkTime);
putSupplier(SessionKeys.PLAYER_KILL_COUNT, getUnsafe(SessionKeys.PLAYER_KILLS)::size);
putSupplier(SessionKeys.LENGTH, () ->
@ -64,22 +72,26 @@ public class Session extends DataContainer implements DateHolder {
* @param afkTime Time spent AFK during the session.
*/
public Session(int id, UUID uuid, UUID serverUUID, long sessionStart, long sessionEnd, int mobKills, int deaths, long afkTime) {
putRawData(SessionKeys.DB_ID, id);
putRawData(SessionKeys.UUID, uuid);
putRawData(SessionKeys.SERVER_UUID, serverUUID);
putRawData(SessionKeys.START, sessionStart);
putRawData(SessionKeys.END, sessionEnd);
putRawData(SessionKeys.WORLD_TIMES, new WorldTimes(new HashMap<>()));
putRawData(SessionKeys.PLAYER_KILLS, new ArrayList<>());
putRawData(SessionKeys.PLAYER_DEATHS, new ArrayList<>());
putSupplier(SessionKeys.MOB_KILL_COUNT, () -> mobKills);
putSupplier(SessionKeys.DEATH_COUNT, () -> deaths);
putSupplier(SessionKeys.AFK_TIME, () -> afkTime);
this.sessionStart = sessionStart;
worldTimes = new WorldTimes(new HashMap<>());
playerKills = new ArrayList<>();
this.mobKills = mobKills;
this.deaths = deaths;
this.afkTime = afkTime;
putRawData(SessionKeys.DB_ID, id);
putRawData(SessionKeys.UUID, uuid);
putRawData(SessionKeys.SERVER_UUID, serverUUID);
putSupplier(SessionKeys.START, this::getSessionStart);
putRawData(SessionKeys.END, sessionEnd);
putSupplier(SessionKeys.WORLD_TIMES, this::getWorldTimes);
putSupplier(SessionKeys.PLAYER_KILLS, this::getPlayerKills);
putRawData(SessionKeys.PLAYER_DEATHS, new ArrayList<>());
putSupplier(SessionKeys.MOB_KILL_COUNT, this::getMobKills);
putSupplier(SessionKeys.DEATH_COUNT, this::getDeaths);
putSupplier(SessionKeys.AFK_TIME, this::getAfkTime);
putSupplier(SessionKeys.PLAYER_KILL_COUNT, () -> getUnsafe(SessionKeys.PLAYER_KILLS).size());
putSupplier(SessionKeys.LENGTH, () ->
getValue(SessionKeys.END).orElse(System.currentTimeMillis()) - getUnsafe(SessionKeys.START));
@ -95,8 +107,6 @@ public class Session extends DataContainer implements DateHolder {
*/
public void endSession(long endOfSession) {
putRawData(SessionKeys.END, endOfSession);
WorldTimes worldTimes = getValue(SessionKeys.WORLD_TIMES)
.orElseThrow(() -> new IllegalStateException("World times have not been defined"));
worldTimes.updateState(endOfSession);
}
@ -108,14 +118,10 @@ public class Session extends DataContainer implements DateHolder {
* @param time Epoch ms of the event.
*/
public void changeState(String world, String gm, long time) {
WorldTimes worldTimes = getValue(SessionKeys.WORLD_TIMES)
.orElseThrow(() -> new IllegalStateException("World times is not defined"));
worldTimes.updateState(world, gm, time);
}
public void playerKilled(PlayerKill kill) {
List<PlayerKill> playerKills = getValue(SessionKeys.PLAYER_KILLS)
.orElseThrow(() -> new IllegalStateException("Player kills is not defined."));
playerKills.add(kill);
}
@ -179,4 +185,33 @@ public class Session extends DataContainer implements DateHolder {
session.getValue(SessionKeys.PLAYER_KILLS).orElse(new ArrayList<>())
);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), mobKills, deaths, afkTime);
}
private long getSessionStart() {
return sessionStart;
}
private WorldTimes getWorldTimes() {
return worldTimes;
}
private List<PlayerKill> getPlayerKills() {
return playerKills;
}
private int getMobKills() {
return mobKills;
}
private int getDeaths() {
return deaths;
}
private long getAfkTime() {
return afkTime;
}
}

View File

@ -17,10 +17,6 @@ public class UserInfo {
private boolean banned;
private boolean opped;
public UserInfo(UUID uuid) {
this.uuid = uuid;
}
public UserInfo(UUID uuid, String name, long registered, boolean opped, boolean banned) {
this.uuid = uuid;
this.name = name;

View File

@ -1,6 +1,6 @@
package com.djrapitops.plan.data.plugin;
import com.djrapitops.plan.Plan;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.data.element.InspectContainer;
import com.djrapitops.plan.system.PlanSystem;
import com.djrapitops.plan.system.SubSystem;
@ -65,7 +65,7 @@ public class HookHandler implements SubSystem {
return;
}
try {
StaticHolder.saveInstance(dataSource.getClass(), Plan.class);
StaticHolder.saveInstance(dataSource.getClass(), PlanPlugin.getInstance().getClass());
if (!configHandler.hasSection(dataSource)) {
configHandler.createSection(dataSource);
}

View File

@ -16,15 +16,22 @@ public class CachingSupplier<T> implements Supplier<T> {
private final Supplier<T> original;
private T cachedValue;
private long cacheTime;
private long timeToLive;
public CachingSupplier(Supplier<T> original) {
this(original, TimeAmount.SECOND.ms() * 30L);
}
public CachingSupplier(Supplier<T> original, long timeToLive) {
this.original = original;
this.timeToLive = timeToLive;
cacheTime = 0L;
}
@Override
public T get() {
if (cachedValue == null || System.currentTimeMillis() - cacheTime > TimeAmount.SECOND.ms() * 30L) {
if (cachedValue == null || System.currentTimeMillis() - cacheTime > timeToLive) {
cachedValue = original.get();
cacheTime = System.currentTimeMillis();
}

View File

@ -3,8 +3,10 @@ package com.djrapitops.plan.data.store.containers;
import com.djrapitops.plan.data.store.CachingSupplier;
import com.djrapitops.plan.data.store.Key;
import com.djrapitops.plan.data.store.mutators.formatting.Formatter;
import com.djrapitops.plugin.api.TimeAmount;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
@ -16,7 +18,19 @@ import java.util.function.Supplier;
*
* @author Rsl1122
*/
public class DataContainer extends HashMap<Key, Supplier> {
public class DataContainer {
private final Map<Key, Supplier> map;
private long timeToLive;
public DataContainer() {
this(TimeAmount.SECOND.ms() * 30L);
}
public DataContainer(long timeToLive) {
this.timeToLive = timeToLive;
map = new HashMap<>();
}
/**
* Place your data inside the container.
@ -30,11 +44,14 @@ public class DataContainer extends HashMap<Key, Supplier> {
}
public <T> void putSupplier(Key<T> key, Supplier<T> supplier) {
super.put(key, new CachingSupplier<>(supplier));
if (supplier == null) {
return;
}
map.put(key, new CachingSupplier<>(supplier, timeToLive));
}
public <T> Supplier<T> getSupplier(Key<T> key) {
return (Supplier<T>) super.get(key);
return (Supplier<T>) map.get(key);
}
/**
@ -45,7 +62,7 @@ public class DataContainer extends HashMap<Key, Supplier> {
* @return true if found, false if not.
*/
public <T> boolean supports(Key<T> key) {
return containsKey(key);
return map.containsKey(key);
}
/**
@ -73,7 +90,7 @@ public class DataContainer extends HashMap<Key, Supplier> {
}
public <T> T getUnsafe(Key<T> key) {
Supplier supplier = get(key);
Supplier supplier = map.get(key);
if (supplier == null) {
throw new IllegalArgumentException("Unsupported Key: " + key.getKeyName());
}
@ -90,30 +107,15 @@ public class DataContainer extends HashMap<Key, Supplier> {
return formatter.apply(value);
}
/**
* Normal put method.
*
* @param key Key.
* @param value Supplier
* @return the previous value.
* @deprecated Use putSupplier instead for type safety.
*/
@Override
@Deprecated
public Supplier put(Key key, Supplier value) {
return super.put(key, value);
public void putAll(Map<Key, Supplier> toPut) {
map.putAll(toPut);
}
/**
* Normal get method.
*
* @param key Key.
* @return Supplier
* @deprecated Use getSupplier instead for types.
*/
@Override
@Deprecated
public Supplier get(Object key) {
return super.get(key);
public void putAll(DataContainer dataContainer) {
putAll(dataContainer.map);
}
public void clear() {
map.clear();
}
}

View File

@ -47,7 +47,7 @@ public class DateHoldersMutator<T extends DateHolder> {
long start = map.firstKey();
long now = System.currentTimeMillis();
long end = now - (now % twentyFourHours);
for (long date = map.firstKey(); date < end; date += twentyFourHours) {
for (long date = start; date < end; date += twentyFourHours) {
map.putIfAbsent(date, new ArrayList<>());
}
}

View File

@ -36,7 +36,6 @@ public class GeoInfoMutator {
if (geoInfo.isEmpty()) {
return Optional.empty();
}
geoInfo.sort(new GeoInfoComparator());
return Optional.of(geoInfo.get(0));
return geoInfo.stream().min(new GeoInfoComparator());
}
}

View File

@ -4,12 +4,14 @@ import com.djrapitops.plan.data.container.TPS;
import com.djrapitops.plan.data.store.containers.DataContainer;
import com.djrapitops.plan.data.store.keys.ServerKeys;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plan.utilities.comparators.TPSComparator;
import com.djrapitops.plan.utilities.html.graphs.line.Point;
import com.djrapitops.plugin.api.TimeAmount;
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalDouble;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
@ -35,12 +37,16 @@ public class TPSMutator {
return new TPSMutator(new ArrayList<>(mutator.tpsData));
}
public TPSMutator filterDataBetween(long after, long before) {
public TPSMutator filterBy(Predicate<TPS> filter) {
return new TPSMutator(tpsData.stream()
.filter(tps -> tps.getDate() >= after && tps.getDate() <= before)
.filter(filter)
.collect(Collectors.toList()));
}
public TPSMutator filterDataBetween(long after, long before) {
return filterBy(tps -> tps.getDate() >= after && tps.getDate() <= before);
}
public List<TPS> all() {
return tpsData;
}
@ -84,6 +90,7 @@ public class TPSMutator {
public long serverDownTime() {
long lastDate = -1;
long downTime = 0;
tpsData.sort(new TPSComparator());
for (TPS tps : tpsData) {
long date = tps.getDate();
if (lastDate == -1) {
@ -105,6 +112,7 @@ public class TPSMutator {
long lastDate = -1;
int lastPlayers = 0;
long idleTime = 0;
tpsData.sort(new TPSComparator());
for (TPS tps : tpsData) {
long date = tps.getDate();
int players = tps.getPlayers();

View File

@ -3,7 +3,10 @@ package com.djrapitops.plan.data.store.mutators.formatting;
import com.djrapitops.plan.data.store.objects.DateHolder;
import com.djrapitops.plan.utilities.FormatUtils;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.utilities.Format;
import org.apache.commons.text.TextStringBuilder;
import java.util.Arrays;
import java.util.Calendar;
import java.util.function.Function;
@ -79,4 +82,13 @@ public class Formatters {
}
};
}
public static Formatter<String> itemName() {
return name -> {
String[] parts = name.split("_");
TextStringBuilder builder = new TextStringBuilder();
builder.appendWithSeparators(Arrays.stream(parts).map(part -> new Format(part).capitalize()).iterator(), " ");
return builder.toString();
};
}
}

View File

@ -77,13 +77,13 @@ public class HealthInformation extends AbstractHealthInfo {
long playersRetainedMonth = analysisContainer.getValue(AnalysisKeys.PLAYERS_RETAINED_MONTH).orElse(0);
if (playersNewMonth != 0) {
double retainPercentage = playersRetainedMonth / playersNewMonth;
double retainPercentage = playersRetainedMonth * 1.0 / playersNewMonth;
if (retainPercentage >= 0.25) {
addNote(Icons.GREEN_THUMB + " " + Formatters.percentage().apply(retainPercentage)
+ " of new players have stuck around (" + playersRetainedMonth + "/" + playersNewMonth + ")");
} else {
addNote(Icons.YELLOW_FLAG + " " + Formatters.percentage().apply(retainPercentage)
+ "% of new players have stuck around (" + playersRetainedMonth + "/" + playersNewMonth + ")");
+ " of new players have stuck around (" + playersRetainedMonth + "/" + playersNewMonth + ")");
}
}
}

View File

@ -55,7 +55,7 @@ public class NetworkHealthInformation extends AbstractHealthInfo {
uniquePlayersNote(serverCount, serverKey, perServerContainers);
newPlayersNote(serverCount, serverKey, perServerContainers);
playersNote(serverCount, serverKey, perServerContainers);
playersNote(serverKey, perServerContainers);
}
private void uniquePlayersNote(int serverCount, Key<Server> serverKey, List<DataContainer> perServerContainers) {
@ -137,7 +137,7 @@ public class NetworkHealthInformation extends AbstractHealthInfo {
return perServerContainers;
}
private void playersNote(int serverCount, Key<Server> serverKey, List<DataContainer> perServerContainers) {
private void playersNote(Key<Server> serverKey, List<DataContainer> perServerContainers) {
Icon icon = Icons.HELP_RING;
String uniquePlayersNote = "${playersMonth} players played on the network:";
StringBuilder subNotes = new StringBuilder();

View File

@ -2,25 +2,20 @@ package com.djrapitops.plan.data.time;
import com.djrapitops.plugin.utilities.Verify;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Abstract class for keeping track of time spent in each state.
*
* @author Rsl1122
*/
public abstract class TimeKeeper {
/**
* Keeps time of states.
*/
public abstract class TimeKeeper implements Serializable {
protected Map<String, Long> times;
/**
* Last State seen in
*/
protected String state;
/**
* Relates to Playtime Milliseconds.
*/
protected long lastStateChange;
public TimeKeeper(Map<String, Long> times, String lastState, long lastStateChange) {
@ -72,19 +67,19 @@ public abstract class TimeKeeper {
* Adds time to the last state while updating the status of other parameters.
*
* @param newState New State seen in.
* @param playTime Current Playtime.
* @param ms Epoch ms the change occurred.
* @throws IllegalArgumentException If newState is null.
*/
public void changeState(String newState, long playTime) {
public void changeState(String newState, long ms) {
Verify.nullCheck(newState);
if (state == null) {
state = newState;
}
Long currentTime = times.getOrDefault(state, 0L);
long diff = playTime - lastStateChange;
long diff = ms - lastStateChange;
times.put(state, currentTime + Math.abs(diff));
state = newState;
lastStateChange = playTime;
lastStateChange = ms;
}
protected void resetState(String state) {

View File

@ -1,5 +1,6 @@
package com.djrapitops.plan.data.time;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@ -10,7 +11,7 @@ import java.util.Objects;
* @author Rsl1122
* @since 4.0.0
*/
public class WorldTimes {
public class WorldTimes implements Serializable {
private final Map<String, GMTimes> worldTimes;
private String currentWorld;
@ -21,12 +22,13 @@ public class WorldTimes {
*
* @param startingWorld World to start the calculations at.
* @param startingGM GameMode to start the calculations at.
* @param time Epoch ms the time calculation should start
*/
public WorldTimes(String startingWorld, String startingGM) {
public WorldTimes(String startingWorld, String startingGM, long time) {
worldTimes = new HashMap<>();
currentWorld = startingWorld;
currentGamemode = startingGM;
addWorld(startingWorld, startingGM, System.currentTimeMillis());
addWorld(startingWorld, startingGM, time);
}
/**

View File

@ -14,6 +14,7 @@ import com.djrapitops.plan.system.file.FileSystem;
import com.djrapitops.plan.system.info.ServerInfoSystem;
import com.djrapitops.plan.system.info.server.BukkitServerInfo;
import com.djrapitops.plan.system.listeners.BukkitListenerSystem;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.settings.PlanErrorManager;
import com.djrapitops.plan.system.settings.config.ServerConfigSystem;
import com.djrapitops.plan.system.settings.network.NetworkSettings;
@ -22,6 +23,8 @@ import com.djrapitops.plan.system.update.VersionCheckSystem;
import com.djrapitops.plugin.StaticHolder;
import com.djrapitops.plugin.api.utility.log.Log;
import java.util.function.Supplier;
/**
* Represents PlanSystem for Plan.
*
@ -34,14 +37,16 @@ public class BukkitSystem extends PlanSystem implements ServerSystem {
Log.setErrorManager(new PlanErrorManager());
versionCheckSystem = new VersionCheckSystem(plugin.getVersion());
Supplier<Locale> localeSupplier = () -> getLocaleSystem().getLocale();
versionCheckSystem = new VersionCheckSystem(plugin.getVersion(), localeSupplier);
fileSystem = new FileSystem(plugin);
configSystem = new ServerConfigSystem();
databaseSystem = new ServerDBSystem();
databaseSystem = new ServerDBSystem(localeSupplier);
listenerSystem = new BukkitListenerSystem(plugin);
taskSystem = new BukkitTaskSystem(plugin);
infoSystem = new ServerInfoSystem();
infoSystem = new ServerInfoSystem(localeSupplier);
serverInfo = new BukkitServerInfo(plugin);
hookHandler = new HookHandler();

View File

@ -15,6 +15,7 @@ import com.djrapitops.plan.system.file.FileSystem;
import com.djrapitops.plan.system.info.BungeeInfoSystem;
import com.djrapitops.plan.system.info.server.BungeeServerInfo;
import com.djrapitops.plan.system.listeners.BungeeListenerSystem;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.settings.PlanErrorManager;
import com.djrapitops.plan.system.settings.config.BungeeConfigSystem;
import com.djrapitops.plan.system.settings.network.NetworkSettings;
@ -22,6 +23,8 @@ import com.djrapitops.plan.system.tasks.BungeeTaskSystem;
import com.djrapitops.plan.system.update.VersionCheckSystem;
import com.djrapitops.plugin.api.utility.log.Log;
import java.util.function.Supplier;
/**
* Represents PlanSystem for PlanBungee.
*
@ -34,10 +37,12 @@ public class BungeeSystem extends PlanSystem {
Log.setErrorManager(new PlanErrorManager());
versionCheckSystem = new VersionCheckSystem(plugin.getVersion());
Supplier<Locale> localeSupplier = () -> getLocaleSystem().getLocale();
versionCheckSystem = new VersionCheckSystem(plugin.getVersion(), localeSupplier);
fileSystem = new FileSystem(plugin);
configSystem = new BungeeConfigSystem();
databaseSystem = new BungeeDBSystem();
databaseSystem = new BungeeDBSystem(localeSupplier);
cacheSystem = new BungeeCacheSystem(this);
listenerSystem = new BungeeListenerSystem(plugin);
taskSystem = new BungeeTaskSystem(plugin);

View File

@ -13,6 +13,8 @@ import com.djrapitops.plan.system.file.FileSystem;
import com.djrapitops.plan.system.info.InfoSystem;
import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plan.system.listeners.ListenerSystem;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.LocaleSystem;
import com.djrapitops.plan.system.processing.Processing;
import com.djrapitops.plan.system.settings.config.ConfigSystem;
import com.djrapitops.plan.system.tasks.TaskSystem;
@ -22,6 +24,8 @@ import com.djrapitops.plugin.api.Check;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.utilities.Verify;
import java.util.function.Supplier;
/**
* PlanSystem contains everything Plan needs to run.
* <p>
@ -36,6 +40,7 @@ public abstract class PlanSystem implements SubSystem {
// Initialized in this class
private Processing processing;
protected final WebServerSystem webServerSystem;
protected final LocaleSystem localeSystem;
protected CacheSystem cacheSystem;
// These need to be initialized in the sub class.
@ -55,8 +60,11 @@ public abstract class PlanSystem implements SubSystem {
protected PlanAPI planAPI;
public PlanSystem() {
processing = new Processing();
webServerSystem = new WebServerSystem();
Supplier<Locale> localeSupplier = () -> getLocaleSystem().getLocale();
processing = new Processing(localeSupplier);
webServerSystem = new WebServerSystem(localeSupplier);
localeSystem = new LocaleSystem();
cacheSystem = new CacheSystem(this);
}
@ -80,9 +88,10 @@ public abstract class PlanSystem implements SubSystem {
public void enable() throws EnableException {
checkSubSystemInitialization();
SubSystem[] systems = new SubSystem[]{
enableSystems(
fileSystem,
configSystem,
localeSystem,
versionCheckSystem,
databaseSystem,
webServerSystem,
@ -93,7 +102,10 @@ public abstract class PlanSystem implements SubSystem {
listenerSystem,
taskSystem,
hookHandler
};
);
}
private void enableSystems(SubSystem... systems) throws EnableException {
for (SubSystem system : systems) {
system.enable();
}
@ -101,7 +113,7 @@ public abstract class PlanSystem implements SubSystem {
@Override
public void disable() {
SubSystem[] systems = new SubSystem[]{
disableSystems(
taskSystem,
hookHandler,
cacheSystem,
@ -111,10 +123,14 @@ public abstract class PlanSystem implements SubSystem {
webServerSystem,
infoSystem,
serverInfo,
localeSystem,
configSystem,
fileSystem,
versionCheckSystem
};
);
}
private void disableSystems(SubSystem... systems) {
for (SubSystem system : systems) {
try {
if (system != null) {
@ -131,6 +147,7 @@ public abstract class PlanSystem implements SubSystem {
Verify.nullCheck(versionCheckSystem, () -> new IllegalStateException("Version Check system was not initialized."));
Verify.nullCheck(fileSystem, () -> new IllegalStateException("File system was not initialized."));
Verify.nullCheck(configSystem, () -> new IllegalStateException("Config system was not initialized."));
Verify.nullCheck(localeSystem, () -> new IllegalStateException("Locale system was not initialized."));
Verify.nullCheck(databaseSystem, () -> new IllegalStateException("Database system was not initialized."));
Verify.nullCheck(infoSystem, () -> new IllegalStateException("Info system was not initialized."));
Verify.nullCheck(serverInfo, () -> new IllegalStateException("ServerInfo was not initialized."));
@ -200,4 +217,8 @@ public abstract class PlanSystem implements SubSystem {
static void setTestSystem(PlanSystem testSystem) {
PlanSystem.testSystem = testSystem;
}
public LocaleSystem getLocaleSystem() {
return localeSystem;
}
}

View File

@ -14,6 +14,7 @@ import com.djrapitops.plan.system.file.FileSystem;
import com.djrapitops.plan.system.info.ServerInfoSystem;
import com.djrapitops.plan.system.info.server.SpongeServerInfo;
import com.djrapitops.plan.system.listeners.SpongeListenerSystem;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.settings.PlanErrorManager;
import com.djrapitops.plan.system.settings.config.SpongeConfigSystem;
import com.djrapitops.plan.system.settings.network.NetworkSettings;
@ -22,6 +23,8 @@ import com.djrapitops.plan.system.update.VersionCheckSystem;
import com.djrapitops.plugin.StaticHolder;
import com.djrapitops.plugin.api.utility.log.Log;
import java.util.function.Supplier;
/**
* Represents PlanSystem for PlanSponge.
*
@ -32,16 +35,18 @@ public class SpongeSystem extends PlanSystem implements ServerSystem {
public SpongeSystem(PlanSponge plugin) {
setTestSystem(this);
Supplier<Locale> localeSupplier = () -> getLocaleSystem().getLocale();
Log.setErrorManager(new PlanErrorManager());
versionCheckSystem = new VersionCheckSystem(plugin.getVersion());
versionCheckSystem = new VersionCheckSystem(plugin.getVersion(), localeSupplier);
fileSystem = new FileSystem(plugin);
configSystem = new SpongeConfigSystem();
databaseSystem = new ServerDBSystem();
databaseSystem = new ServerDBSystem(localeSupplier);
listenerSystem = new SpongeListenerSystem(plugin);
taskSystem = new SpongeTaskSystem(plugin);
infoSystem = new ServerInfoSystem();
infoSystem = new ServerInfoSystem(localeSupplier);
serverInfo = new SpongeServerInfo();
hookHandler = new HookHandler();

View File

@ -12,7 +12,7 @@ import com.djrapitops.plan.system.PlanSystem;
public class BungeeCacheSystem extends CacheSystem {
public BungeeCacheSystem(PlanSystem system) {
super(new BungeeDataCache(system));
super(new BungeeDataCache(system), system);
}
}

View File

@ -7,6 +7,9 @@ package com.djrapitops.plan.system.cache;
import com.djrapitops.plan.api.exceptions.EnableException;
import com.djrapitops.plan.system.PlanSystem;
import com.djrapitops.plan.system.SubSystem;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.RunnableFactory;
import com.djrapitops.plugin.utilities.Verify;
/**
@ -18,14 +21,16 @@ public class CacheSystem implements SubSystem {
private final DataCache dataCache;
private final GeolocationCache geolocationCache;
private final DataContainerCache dataContainerCache;
public CacheSystem(PlanSystem system) {
this(new DataCache(system));
this(new DataCache(system), system);
}
protected CacheSystem(DataCache dataCache) {
protected CacheSystem(DataCache dataCache, PlanSystem system) {
this.dataCache = dataCache;
geolocationCache = new GeolocationCache();
geolocationCache = new GeolocationCache(() -> system.getLocaleSystem().getLocale());
dataContainerCache = new DataContainerCache();
}
public static CacheSystem getInstance() {
@ -39,11 +44,18 @@ public class CacheSystem implements SubSystem {
dataCache.enable();
geolocationCache.enable();
RunnableFactory.createNew("DataContainer cache clean task", new AbsRunnable() {
@Override
public void run() {
dataContainerCache.clear();
}
}).runTaskTimerAsynchronously(TimeAmount.MINUTE.ticks(), TimeAmount.MINUTE.ms());
}
@Override
public void disable() {
geolocationCache.clearCache();
dataContainerCache.clear();
}
public DataCache getDataCache() {
@ -53,4 +65,8 @@ public class CacheSystem implements SubSystem {
public GeolocationCache getGeolocationCache() {
return geolocationCache;
}
public DataContainerCache getDataContainerCache() {
return dataContainerCache;
}
}

View File

@ -0,0 +1,71 @@
package com.djrapitops.plan.system.cache;
import com.djrapitops.plan.data.store.Key;
import com.djrapitops.plan.data.store.containers.AnalysisContainer;
import com.djrapitops.plan.data.store.containers.DataContainer;
import com.djrapitops.plan.data.store.containers.NetworkContainer;
import com.djrapitops.plan.data.store.containers.PlayerContainer;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plugin.api.TimeAmount;
import java.util.UUID;
import java.util.function.Supplier;
/**
* Cache to aid Bungee in case SQL is causing cpu thread starvation, leading to mysql connection drops.
*
* @author Rsl1122
*/
public class DataContainerCache extends DataContainer {
public DataContainerCache() {
super(TimeAmount.SECOND.ms() * 10L);
putSupplier(Keys.NETWORK_CONTAINER, Suppliers.NETWORK_CONTAINER);
}
public PlayerContainer getPlayerContainer(UUID uuid) {
return getAndCacheSupplier(Keys.playerContainer(uuid), Suppliers.playerContainer(uuid));
}
public AnalysisContainer getAnalysisContainer(UUID serverUUID) {
return getAndCacheSupplier(Keys.analysisContainer(serverUUID), Suppliers.analysisContainer(serverUUID));
}
public <T> T getAndCacheSupplier(Key<T> key, Supplier<T> ifNotPresent) {
if (!supports(key)) {
putSupplier(key, ifNotPresent);
}
return getUnsafe(key);
}
public NetworkContainer getNetworkContainer() {
return getAndCacheSupplier(Keys.NETWORK_CONTAINER, Suppliers.NETWORK_CONTAINER);
}
public static class Keys {
static final Key<NetworkContainer> NETWORK_CONTAINER = new Key<>(NetworkContainer.class, "NETWORK_CONTAINER");
static Key<AnalysisContainer> analysisContainer(UUID serverUUID) {
return new Key<>(AnalysisContainer.class, "ANALYSIS_CONTAINER:" + serverUUID);
}
static Key<PlayerContainer> playerContainer(UUID uuid) {
return new Key<>(PlayerContainer.class, "PLAYER_CONTAINER:" + uuid);
}
}
public static class Suppliers {
static final Supplier<NetworkContainer> NETWORK_CONTAINER = () -> Database.getActive().fetch().getNetworkContainer();
static Supplier<AnalysisContainer> analysisContainer(UUID serverUUID) {
return () -> new AnalysisContainer(Database.getActive().fetch().getServerContainer(serverUUID));
}
static Supplier<PlayerContainer> playerContainer(UUID uuid) {
return () -> Database.getActive().fetch().getPlayerContainer(uuid);
}
}
}

View File

@ -3,6 +3,8 @@ package com.djrapitops.plan.system.cache;
import com.djrapitops.plan.api.exceptions.EnableException;
import com.djrapitops.plan.system.SubSystem;
import com.djrapitops.plan.system.file.FileSystem;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.utilities.Verify;
@ -21,6 +23,7 @@ import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import java.util.zip.GZIPInputStream;
/**
@ -33,10 +36,12 @@ import java.util.zip.GZIPInputStream;
*/
public class GeolocationCache implements SubSystem {
private final Supplier<Locale> locale;
private final Map<String, String> geolocationCache;
private File geolocationDB;
public GeolocationCache() {
public GeolocationCache(Supplier<Locale> locale) {
this.locale = locale;
geolocationCache = new HashMap<>();
}
@ -47,10 +52,12 @@ public class GeolocationCache implements SubSystem {
try {
GeolocationCache.checkDB();
} catch (UnknownHostException e) {
Log.error("Plan Requires internet access on first run to download GeoLite2 Geolocation database.");
Log.error(locale.get().getString(PluginLang.ENABLE_NOTIFY_GEOLOCATIONS_INTERNET_REQUIRED));
} catch (IOException e) {
throw new EnableException("Something went wrong saving the downloaded GeoLite2 Geolocation database", e);
throw new EnableException(locale.get().getString(PluginLang.ENABLE_FAIL_GEODB_WRITE), e);
}
} else {
Log.infoColor("§e" + locale.get().getString(PluginLang.ENABLE_NOTIFY_GEOLOCATIONS_DISABLED));
}
}

View File

@ -58,10 +58,6 @@ public class SessionCache {
return Optional.ofNullable(activeSessions.get(uuid));
}
public static boolean isOnline(UUID uuid) {
return getCachedSession(uuid).isPresent();
}
public void cacheSession(UUID uuid, Session session) {
if (getCachedSession(uuid).isPresent()) {
endSession(uuid, System.currentTimeMillis());

View File

@ -6,6 +6,9 @@ package com.djrapitops.plan.system.database;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.system.database.databases.sql.MySQLDB;
import com.djrapitops.plan.system.locale.Locale;
import java.util.function.Supplier;
/**
* Bungee Database system that initializes MySQL object.
@ -14,9 +17,13 @@ import com.djrapitops.plan.system.database.databases.sql.MySQLDB;
*/
public class BungeeDBSystem extends DBSystem {
public BungeeDBSystem(Supplier<Locale> locale) {
super(locale);
}
@Override
protected void initDatabase() throws DBInitException {
db = new MySQLDB();
db = new MySQLDB(locale);
databases.add(db);
db.init();
}

View File

@ -10,14 +10,15 @@ import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.system.PlanSystem;
import com.djrapitops.plan.system.SubSystem;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.settings.locale.Locale;
import com.djrapitops.plan.system.settings.locale.Msg;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plugin.api.Benchmark;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.utilities.Verify;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;
/**
* System that holds the active databases.
@ -26,10 +27,13 @@ import java.util.Set;
*/
public abstract class DBSystem implements SubSystem {
protected final Supplier<Locale> locale;
protected Database db;
protected Set<Database> databases;
public DBSystem() {
public DBSystem(Supplier<Locale> locale) {
this.locale = locale;
databases = new HashSet<>();
}
@ -39,20 +43,16 @@ public abstract class DBSystem implements SubSystem {
return dbSystem;
}
@Override
public void enable() throws EnableException {
try {
Benchmark.start("Init Database");
Log.info(Locale.get(Msg.ENABLE_DB_INIT).toString());
initDatabase();
db.scheduleClean(1L);
Log.info(Locale.get(Msg.ENABLE_DB_INFO).parse(db.getConfigName()));
Benchmark.stop("Enable", "Init Database");
} catch (DBInitException e) {
Throwable cause = e.getCause();
String message = cause == null ? e.getMessage() : cause.getMessage();
throw new EnableException((db != null ? db.getName() : "Database") + " init failure: " + message, cause);
public static Database getActiveDatabaseByName(String dbName) throws DBInitException {
DBSystem system = getInstance();
for (Database database : system.getDatabases()) {
String dbConfigName = database.getConfigName();
if (Verify.equalsIgnoreCase(dbName, dbConfigName)) {
database.init();
return database;
}
}
throw new DBInitException(system.locale.get().getString(PluginLang.ENABLE_FAIL_WRONG_DB, dbName));
}
protected abstract void initDatabase() throws DBInitException;
@ -76,15 +76,19 @@ public abstract class DBSystem implements SubSystem {
return db;
}
public static Database getActiveDatabaseByName(String dbName) throws DBInitException {
for (Database database : getInstance().getDatabases()) {
String dbConfigName = database.getConfigName();
if (Verify.equalsIgnoreCase(dbName, dbConfigName)) {
database.init();
return database;
}
@Override
public void enable() throws EnableException {
try {
Benchmark.start("Init Database");
initDatabase();
db.scheduleClean(1L);
Log.info(locale.get().getString(PluginLang.ENABLED_DATABASE, db.getName()));
Benchmark.stop("Enable", "Init Database");
} catch (DBInitException e) {
Throwable cause = e.getCause();
String message = cause == null ? e.getMessage() : cause.getMessage();
throw new EnableException((db != null ? db.getName() : "Database") + " init failure: " + message, cause);
}
throw new DBInitException(Locale.get(Msg.ENABLE_FAIL_WRONG_DB) + " " + dbName);
}
public void setActiveDatabase(Database db) throws DBException {

View File

@ -8,9 +8,12 @@ import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.system.database.databases.sql.MySQLDB;
import com.djrapitops.plan.system.database.databases.sql.SQLiteDB;
import com.djrapitops.plan.system.database.databases.sql.SpongeMySQLDB;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plugin.api.Check;
import java.util.function.Supplier;
/**
* Bukkit Database system that initializes SQLite and MySQL database objects.
*
@ -18,10 +21,14 @@ import com.djrapitops.plugin.api.Check;
*/
public class ServerDBSystem extends DBSystem {
public ServerDBSystem(Supplier<Locale> locale) {
super(locale);
}
@Override
protected void initDatabase() throws DBInitException {
databases.add(Check.isSpongeAvailable() ? new SpongeMySQLDB() : new MySQLDB());
databases.add(new SQLiteDB());
databases.add(Check.isSpongeAvailable() ? new SpongeMySQLDB(locale) : new MySQLDB(locale));
databases.add(new SQLiteDB(locale));
String dbType = Settings.DB_TYPE.toString().toLowerCase().trim();
db = getActiveDatabaseByName(dbType);

View File

@ -6,5 +6,4 @@ public interface CountOperations {
int getServerPlayerCount(UUID server);
int getNetworkPlayerCount();
}

View File

@ -1,53 +1,36 @@
package com.djrapitops.plan.system.database.databases.sql;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.api.utility.log.Log;
import org.apache.commons.dbcp2.BasicDataSource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;
import java.util.function.Supplier;
/**
* @author Rsl1122
*/
public class MySQLDB extends SQLDB {
protected DataSource dataSource;
private static int increment = 1;
public MySQLDB() {
protected volatile DataSource dataSource;
public MySQLDB(Supplier<Locale> locale) {
super(locale);
}
/**
* Setups the {@link BasicDataSource}
*/
@Override
public void setupDataSource() throws DBInitException {
BasicDataSource dataSource = new BasicDataSource();
this.dataSource = dataSource;
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
String host = Settings.DB_HOST.toString();
String port = Integer.toString(Settings.DB_PORT.getNumber());
String database = Settings.DB_DATABASE.toString();
String launchOptions = Settings.DB_LAUNCH_OPTIONS.toString();
if (launchOptions.isEmpty() || !launchOptions.startsWith("?") || launchOptions.endsWith("&")) {
Log.error("Launch Options were faulty, using default (?rewriteBatchedStatements=true&useSSL=false)");
launchOptions = "?rewriteBatchedStatements=true&useSSL=false";
}
dataSource.setUrl("jdbc:mysql://" + host + ":" + port + "/" + database + launchOptions);
String username = Settings.DB_USER.toString();
String password = Settings.DB_PASS.toString();
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setInitialSize(1);
dataSource.setMaxTotal(8);
private static synchronized void increment() {
increment++;
}
/**
@ -58,21 +41,87 @@ public class MySQLDB extends SQLDB {
return "MySQL";
}
/**
* Setups the {@link HikariDataSource}
*/
@Override
public void setupDataSource() throws DBInitException {
try {
HikariConfig config = new HikariConfig();
String host = Settings.DB_HOST.toString();
String port = Integer.toString(Settings.DB_PORT.getNumber());
String database = Settings.DB_DATABASE.toString();
String launchOptions = Settings.DB_LAUNCH_OPTIONS.toString();
if (launchOptions.isEmpty() || !launchOptions.startsWith("?") || launchOptions.endsWith("&")) {
launchOptions = "?rewriteBatchedStatements=true&useSSL=false";
Log.error(locale.get().getString(PluginLang.DB_MYSQL_LAUNCH_OPTIONS_FAIL, launchOptions));
}
config.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + database + launchOptions);
String username = Settings.DB_USER.toString();
String password = Settings.DB_PASS.toString();
config.setUsername(username);
config.setPassword(password);
config.setPoolName("Plan Connection Pool-" + increment);
increment();
config.setAutoCommit(true);
config.setMaximumPoolSize(8);
config.setMaxLifetime(25L * TimeAmount.MINUTE.ms());
config.setLeakDetectionThreshold(10L * TimeAmount.MINUTE.ms());
this.dataSource = new HikariDataSource(config);
getConnection();
} catch (SQLException e) {
throw new DBInitException("Failed to set-up HikariCP Datasource: " + e.getMessage(), e);
}
}
@Override
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
Connection connection = dataSource.getConnection();
if (!connection.isValid(5)) {
connection.close();
if (dataSource instanceof HikariDataSource) {
((HikariDataSource) dataSource).close();
}
try {
setupDataSource();
// get new connection after restarting pool
return dataSource.getConnection();
} catch (DBInitException e) {
throw new DBOpException("Failed to restart DataSource after a connection was invalid: " + e.getMessage(), e);
}
}
return connection;
}
@Override
public void close() {
if (dataSource instanceof HikariDataSource) {
((HikariDataSource) dataSource).close();
}
super.close();
}
@Override
public void returnToPool(Connection connection) {
try {
if (dataSource instanceof BasicDataSource) {
((BasicDataSource) dataSource).close();
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
Log.toLog(this.getClass(), e);
}
super.close();
}
@Override
public void commit(Connection connection) {
returnToPool(connection);
}
@Override
@ -86,7 +135,6 @@ public class MySQLDB extends SQLDB {
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), dataSource);
}
}

View File

@ -1,21 +1,24 @@
package com.djrapitops.plan.system.database.databases.sql;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.database.databases.operation.*;
import com.djrapitops.plan.system.database.databases.sql.operation.*;
import com.djrapitops.plan.system.database.databases.sql.patches.*;
import com.djrapitops.plan.system.database.databases.sql.processing.ExecStatement;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryStatement;
import com.djrapitops.plan.system.database.databases.sql.tables.*;
import com.djrapitops.plan.system.database.databases.sql.tables.move.Version8TransferTable;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.ITask;
import com.djrapitops.plugin.task.RunnableFactory;
import org.apache.commons.dbcp2.BasicDataSource;
import com.djrapitops.plugin.utilities.Verify;
import java.sql.Connection;
import java.sql.PreparedStatement;
@ -24,6 +27,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
@ -34,6 +38,8 @@ import java.util.stream.Collectors;
*/
public abstract class SQLDB extends Database {
protected final Supplier<Locale> locale;
private final UsersTable usersTable;
private final UserInfoTable userInfoTable;
private final KillsTable killsTable;
@ -42,7 +48,6 @@ public abstract class SQLDB extends Database {
private final GeoInfoTable geoInfoTable;
private final CommandUseTable commandUseTable;
private final TPSTable tpsTable;
private final VersionTable versionTable;
private final SecurityTable securityTable;
private final WorldTable worldTable;
private final WorldTimesTable worldTimesTable;
@ -62,10 +67,10 @@ public abstract class SQLDB extends Database {
private final boolean usingMySQL;
private ITask dbCleanTask;
public SQLDB() {
usingMySQL = getName().equals("MySQL");
public SQLDB(Supplier<Locale> locale) {
this.locale = locale;
usingMySQL = this instanceof MySQLDB;
versionTable = new VersionTable(this);
serverTable = new ServerTable(this);
securityTable = new SecurityTable(this);
@ -136,67 +141,47 @@ public abstract class SQLDB extends Database {
*/
public void setupDatabase() throws DBInitException {
try {
boolean newDatabase = versionTable.isNewDatabase();
versionTable.createTable();
createTables();
if (newDatabase) {
Log.info("New Database created.");
versionTable.setVersion(19);
}
Patch[] patches = new Patch[]{
new Version10Patch(this),
new GeoInfoLastUsedPatch(this),
new TransferPartitionPatch(this),
new SessionAFKTimePatch(this),
new KillsServerIDPatch(this),
new WorldTimesSeverIDPatch(this),
new WorldsServerIDPatch(this),
new IPHashPatch(this),
new IPAnonPatch(this),
new NicknameLastSeenPatch(this),
new VersionTableRemovalPatch(this)
};
int version = versionTable.getVersion();
final SQLDB db = this;
if (version < 10) {
RunnableFactory.createNew("DB v8 -> v10 Task", new AbsRunnable() {
@Override
public void run() {
try {
new Version8TransferTable(db).alterTablesToV10();
} catch (DBInitException | DBOpException e) {
Log.toLog(this.getClass(), e);
RunnableFactory.createNew("Database Patch", new AbsRunnable() {
@Override
public void run() {
try {
boolean applied = false;
for (Patch patch : patches) {
if (!patch.hasBeenApplied()) {
String patchName = patch.getClass().getSimpleName();
Log.info(locale.get().getString(PluginLang.DB_APPLY_PATCH, patchName));
patch.apply();
applied = true;
}
}
Log.info(locale.get().getString(
applied ? PluginLang.DB_APPLIED_PATCHES : PluginLang.DB_APPLIED_PATCHES_ALREADY
));
} catch (Exception e) {
Log.error("----------------------------------------------------");
Log.error(locale.get().getString(PluginLang.ENABLE_FAIL_DB_PATCH));
Log.error("----------------------------------------------------");
Log.toLog(this.getClass(), e);
PlanPlugin.getInstance().onDisable();
}
}).runTaskLaterAsynchronously(TimeAmount.SECOND.ticks() * 5L);
}
if (version < 11) {
serverTable.alterTableV11();
versionTable.setVersion(11);
}
if (version < 12) {
geoInfoTable.alterTableV12();
versionTable.setVersion(12);
}
if (version < 13) {
geoInfoTable.alterTableV13();
versionTable.setVersion(13);
}
if (version < 14) {
transferTable.alterTableV14();
versionTable.setVersion(14);
}
if (version < 15) {
sessionsTable.alterTableV15();
versionTable.setVersion(15);
}
if (version < 16) {
killsTable.alterTableV16();
worldTimesTable.alterTableV16();
versionTable.setVersion(16);
}
if (version < 17) {
geoInfoTable.alterTableV17();
versionTable.setVersion(17);
}
if (version < 18) {
geoInfoTable.alterTableV18();
// version set in the runnable in above method
}
if (version < 19) {
nicknamesTable.alterTableV19();
}
}
}).runTaskLaterAsynchronously(TimeAmount.SECOND.ticks() * 5L);
} catch (DBOpException e) {
throw new DBInitException("Failed to set-up Database", e);
}
@ -241,9 +226,6 @@ public abstract class SQLDB extends Database {
};
}
/**
* Setups the {@link BasicDataSource}
*/
public abstract void setupDataSource() throws DBInitException;
@Override
@ -254,18 +236,9 @@ public abstract class SQLDB extends Database {
}
}
public int getVersion() {
return versionTable.getVersion();
}
public void setVersion(int version) {
versionTable.setVersion(version);
}
private void clean() {
tpsTable.clean();
transferTable.clean();
geoInfoTable.clean();
pingTable.clean();
long now = System.currentTimeMillis();
@ -280,40 +253,15 @@ public abstract class SQLDB extends Database {
}
int removed = inactivePlayers.size();
if (removed > 0) {
Log.info("Removed data of " + removed + " players.");
Log.info(locale.get().getString(PluginLang.DB_NOTIFY_CLEAN, removed));
}
}
public abstract Connection getConnection() throws SQLException;
/**
* Commits changes to the .db file when using SQLite Database.
* <p>
* MySQL has Auto Commit enabled.
*/
public void commit(Connection connection) {
try {
if (!usingMySQL) {
connection.commit();
}
} catch (SQLException e) {
if (!e.getMessage().contains("cannot commit")) {
Log.toLog(this.getClass(), e);
}
} finally {
returnToPool(connection);
}
}
public abstract void commit(Connection connection);
public void returnToPool(Connection connection) {
try {
if (usingMySQL && connection != null) {
connection.close();
}
} catch (SQLException e) {
Log.toLog(this.getClass(), e);
}
}
public abstract void returnToPool(Connection connection);
/**
* Reverts transaction when using SQLite Database.
@ -344,6 +292,28 @@ public abstract class SQLDB extends Database {
}
}
public boolean execute(String sql) {
return execute(new ExecStatement(sql) {
@Override
public void prepare(PreparedStatement statement) {
// Statement is ready for execution.
}
});
}
public void executeUnsafe(String... statements) {
Verify.nullCheck(statements);
for (String statement : statements) {
try {
execute(statement);
} catch (DBOpException e) {
if (Settings.DEV_MODE.isTrue()) {
Log.toLog(this.getClass(), e);
}
}
}
}
public void executeBatch(ExecStatement statement) {
Connection connection = null;
try {

View File

@ -2,16 +2,18 @@ package com.djrapitops.plan.system.database.databases.sql;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.utilities.MiscUtils;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.ITask;
import com.djrapitops.plugin.task.RunnableFactory;
import org.apache.commons.dbcp2.BasicDataSource;
import java.io.File;
import java.sql.*;
import java.util.Objects;
import java.util.function.Supplier;
/**
* @author Rsl1122
@ -23,25 +25,20 @@ public class SQLiteDB extends SQLDB {
private Connection connection;
private ITask connectionPingTask;
/**
* Class Constructor.
*/
public SQLiteDB() {
this("database");
public SQLiteDB(Supplier<Locale> locale) {
this("database", locale);
}
public SQLiteDB(String dbName) {
this(new File(PlanPlugin.getInstance().getDataFolder(), dbName + ".db"));
public SQLiteDB(String dbName, Supplier<Locale> locale) {
this(new File(PlanPlugin.getInstance().getDataFolder(), dbName + ".db"), locale);
}
public SQLiteDB(File databaseFile) {
public SQLiteDB(File databaseFile, Supplier<Locale> locale) {
super(locale);
dbName = databaseFile.getName();
this.databaseFile = databaseFile;
}
/**
* Setups the {@link BasicDataSource}
*/
@Override
public void setupDataSource() throws DBInitException {
try {
@ -72,7 +69,7 @@ public class SQLiteDB extends SQLDB {
try {
return DriverManager.getConnection("jdbc:sqlite:" + dbFilePath + "?journal_mode=WAL");
} catch (SQLException ignored) {
Log.info("SQLite WAL mode not supported on this server version, using default. This may or may not affect performance.");
Log.info(locale.get().getString(PluginLang.DB_NOTIFY_SQLITE_WAL));
return DriverManager.getConnection("jdbc:sqlite:" + dbFilePath);
}
}
@ -92,7 +89,7 @@ public class SQLiteDB extends SQLDB {
resultSet = statement.executeQuery("/* ping */ SELECT 1");
}
} catch (SQLException e) {
Log.debug("Something went wrong during Ping task.");
Log.debug("Something went wrong during SQLite Connection upkeep task.");
try {
connection = getNewConnection(databaseFile);
} catch (SQLException e1) {
@ -144,6 +141,22 @@ public class SQLiteDB extends SQLDB {
super.close();
}
@Override
public void commit(Connection connection) {
try {
connection.commit();
} catch (SQLException e) {
if (!e.getMessage().contains("cannot commit")) {
Log.toLog(this.getClass(), e);
}
}
}
@Override
public void returnToPool(Connection connection) {
// Connection pool not in use, no action required.
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
@ -155,7 +168,6 @@ public class SQLiteDB extends SQLDB {
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), dbName);
}
}

View File

@ -1,6 +1,7 @@
package com.djrapitops.plan.system.database.databases.sql;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plugin.api.utility.log.Log;
import org.spongepowered.api.Sponge;
@ -9,6 +10,7 @@ import org.spongepowered.api.service.sql.SqlService;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;
import java.util.function.Supplier;
/**
* MySQLDB implementation for Sponge since default driver is not available.
@ -17,6 +19,10 @@ import java.util.Optional;
*/
public class SpongeMySQLDB extends MySQLDB {
public SpongeMySQLDB(Supplier<Locale> locale) {
super(locale);
}
@Override
public void setupDataSource() throws DBInitException {
Optional<SqlService> sqlServiceProvider = Sponge.getServiceManager().provide(SqlService.class);

View File

@ -16,8 +16,4 @@ public class SQLCountOps extends SQLOps implements CountOperations {
return userInfoTable.getServerUserCount(server);
}
@Override
public int getNetworkPlayerCount() {
return usersTable.getPlayerCount();
}
}

View File

@ -0,0 +1,23 @@
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.tables.GeoInfoTable;
public class GeoInfoLastUsedPatch extends Patch {
public GeoInfoLastUsedPatch(SQLDB db) {
super(db);
}
@Override
public boolean hasBeenApplied() {
return hasColumn(GeoInfoTable.TABLE_NAME, GeoInfoTable.Col.LAST_USED.get());
}
@Override
public void apply() {
addColumns(GeoInfoTable.TABLE_NAME,
GeoInfoTable.Col.LAST_USED + " bigint NOT NULL DEFAULT 0"
);
}
}

View File

@ -0,0 +1,102 @@
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.data.container.GeoInfo;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.processing.ExecStatement;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryStatement;
import com.djrapitops.plan.system.database.databases.sql.tables.GeoInfoTable;
import com.djrapitops.plan.system.database.databases.sql.tables.move.Version18TransferTable;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plugin.api.utility.log.Log;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class IPAnonPatch extends Patch {
public IPAnonPatch(SQLDB db) {
super(db);
}
@Override
public boolean hasBeenApplied() {
String sql = "SELECT * FROM " + GeoInfoTable.TABLE_NAME +
" WHERE " + GeoInfoTable.Col.IP + " NOT LIKE ? LIMIT 1";
return query(new QueryStatement<Boolean>(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, "%x%");
}
@Override
public Boolean processResults(ResultSet set) throws SQLException {
return !set.next();
}
});
}
@Override
public void apply() {
Map<UUID, List<GeoInfo>> allGeoInfo = db.getGeoInfoTable().getAllGeoInfo();
anonymizeIPs(allGeoInfo);
groupHashedIPs();
}
private void anonymizeIPs(Map<UUID, List<GeoInfo>> allGeoInfo) {
String sql = "UPDATE " + GeoInfoTable.TABLE_NAME + " SET " +
GeoInfoTable.Col.IP + "=?, " +
GeoInfoTable.Col.IP_HASH + "=? " +
"WHERE " + GeoInfoTable.Col.IP + "=?";
db.executeBatch(new ExecStatement(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
for (List<GeoInfo> geoInfos : allGeoInfo.values()) {
for (GeoInfo geoInfo : geoInfos) {
addToBatch(statement, geoInfo);
}
}
}
private void addToBatch(PreparedStatement statement, GeoInfo geoInfo) throws SQLException {
try {
String oldIP = geoInfo.getIp();
if (oldIP.endsWith(".xx.xx") || oldIP.endsWith("xx..")) {
return;
}
GeoInfo updatedInfo = new GeoInfo(
InetAddress.getByName(oldIP),
geoInfo.getGeolocation(),
geoInfo.getDate()
);
statement.setString(1, updatedInfo.getIp());
statement.setString(2, updatedInfo.getIpHash());
statement.setString(3, geoInfo.getIp());
statement.addBatch();
} catch (UnknownHostException | NoSuchAlgorithmException e) {
if (Settings.DEV_MODE.isTrue()) {
Log.toLog(this.getClass(), e);
}
}
}
});
}
private void groupHashedIPs() {
try {
new Version18TransferTable(db).alterTableV18();
} catch (DBInitException e) {
throw new DBOpException(e.getMessage(), e);
}
}
}

View File

@ -0,0 +1,21 @@
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.tables.GeoInfoTable;
public class IPHashPatch extends Patch {
public IPHashPatch(SQLDB db) {
super(db);
}
@Override
public boolean hasBeenApplied() {
return hasColumn(GeoInfoTable.TABLE_NAME, GeoInfoTable.Col.IP_HASH.get());
}
@Override
public void apply() {
addColumns(GeoInfoTable.Col.IP_HASH.get() + " varchar(200) DEFAULT ''");
}
}

View File

@ -0,0 +1,64 @@
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.processing.ExecStatement;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryStatement;
import com.djrapitops.plan.system.database.databases.sql.tables.KillsTable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
public class KillsServerIDPatch extends Patch {
public KillsServerIDPatch(SQLDB db) {
super(db);
}
@Override
public boolean hasBeenApplied() {
String tableName = KillsTable.TABLE_NAME;
String columnName = KillsTable.Col.SERVER_ID.get();
return hasColumn(tableName, columnName) && allValuesHaveServerID(tableName, columnName);
}
private Boolean allValuesHaveServerID(String tableName, String columnName) {
String sql = "SELECT * FROM " + tableName + " WHERE " + columnName + "=? LIMIT 1";
return query(new QueryStatement<Boolean>(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setInt(1, 0);
}
@Override
public Boolean processResults(ResultSet set) throws SQLException {
return !set.next();
}
});
}
@Override
public void apply() {
addColumns(KillsTable.Col.SERVER_ID + " integer NOT NULL DEFAULT 0");
Map<Integer, Integer> sessionIDServerIDRelation = db.getSessionsTable().getIDServerIDRelation();
String sql = "UPDATE " + KillsTable.TABLE_NAME + " SET " +
KillsTable.Col.SERVER_ID + "=?" +
" WHERE " + KillsTable.Col.SESSION_ID + "=?";
db.executeBatch(new ExecStatement(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
for (Map.Entry<Integer, Integer> entry : sessionIDServerIDRelation.entrySet()) {
Integer sessionID = entry.getKey();
Integer serverID = entry.getValue();
statement.setInt(1, serverID);
statement.setInt(2, sessionID);
statement.addBatch();
}
}
});
}
}

View File

@ -0,0 +1,99 @@
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.data.store.objects.Nickname;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.processing.ExecStatement;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryAllStatement;
import com.djrapitops.plan.system.database.databases.sql.tables.GeoInfoTable;
import com.djrapitops.plan.system.database.databases.sql.tables.NicknamesTable;
import com.djrapitops.plan.system.database.databases.sql.tables.UserIDTable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public class NicknameLastSeenPatch extends Patch {
public NicknameLastSeenPatch(SQLDB db) {
super(db);
}
@Override
public boolean hasBeenApplied() {
return hasColumn(GeoInfoTable.TABLE_NAME, GeoInfoTable.Col.LAST_USED.get());
}
@Override
public void apply() {
addColumns(NicknamesTable.TABLE_NAME,
NicknamesTable.Col.LAST_USED + " bigint NOT NULL DEFAULT '0'"
);
// Create table if has failed already
db.executeUnsafe("CREATE TABLE IF NOT EXISTS plan_actions " +
"(action_id integer, date bigint, server_id integer, user_id integer, additional_info varchar(1))");
Map<Integer, UUID> serverUUIDsByID = db.getServerTable().getServerUUIDsByID();
Map<UUID, Integer> serverIDsByUUID = new HashMap<>();
for (Map.Entry<Integer, UUID> entry : serverUUIDsByID.entrySet()) {
serverIDsByUUID.put(entry.getValue(), entry.getKey());
}
Map<Integer, Set<Nickname>> nicknames = getNicknamesByUserID(serverUUIDsByID);
updateLastUsed(serverIDsByUUID, nicknames);
db.executeUnsafe("DROP TABLE plan_actions");
}
private Map<Integer, Set<Nickname>> getNicknamesByUserID(Map<Integer, UUID> serverUUIDsByID) {
String fetchSQL = "SELECT * FROM plan_actions WHERE action_id=3 ORDER BY date DESC";
return query(new QueryAllStatement<Map<Integer, Set<Nickname>>>(fetchSQL, 10000) {
@Override
public Map<Integer, Set<Nickname>> processResults(ResultSet set) throws SQLException {
Map<Integer, Set<Nickname>> map = new HashMap<>();
while (set.next()) {
long date = set.getLong("date");
int userID = set.getInt(UserIDTable.Col.USER_ID.get());
int serverID = set.getInt("server_id");
UUID serverUUID = serverUUIDsByID.get(serverID);
Nickname nick = new Nickname(set.getString("additional_info"), date, serverUUID);
Set<Nickname> nicknames1 = map.getOrDefault(userID, new HashSet<>());
if (serverUUID == null || nicknames1.contains(nick)) {
continue;
}
nicknames1.add(nick);
map.put(userID, nicknames1);
}
return map;
}
});
}
private void updateLastUsed(Map<UUID, Integer> serverIDsByUUID, Map<Integer, Set<Nickname>> nicknames) {
String updateSQL = "UPDATE " + NicknamesTable.TABLE_NAME + " SET " + NicknamesTable.Col.LAST_USED + "=?" +
" WHERE " + NicknamesTable.Col.NICKNAME + "=?" +
" AND " + NicknamesTable.Col.USER_ID + "=?" +
" AND " + NicknamesTable.Col.SERVER_ID + "=?";
db.executeBatch(new ExecStatement(updateSQL) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
for (Map.Entry<Integer, Set<Nickname>> entry : nicknames.entrySet()) {
Integer userId = entry.getKey();
Set<Nickname> nicks = entry.getValue();
for (Nickname nick : nicks) {
Integer serverID = serverIDsByUUID.get(nick.getServerUUID());
statement.setLong(1, nick.getDate());
statement.setString(2, nick.getName());
statement.setInt(3, userId);
statement.setInt(4, serverID);
statement.addBatch();
}
}
}
});
}
}

View File

@ -0,0 +1,94 @@
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryAllStatement;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryStatement;
import com.djrapitops.plan.system.database.databases.sql.statements.TableSqlParser;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class Patch {
protected final SQLDB db;
protected final boolean usingMySQL;
public Patch(SQLDB db) {
this.db = db;
usingMySQL = db.isUsingMySQL();
}
public abstract boolean hasBeenApplied();
public abstract void apply();
public <T> T query(QueryStatement<T> query) {
return db.query(query);
}
public boolean hasTable(String tableName) {
String sql = usingMySQL ?
"SELECT * FROM information_schema.TABLES WHERE table_name=? LIMIT 1" :
"SELECT tbl_name FROM sqlite_master WHERE tbl_name=?";
return query(new QueryStatement<Boolean>(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, tableName);
}
@Override
public Boolean processResults(ResultSet set) throws SQLException {
return set.next();
}
});
}
protected boolean hasColumn(String tableName, String columnName) {
return usingMySQL ?
query(new QueryStatement<Boolean>("SELECT * FROM information_schema.COLUMNS" +
" WHERE TABLE_NAME=? AND COLUMN_NAME=?") {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, tableName);
statement.setString(2, columnName);
}
@Override
public Boolean processResults(ResultSet set) throws SQLException {
return set.next();
}
}) :
query(new QueryAllStatement<Boolean>("PRAGMA table_info(" + tableName + ")") {
@Override
public Boolean processResults(ResultSet set) throws SQLException {
while (set.next()) {
if (columnName.equals(set.getString("name"))) {
return true;
}
}
return false;
}
});
}
protected void addColumns(String tableName, String... columnInfo) {
for (int i = 0; i < columnInfo.length; i++) {
columnInfo[i] = "ALTER TABLE " + tableName + " ADD " + (usingMySQL ? "" : "COLUMN ") + columnInfo[i];
}
db.executeUnsafe(columnInfo);
}
protected void dropTable(String name) {
db.executeUnsafe(TableSqlParser.dropTable(name));
}
protected void renameTable(String from, String to) {
String sql = usingMySQL ?
"RENAME TABLE " + from + " TO " + to :
"ALTER TABLE " + from + " RENAME TO " + to;
db.execute(sql);
}
}

View File

@ -0,0 +1,23 @@
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.tables.SessionsTable;
public class SessionAFKTimePatch extends Patch {
public SessionAFKTimePatch(SQLDB db) {
super(db);
}
@Override
public boolean hasBeenApplied() {
return hasColumn(SessionsTable.TABLE_NAME, SessionsTable.Col.AFK_TIME.get());
}
@Override
public void apply() {
addColumns(SessionsTable.TABLE_NAME,
SessionsTable.Col.AFK_TIME + " bigint NOT NULL DEFAULT 0"
);
}
}

View File

@ -0,0 +1,21 @@
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.tables.TransferTable;
public class TransferPartitionPatch extends Patch {
public TransferPartitionPatch(SQLDB db) {
super(db);
}
@Override
public boolean hasBeenApplied() {
return hasColumn(TransferTable.TABLE_NAME, TransferTable.Col.PART.get());
}
@Override
public void apply() {
addColumns(TransferTable.TABLE_NAME, TransferTable.Col.PART + " bigint NOT NULL DEFAULT 0");
}
}

View File

@ -1,10 +1,7 @@
/*
* License is provided in the jar as LICENSE also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/LICENSE
*/
package com.djrapitops.plan.system.database.databases.sql.tables.move;
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.tables.*;
import com.djrapitops.plan.system.info.server.ServerInfo;
@ -12,24 +9,31 @@ import com.djrapitops.plugin.api.Benchmark;
import java.util.Optional;
/**
* Class used for executing transfer queries when the database has version 8.
* <p>
* Changes the DB Schema to 10.
*
* @author Rsl1122
*/
public class Version8TransferTable extends TransferTable {
public class Version10Patch extends Patch {
private final int serverID;
private Integer serverID;
public Version8TransferTable(SQLDB db) {
public Version10Patch(SQLDB db) {
super(db);
Optional<Integer> serverID = db.getServerTable().getServerID(ServerInfo.getServerUUID());
if (!serverID.isPresent()) {
throw new IllegalStateException("Server UUID was not registered, try rebooting the plugin.");
}
@Override
public boolean hasBeenApplied() {
return !hasTable("plan_gamemodetimes");
}
@Override
public void apply() {
try {
Optional<Integer> fetchedServerID = db.getServerTable().getServerID(ServerInfo.getServerUUID());
if (!fetchedServerID.isPresent()) {
throw new IllegalStateException("Server UUID was not registered, try rebooting the plugin.");
}
serverID = fetchedServerID.get();
alterTablesToV10();
} catch (DBInitException e) {
throw new DBOpException(e.getMessage(), e);
}
this.serverID = serverID.get();
}
public void alterTablesToV10() throws DBInitException {
@ -52,8 +56,6 @@ public class Version8TransferTable extends TransferTable {
dropTable("temp_nicks");
dropTable("temp_kills");
dropTable("temp_users");
db.setVersion(10);
Benchmark.stop("Schema copy from 8 to 10");
}
@ -80,40 +82,32 @@ public class Version8TransferTable extends TransferTable {
userInfoTable.createTable();
String statement = "INSERT INTO plan_users " +
"(" +
"id, uuid, registered, name" +
") SELECT " +
"id, uuid, registered, name" +
"(id, uuid, registered, name)" +
" SELECT id, uuid, registered, name" +
" FROM " + tempTableName;
execute(statement);
db.execute(statement);
statement = "INSERT INTO plan_user_info " +
"(" +
"user_id, registered, opped, banned, server_id" +
") SELECT " +
"id, registered, opped, banned, '" + serverID + "'" +
"(user_id, registered, opped, banned, server_id)" +
" SELECT id, registered, opped, banned, '" + serverID + "'" +
" FROM " + tempTableName;
execute(statement);
db.execute(statement);
statement = "INSERT INTO plan_nicknames " +
"(" +
"user_id, nickname, server_id" +
") SELECT " +
"user_id, nickname, '" + serverID + "'" +
"(user_id, nickname, server_id)" +
" SELECT user_id, nickname, '" + serverID + "'" +
" FROM " + tempNickTableName;
execute(statement);
db.execute(statement);
try {
if (usingMySQL) {
execute("SET foreign_key_checks = 0");
db.execute("SET foreign_key_checks = 0");
}
statement = "INSERT INTO plan_kills " +
"(" +
"killer_id, victim_id, weapon, date, session_id" +
") SELECT " +
"killer_id, victim_id, weapon, date, '0'" +
"(killer_id, victim_id, weapon, date, session_id)" +
" SELECT killer_id, victim_id, weapon, date, '0'" +
" FROM " + tempKillsTableName;
execute(statement);
db.execute(statement);
} finally {
if (usingMySQL) {
execute("SET foreign_key_checks = 1");
db.execute("SET foreign_key_checks = 1");
}
}
}
@ -127,12 +121,10 @@ public class Version8TransferTable extends TransferTable {
commandUseTable.createTable();
String statement = "INSERT INTO plan_commandusages " +
"(" +
"command, times_used, server_id" +
") SELECT " +
"command, times_used, '" + serverID + "'" +
"(command, times_used, server_id)" +
" SELECT command, times_used, '" + serverID + "'" +
" FROM " + tempTableName;
execute(statement);
db.execute(statement);
dropTable(tempTableName);
}
@ -146,12 +138,10 @@ public class Version8TransferTable extends TransferTable {
tpsTable.createTable();
String statement = "INSERT INTO plan_tps " +
"(" +
"date, tps, players_online, cpu_usage, ram_usage, entities, chunks_loaded, server_id" +
") SELECT " +
"date, tps, players_online, cpu_usage, ram_usage, entities, chunks_loaded, '" + serverID + "'" +
"(date, tps, players_online, cpu_usage, ram_usage, entities, chunks_loaded, server_id)" +
" SELECT date, tps, players_online, cpu_usage, ram_usage, entities, chunks_loaded, '" + serverID + "'" +
" FROM " + tempTableName;
execute(statement);
db.execute(statement);
dropTable(tempTableName);
}

View File

@ -0,0 +1,20 @@
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
public class VersionTableRemovalPatch extends Patch {
public VersionTableRemovalPatch(SQLDB db) {
super(db);
}
@Override
public boolean hasBeenApplied() {
return hasTable("plan_version");
}
@Override
public void apply() {
dropTable("plan_version");
}
}

View File

@ -0,0 +1,63 @@
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.processing.ExecStatement;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryStatement;
import com.djrapitops.plan.system.database.databases.sql.tables.WorldTimesTable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
public class WorldTimesSeverIDPatch extends Patch {
public WorldTimesSeverIDPatch(SQLDB db) {
super(db);
}
@Override
public boolean hasBeenApplied() {
String tableName = WorldTimesTable.TABLE_NAME;
String columnName = WorldTimesTable.Col.SERVER_ID.get();
return hasColumn(tableName, columnName)
&& allValuesHaveServerID(tableName, columnName);
}
private Boolean allValuesHaveServerID(String tableName, String columnName) {
String sql = "SELECT * FROM " + tableName + " WHERE " + columnName + "=? LIMIT 1";
return query(new QueryStatement<Boolean>(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setInt(1, 0);
}
@Override
public Boolean processResults(ResultSet set) throws SQLException {
return !set.next();
}
});
}
@Override
public void apply() {
Map<Integer, Integer> sessionIDServerIDRelation = db.getSessionsTable().getIDServerIDRelation();
String sql = "UPDATE " + WorldTimesTable.TABLE_NAME + " SET " +
WorldTimesTable.Col.SERVER_ID + "=?" +
" WHERE " + WorldTimesTable.Col.SESSION_ID + "=?";
db.executeBatch(new ExecStatement(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
for (Map.Entry<Integer, Integer> entry : sessionIDServerIDRelation.entrySet()) {
Integer sessionID = entry.getKey();
Integer serverID = entry.getValue();
statement.setInt(1, serverID);
statement.setInt(2, sessionID);
statement.addBatch();
}
}
});
}
}

View File

@ -0,0 +1,188 @@
package com.djrapitops.plan.system.database.databases.sql.patches;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.processing.ExecStatement;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryAllStatement;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryStatement;
import com.djrapitops.plan.system.database.databases.sql.tables.SessionsTable;
import com.djrapitops.plan.system.database.databases.sql.tables.WorldTable;
import com.djrapitops.plan.system.database.databases.sql.tables.WorldTimesTable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class WorldsServerIDPatch extends Patch {
public WorldsServerIDPatch(SQLDB db) {
super(db);
}
@Override
public boolean hasBeenApplied() {
String tableName = WorldTable.TABLE_NAME;
String columnName = WorldTable.Col.SERVER_ID.get();
return hasColumn(tableName, columnName)
&& allValuesHaveServerID(tableName, columnName);
}
private Boolean allValuesHaveServerID(String tableName, String columnName) {
String sql = "SELECT * FROM " + tableName + " WHERE " + columnName + "=? LIMIT 1";
return query(new QueryStatement<Boolean>(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setInt(1, 0);
}
@Override
public Boolean processResults(ResultSet set) throws SQLException {
return !set.next();
}
});
}
@Override
public void apply() {
WorldTable worldTable = db.getWorldTable();
List<UUID> serverUUIDs = db.getServerTable().getServerUUIDs();
Map<UUID, Set<String>> worldsPerServer = new HashMap<>();
for (UUID serverUUID : serverUUIDs) {
worldsPerServer.put(serverUUID, getWorldNamesOld(serverUUID));
}
for (Map.Entry<UUID, Set<String>> entry : worldsPerServer.entrySet()) {
UUID serverUUID = entry.getKey();
Set<String> worlds = entry.getValue();
worldTable.saveWorlds(worlds, serverUUID);
}
updateWorldTimesTableWorldIDs();
db.executeUnsafe("DELETE FROM " + WorldTable.TABLE_NAME + " WHERE " + WorldTable.Col.SERVER_ID + "=0");
}
private Set<String> getWorldNamesOld(UUID serverUUID) {
WorldTimesTable worldTimesTable = db.getWorldTimesTable();
SessionsTable sessionsTable = db.getSessionsTable();
String statementSelectServerID = db.getServerTable().statementSelectServerID;
String worldIDColumn = worldTimesTable + "." + WorldTimesTable.Col.WORLD_ID;
String worldSessionIDColumn = worldTimesTable + "." + WorldTimesTable.Col.SESSION_ID;
String sessionIDColumn = sessionsTable + "." + SessionsTable.Col.ID;
String sessionServerIDColumn = sessionsTable + "." + SessionsTable.Col.SERVER_ID;
String sql = "SELECT DISTINCT " +
WorldTable.Col.NAME + " FROM " +
WorldTable.TABLE_NAME +
" INNER JOIN " + worldTimesTable + " on " + worldIDColumn + "=" + WorldTable.TABLE_NAME + "." + WorldTable.Col.ID +
" INNER JOIN " + sessionsTable + " on " + worldSessionIDColumn + "=" + sessionIDColumn +
" WHERE " + statementSelectServerID + "=" + sessionServerIDColumn;
return query(new QueryStatement<Set<String>>(sql, 1000) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, serverUUID.toString());
}
@Override
public Set<String> processResults(ResultSet set) throws SQLException {
Set<String> worldNames = new HashSet<>();
while (set.next()) {
worldNames.add(set.getString(WorldTable.Col.NAME.get()));
}
return worldNames;
}
});
}
private void updateWorldTimesTableWorldIDs() {
List<WorldObj> worldObjects = getWorldObjects();
Map<WorldObj, List<WorldObj>> oldToNewMap =
worldObjects.stream()
.filter(worldObj -> worldObj.serverId == 0)
.collect(Collectors.toMap(
Function.identity(),
oldWorld -> worldObjects.stream()
.filter(worldObj -> worldObj.serverId != 0)
.filter(worldObj -> worldObj.equals(oldWorld))
.collect(Collectors.toList()
)));
WorldTimesTable worldTimesTable = db.getWorldTimesTable();
String sql = "UPDATE " + worldTimesTable + " SET " +
WorldTimesTable.Col.WORLD_ID + "=?" +
" WHERE " + WorldTimesTable.Col.WORLD_ID + "=?" +
" AND " + WorldTimesTable.Col.SERVER_ID + "=?";
db.executeBatch(new ExecStatement(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
for (Map.Entry<WorldObj, List<WorldObj>> entry : oldToNewMap.entrySet()) {
WorldObj old = entry.getKey();
for (WorldObj newWorld : entry.getValue()) {
statement.setInt(1, newWorld.id);
statement.setInt(2, old.id);
statement.setInt(3, newWorld.serverId);
statement.addBatch();
}
}
}
});
}
public List<WorldObj> getWorldObjects() {
String sql = "SELECT * FROM " + WorldTable.TABLE_NAME;
return query(new QueryAllStatement<List<WorldObj>>(sql, 100) {
@Override
public List<WorldObj> processResults(ResultSet set) throws SQLException {
List<WorldObj> objects = new ArrayList<>();
while (set.next()) {
int worldID = set.getInt(WorldTable.Col.ID.get());
int serverID = set.getInt(WorldTable.Col.SERVER_ID.get());
String worldName = set.getString(WorldTable.Col.NAME.get());
objects.add(new WorldObj(worldID, serverID, worldName));
}
return objects;
}
});
}
}
class WorldObj {
final int id;
final int serverId;
final String name;
public WorldObj(int id, int serverId, String name) {
this.id = id;
this.serverId = serverId;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WorldObj worldObj = (WorldObj) o;
return Objects.equals(name, worldObj.name);
}
@Override
public int hashCode() {
return Objects.hashCode(name);
}
@Override
public String toString() {
return "{" +
"id=" + id +
", serverId=" + serverId +
", name='" + name + '\'' +
'}';
}
}

View File

@ -1,7 +1,6 @@
package com.djrapitops.plan.system.database.databases.sql.tables;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.data.container.GeoInfo;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.processing.ExecStatement;
@ -11,18 +10,9 @@ import com.djrapitops.plan.system.database.databases.sql.statements.Column;
import com.djrapitops.plan.system.database.databases.sql.statements.Select;
import com.djrapitops.plan.system.database.databases.sql.statements.Sql;
import com.djrapitops.plan.system.database.databases.sql.statements.TableSqlParser;
import com.djrapitops.plan.system.database.databases.sql.tables.move.Version18TransferTable;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plan.utilities.comparators.GeoInfoComparator;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.RunnableFactory;
import com.djrapitops.plugin.utilities.Verify;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@ -39,8 +29,10 @@ import java.util.*;
*/
public class GeoInfoTable extends UserIDTable {
public static final String TABLE_NAME = "plan_ips";
public GeoInfoTable(SQLDB db) {
super("plan_ips", db);
super(TABLE_NAME, db);
insertStatement = "INSERT INTO " + tableName + " ("
+ Col.USER_ID + ", "
+ Col.IP + ", "
@ -67,71 +59,6 @@ public class GeoInfoTable extends UserIDTable {
);
}
public void alterTableV12() {
if (usingMySQL) {
executeUnsafe("ALTER TABLE " + tableName + " MODIFY " + Col.IP + " VARCHAR(39) NOT NULL");
}
}
public void alterTableV13() {
addColumns(Col.LAST_USED + " bigint NOT NULL DEFAULT 0");
}
public void alterTableV17() {
addColumns(Col.IP_HASH.get() + " varchar(200) DEFAULT ''");
}
public void alterTableV18() {
RunnableFactory.createNew("DB Version 17->18", new AbsRunnable() {
@Override
public void run() {
try {
Map<UUID, List<GeoInfo>> allGeoInfo = getAllGeoInfo();
String sql = "UPDATE " + tableName + " SET " +
Col.IP + "=?, " +
Col.IP_HASH + "=? " +
"WHERE " + Col.IP + "=?";
executeBatch(new ExecStatement(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
for (List<GeoInfo> geoInfos : allGeoInfo.values()) {
for (GeoInfo geoInfo : geoInfos) {
try {
if (geoInfo.getIp().endsWith(".xx.xx")) {
continue;
}
GeoInfo updatedInfo = new GeoInfo(
InetAddress.getByName(geoInfo.getIp()),
geoInfo.getGeolocation(),
geoInfo.getDate()
);
statement.setString(1, updatedInfo.getIp());
statement.setString(2, updatedInfo.getIpHash());
statement.setString(3, geoInfo.getIp());
statement.addBatch();
} catch (UnknownHostException | UnsupportedEncodingException | NoSuchAlgorithmException e) {
if (Settings.DEV_MODE.isTrue()) {
Log.toLog(this.getClass(), e);
}
}
}
}
}
});
new Version18TransferTable(db).alterTableV18();
db.setVersion(18);
} catch (DBOpException | DBInitException e) {
Log.toLog(this.getClass(), e);
}
}
}).runTaskAsynchronously();
}
public void clean() {
}
public List<GeoInfo> getGeoInfo(UUID uuid) {
String sql = "SELECT DISTINCT * FROM " + tableName +
" WHERE " + Col.USER_ID + "=" + usersTable.statementSelectID;

View File

@ -31,10 +31,11 @@ import java.util.*;
*/
public class KillsTable extends UserIDTable {
public static final String TABLE_NAME = "plan_kills";
private final ServerTable serverTable;
public KillsTable(SQLDB db) {
super("plan_kills", db);
super(TABLE_NAME, db);
sessionsTable = db.getSessionsTable();
serverTable = db.getServerTable();
insertStatement = "INSERT INTO " + tableName + " ("
@ -304,29 +305,6 @@ public class KillsTable extends UserIDTable {
});
}
public void alterTableV16() {
addColumns(Col.SERVER_ID + " integer NOT NULL DEFAULT 0");
Map<Integer, Integer> sessionIDServerIDRelation = sessionsTable.getIDServerIDRelation();
String sql = "UPDATE " + tableName + " SET " +
Col.SERVER_ID + "=?" +
" WHERE " + Col.SESSION_ID + "=?";
executeBatch(new ExecStatement(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
for (Map.Entry<Integer, Integer> entry : sessionIDServerIDRelation.entrySet()) {
Integer sessionID = entry.getKey();
Integer serverID = entry.getValue();
statement.setInt(1, serverID);
statement.setInt(2, sessionID);
statement.addBatch();
}
}
});
}
public enum Col implements Column {
KILLER_ID("killer_id"),
VICTIM_ID("victim_id"),

View File

@ -10,8 +10,6 @@ import com.djrapitops.plan.system.database.databases.sql.statements.Column;
import com.djrapitops.plan.system.database.databases.sql.statements.Sql;
import com.djrapitops.plan.system.database.databases.sql.statements.TableSqlParser;
import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.RunnableFactory;
import com.djrapitops.plugin.utilities.Verify;
import java.sql.PreparedStatement;
@ -30,12 +28,13 @@ import java.util.*;
*/
public class NicknamesTable extends UserIDTable {
public static final String TABLE_NAME = "plan_nicknames";
private final ServerTable serverTable;
private String insertStatement;
private final String updateStatement;
public NicknamesTable(SQLDB db) {
super("plan_nicknames", db);
super(TABLE_NAME, db);
serverTable = db.getServerTable();
insertStatement = "INSERT INTO " + tableName + " (" +
Col.USER_ID + ", " +
@ -65,117 +64,6 @@ public class NicknamesTable extends UserIDTable {
);
}
public void alterTableV19() {
addColumns(Col.LAST_USED + " bigint NOT NULL DEFAULT '0'");
RunnableFactory.createNew(new AbsRunnable("DB version 18->19") {
@Override
public void run() {
// Create actions table if version 18 transfer is run concurrently.
execute("CREATE TABLE IF NOT EXISTS plan_actions " +
"(action_id integer, date bigint, server_id integer, user_id integer, additional_info varchar(1))");
Map<Integer, UUID> serverUUIDsByID = serverTable.getServerUUIDsByID();
Map<UUID, Integer> serverIDsByUUID = new HashMap<>();
for (Map.Entry<Integer, UUID> entry : serverUUIDsByID.entrySet()) {
serverIDsByUUID.put(entry.getValue(), entry.getKey());
}
String fetchSQL = "SELECT * FROM plan_actions WHERE action_id=3 ORDER BY date DESC";
Map<Integer, Set<Nickname>> nicknames = query(new QueryAllStatement<Map<Integer, Set<Nickname>>>(fetchSQL, 10000) {
@Override
public Map<Integer, Set<Nickname>> processResults(ResultSet set) throws SQLException {
Map<Integer, Set<Nickname>> map = new HashMap<>();
while (set.next()) {
long date = set.getLong("date");
int userID = set.getInt(UserIDTable.Col.USER_ID.get());
int serverID = set.getInt("server_id");
UUID serverUUID = serverUUIDsByID.get(serverID);
Nickname nick = new Nickname(set.getString("additional_info"), date, serverUUID);
Set<Nickname> nicknames = map.getOrDefault(userID, new HashSet<>());
if (serverUUID == null || nicknames.contains(nick)) {
continue;
}
nicknames.add(nick);
map.put(userID, nicknames);
}
return map;
}
});
String updateSQL = "UPDATE " + tableName + " SET " + Col.LAST_USED + "=?" +
" WHERE " + Col.NICKNAME + "=?" +
" AND " + Col.USER_ID + "=?" +
" AND " + Col.SERVER_ID + "=?";
executeBatch(new ExecStatement(updateSQL) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
for (Map.Entry<Integer, Set<Nickname>> entry : nicknames.entrySet()) {
Integer userId = entry.getKey();
Set<Nickname> nicks = entry.getValue();
for (Nickname nick : nicks) {
Integer serverID = serverIDsByUUID.get(nick.getServerUUID());
statement.setLong(1, nick.getDate());
statement.setString(2, nick.getName());
statement.setInt(3, userId);
statement.setInt(4, serverID);
statement.addBatch();
}
}
}
});
db.setVersion(19);
executeUnsafe("DROP TABLE plan_actions");
}
}).runTaskAsynchronously();
}
/**
* Get ALL nicknames of the user by Server UUID.
* <p>
* Get's nicknames from other servers as well.
*
* @param uuid UUID of the Player
* @return The nicknames of the User in a map by ServerUUID
*/
public Map<UUID, List<String>> getAllNicknames(UUID uuid) {
String serverIDColumn = serverTable + "." + ServerTable.Col.SERVER_ID;
String serverUUIDColumn = serverTable + "." + ServerTable.Col.SERVER_UUID + " as s_uuid";
String sql = "SELECT " +
Col.NICKNAME + ", " +
serverUUIDColumn +
" FROM " + tableName +
" INNER JOIN " + serverTable + " on " + serverIDColumn + "=" + Col.SERVER_ID +
" WHERE (" + Col.USER_ID + "=" + usersTable.statementSelectID + ")";
return query(new QueryStatement<Map<UUID, List<String>>>(sql, 5000) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, uuid.toString());
}
@Override
public Map<UUID, List<String>> processResults(ResultSet set) throws SQLException {
Map<UUID, List<String>> map = new HashMap<>();
while (set.next()) {
UUID serverUUID = UUID.fromString(set.getString("s_uuid"));
List<String> nicknames = map.getOrDefault(serverUUID, new ArrayList<>());
nicknames.add(set.getString(Col.NICKNAME.get()));
map.put(serverUUID, nicknames);
}
return map;
}
});
}
/**
* Get nicknames of the user on a server.
* <p>

View File

@ -62,12 +62,6 @@ public class ServerTable extends Table {
);
}
public void alterTableV11() {
if (usingMySQL) {
executeUnsafe("ALTER TABLE " + tableName + " MODIFY " + Col.MAX_PLAYERS + " INTEGER NOT NULL DEFAULT -1");
}
}
private void updateServerInfo(Server info) {
String sql = Update.values(tableName,
Col.SERVER_UUID,
@ -181,24 +175,6 @@ public class ServerTable extends Table {
});
}
public Map<Integer, String> getServerNamesByID() {
String sql = Select.from(tableName,
Col.SERVER_ID, Col.NAME)
.toString();
return query(new QueryAllStatement<Map<Integer, String>>(sql) {
@Override
public Map<Integer, String> processResults(ResultSet set) throws SQLException {
Map<Integer, String> names = new HashMap<>();
while (set.next()) {
int id = set.getInt(Col.SERVER_ID.get());
names.put(id, set.getString(Col.NAME.get()));
}
return names;
}
});
}
public Map<UUID, String> getServerNames() {
String sql = Select.from(tableName,
Col.SERVER_UUID, Col.NAME)
@ -388,20 +364,6 @@ public class ServerTable extends Table {
});
}
public int getMaxPlayers() {
String sql = "SELECT SUM(" + Col.MAX_PLAYERS + ") AS max FROM " + tableName;
return query(new QueryAllStatement<Integer>(sql) {
@Override
public Integer processResults(ResultSet set) throws SQLException {
if (set.next()) {
return set.getInt("max");
}
return 0;
}
});
}
public enum Col implements Column {
SERVER_ID("id"),
SERVER_UUID("uuid"),

View File

@ -12,7 +12,6 @@ import com.djrapitops.plan.system.database.databases.sql.statements.Select;
import com.djrapitops.plan.system.database.databases.sql.statements.Sql;
import com.djrapitops.plan.system.database.databases.sql.statements.TableSqlParser;
import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.utilities.Verify;
import java.sql.PreparedStatement;
@ -265,52 +264,6 @@ public class SessionsTable extends UserIDTable {
return getPlaytime(uuid, serverUUID, 0L);
}
/**
* Used to get Playtimes after a date in a Map, sorted by ServerNames.
*
* @param uuid UUID of the Player.
* @param afterDate Epoch ms (Playtime after this date is calculated)
* @return key - ServerName, value ms played
*/
public Map<String, Long> getPlaytimeByServer(UUID uuid, long afterDate) {
Map<Integer, String> serverNames = serverTable.getServerNamesByID();
String sql = "SELECT " +
"(SUM(" + Col.SESSION_END + ") - SUM(" + Col.SESSION_START + ")) as playtime, " +
Col.SERVER_ID +
" FROM " + tableName +
" WHERE " + Col.SESSION_START + ">?" +
" AND " + Col.USER_ID + "=" + usersTable.statementSelectID +
" GROUP BY " + Col.SERVER_ID;
return query(new QueryStatement<Map<String, Long>>(sql, 100) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setLong(1, afterDate);
statement.setString(2, uuid.toString());
}
@Override
public Map<String, Long> processResults(ResultSet set) throws SQLException {
Map<String, Long> playtimes = new HashMap<>();
while (set.next()) {
String serverName = serverNames.get(set.getInt(Col.SERVER_ID.get()));
long playtime = set.getLong("playtime");
playtimes.put(serverName, playtime);
}
return playtimes;
}
});
}
/**
* Used to get Totals of Playtime in a Map, sorted by ServerNames.
*
* @param uuid UUID of the Player.
* @return key - ServerName, value ms played
*/
public Map<String, Long> getPlaytimeByServer(UUID uuid) {
return getPlaytimeByServer(uuid, 0L);
}
/**
* Used to get Playtime after a date of a Server.
*
@ -342,15 +295,6 @@ public class SessionsTable extends UserIDTable {
});
}
/**
* Used to get the Total Playtime of THIS Server.
*
* @return Milliseconds played on the server. 0 if server not found.
*/
public long getPlaytimeOfServer() {
return getPlaytimeOfServer(ServerInfo.getServerUUID());
}
/**
* Used to get the Total Playtime of a Server.
*
@ -361,16 +305,6 @@ public class SessionsTable extends UserIDTable {
return getPlaytimeOfServer(serverUUID, 0L);
}
/**
* Used to get Playtime after a date of THIS Server.
*
* @param afterDate Epoch ms (Playtime after this date is calculated)
* @return Milliseconds played after given epoch ms on the server. 0 if server not found.
*/
public long getPlaytimeOfServer(long afterDate) {
return getPlaytimeOfServer(ServerInfo.getServerUUID(), afterDate);
}
/**
* Used to get total Session count of a Player on a server after a given epoch ms.
*
@ -426,17 +360,6 @@ public class SessionsTable extends UserIDTable {
return getSessionCount(uuid, ServerInfo.getServerUUID(), afterDate);
}
/**
* Used to get total Session count of a Player on a server.
*
* @param uuid UUID of the player.
* @param serverUUID UUID of the server.
* @return How many sessions player has. 0 if player or server not found.
*/
public int getSessionCount(UUID uuid, UUID serverUUID) {
return getSessionCount(uuid, serverUUID, 0L);
}
public Map<UUID, List<Session>> getSessionInfoOfServer(UUID serverUUID) {
String usersIDColumn = usersTable + "." + UsersTable.Col.ID;
String usersUUIDColumn = usersTable + "." + UsersTable.Col.UUID + " as uuid";
@ -484,29 +407,6 @@ public class SessionsTable extends UserIDTable {
return getSessionInfoOfServer(ServerInfo.getServerUUID());
}
// TODO Write tests for this method
public long getLastSeen(UUID uuid) {
String sql = "SELECT" +
" MAX(" + Col.SESSION_END + ") as last_seen" +
" FROM " + tableName +
" WHERE " + Col.USER_ID + "=" + usersTable.statementSelectID;
return query(new QueryStatement<Long>(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, uuid.toString());
}
@Override
public Long processResults(ResultSet set) throws SQLException {
if (set.next()) {
return set.getLong("last_seen");
}
return 0L;
}
});
}
public Map<UUID, Long> getLastSeenForAllPlayers() {
String usersIDColumn = usersTable + "." + UsersTable.Col.ID;
String usersUUIDColumn = usersTable + "." + UsersTable.Col.UUID + " as uuid";
@ -581,58 +481,6 @@ public class SessionsTable extends UserIDTable {
});
}
public Map<UUID, Map<UUID, List<Session>>> getSessionInLastMonth() {
Map<Integer, UUID> uuidsByID = usersTable.getUUIDsByID();
Map<Integer, UUID> serverUUIDsByID = serverTable.getServerUUIDsByID();
String sql = "SELECT " +
Col.ID + ", " +
Col.USER_ID + ", " +
Col.SERVER_ID + ", " +
Col.SESSION_START + ", " +
Col.SESSION_END + ", " +
Col.DEATHS + ", " +
Col.MOB_KILLS + ", " +
Col.AFK_TIME +
" FROM " + tableName +
" WHERE " + Col.SESSION_START + ">?";
return query(new QueryStatement<Map<UUID, Map<UUID, List<Session>>>>(sql, 20000) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setLong(1, System.currentTimeMillis() - TimeAmount.MONTH.ms());
}
@Override
public Map<UUID, Map<UUID, List<Session>>> processResults(ResultSet set) throws SQLException {
Map<UUID, Map<UUID, List<Session>>> map = new HashMap<>();
while (set.next()) {
UUID serverUUID = serverUUIDsByID.get(set.getInt(Col.SERVER_ID.get()));
UUID uuid = uuidsByID.get(set.getInt(Col.USER_ID.get()));
Map<UUID, List<Session>> sessionsByUser = map.getOrDefault(serverUUID, new HashMap<>());
List<Session> sessions = sessionsByUser.getOrDefault(uuid, new ArrayList<>());
long start = set.getLong(Col.SESSION_START.get());
long end = set.getLong(Col.SESSION_END.get());
int deaths = set.getInt(Col.DEATHS.get());
int mobKills = set.getInt(Col.MOB_KILLS.get());
int id = set.getInt(Col.ID.get());
long timeAFK = set.getLong(Col.AFK_TIME.get());
Session session = new Session(id, uuid, serverUUID, start, end, mobKills, deaths, timeAFK);
sessions.add(session);
sessionsByUser.put(uuid, sessions);
map.put(serverUUID, sessionsByUser);
}
return map;
}
});
}
public void insertSessions(Map<UUID, Map<UUID, List<Session>>> allSessions, boolean saveKillsAndWorldTimes) {
if (Verify.isEmpty(allSessions)) {
return;
@ -729,10 +577,6 @@ public class SessionsTable extends UserIDTable {
return sessionsByStart;
}
public void alterTableV15() {
addColumns(Col.AFK_TIME + " bigint NOT NULL DEFAULT 0");
}
public Map<Integer, Integer> getIDServerIDRelation() {
String sql = "SELECT " +
Col.ID + ", " +

View File

@ -5,14 +5,10 @@ import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.processing.ExecStatement;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryStatement;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plan.utilities.MiscUtils;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.utilities.Verify;
import com.google.common.base.Objects;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
@ -67,17 +63,6 @@ public abstract class Table {
return db.getConnection();
}
/**
* Get the Database Schema version from VersionTable.
*
* @return Database Schema version.
* @deprecated Use db.getVersion - db is protected variable.
*/
@Deprecated
public int getVersion() {
return db.getVersion();
}
/**
* Executes an SQL Statement
*
@ -85,12 +70,7 @@ public abstract class Table {
* @return true if rows were updated.
*/
protected boolean execute(String statementString) {
return execute(new ExecStatement(statementString) {
@Override
public void prepare(PreparedStatement statement) {
/* No preparations necessary */
}
});
return db.execute(statementString);
}
/**
@ -99,16 +79,7 @@ public abstract class Table {
* @param statements SQL statements to setUp
*/
protected void executeUnsafe(String... statements) {
Verify.nullCheck(statements);
for (String statement : statements) {
try {
execute(statement);
} catch (DBOpException e) {
if (Settings.DEV_MODE.isTrue()) {
Log.toLog(this.getClass(), e);
}
}
}
db.executeUnsafe(statements);
}
/**

View File

@ -30,13 +30,14 @@ import java.util.Optional;
*/
public class TransferTable extends Table {
public static final String TABLE_NAME = "plan_transfer";
private final String insertStatementNoParts;
private final ServerTable serverTable;
private final String selectStatement;
public TransferTable(SQLDB db) {
super("plan_transfer", db);
super(TABLE_NAME, db);
serverTable = db.getServerTable();
insertStatementNoParts = "REPLACE INTO " + tableName + " (" +
@ -70,10 +71,6 @@ public class TransferTable extends Table {
);
}
public void alterTableV14() {
addColumns(Col.PART + " bigint NOT NULL DEFAULT 0");
}
public void clean() {
String sql = "DELETE FROM " + tableName +
" WHERE " + Col.EXPIRY + " < ?" +

View File

@ -290,36 +290,6 @@ public class UserInfoTable extends UserIDTable {
});
}
public Map<UUID, Set<UUID>> getSavedUUIDs() {
String usersIDColumn = usersTable + "." + UsersTable.Col.ID;
String usersUUIDColumn = usersTable + "." + UsersTable.Col.UUID + " as uuid";
String serverIDColumn = serverTable + "." + ServerTable.Col.SERVER_ID;
String serverUUIDColumn = serverTable + "." + ServerTable.Col.SERVER_UUID + " as s_uuid";
String sql = "SELECT " +
usersUUIDColumn + ", " +
serverUUIDColumn +
" FROM " + tableName +
" INNER JOIN " + usersTable + " on " + usersIDColumn + "=" + Col.USER_ID +
" INNER JOIN " + serverTable + " on " + serverIDColumn + "=" + Col.SERVER_ID;
return query(new QueryAllStatement<Map<UUID, Set<UUID>>>(sql, 50000) {
@Override
public Map<UUID, Set<UUID>> processResults(ResultSet set) throws SQLException {
Map<UUID, Set<UUID>> serverMap = new HashMap<>();
while (set.next()) {
UUID serverUUID = UUID.fromString(set.getString("s_uuid"));
UUID uuid = UUID.fromString(set.getString("uuid"));
Set<UUID> uuids = serverMap.getOrDefault(serverUUID, new HashSet<>());
uuids.add(uuid);
serverMap.put(serverUUID, uuids);
}
return serverMap;
}
});
}
public int getServerUserCount(UUID serverUUID) {
String sql = "SELECT " +
" COUNT(" + Col.REGISTERED + ") as c" +

View File

@ -16,7 +16,6 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Supplier;
/**
* Table that is in charge of storing common player data for all servers.
@ -382,39 +381,6 @@ public class UsersTable extends UserIDTable {
});
}
public Optional<Long> getRegisterDate(UUID uuid) {
String sql = Select.from(tableName, Col.REGISTERED).where(Col.UUID + "=?").toString();
return query(new QueryStatement<Optional<Long>>(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, uuid.toString());
}
@Override
public Optional<Long> processResults(ResultSet set) throws SQLException {
if (set.next()) {
return Optional.of(set.getLong(Col.REGISTERED.get()));
}
return Optional.empty();
}
});
}
public int getPlayerCount() {
String sql = "SELECT COUNT(*) AS player_count FROM " + tableName;
return query(new QueryAllStatement<Integer>(sql) {
@Override
public Integer processResults(ResultSet set) throws SQLException {
if (set.next()) {
return set.getInt("player_count");
}
return 0;
}
});
}
public Map<Integer, UUID> getUUIDsByID() {
String sql = Select.from(tableName, Col.ID, Col.UUID).toString();
@ -435,45 +401,45 @@ public class UsersTable extends UserIDTable {
}
public DataContainer getUserInformation(UUID uuid) {
Key<DataContainer> key = new Key<>(DataContainer.class, "plan_users_data");
Key<DataContainer> user_data = new Key<>(DataContainer.class, "plan_users_data");
DataContainer returnValue = new DataContainer();
Supplier<DataContainer> usersTableResults = () -> {
String sql = "SELECT * FROM " + tableName + " WHERE " + Col.UUID + "=?";
return query(new QueryStatement<DataContainer>(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, uuid.toString());
}
@Override
public DataContainer processResults(ResultSet set) throws SQLException {
DataContainer container = new DataContainer();
if (set.next()) {
long registered = set.getLong(Col.REGISTERED.get());
String name = set.getString(Col.USER_NAME.get());
int timesKicked = set.getInt(Col.TIMES_KICKED.get());
container.putRawData(PlayerKeys.REGISTERED, registered);
container.putRawData(PlayerKeys.NAME, name);
container.putRawData(PlayerKeys.KICK_COUNT, timesKicked);
}
return container;
}
});
};
returnValue.putSupplier(key, usersTableResults);
returnValue.putSupplier(user_data, () -> getUserInformationDataContainer(uuid));
returnValue.putRawData(PlayerKeys.UUID, uuid);
returnValue.putSupplier(PlayerKeys.REGISTERED, () -> returnValue.getUnsafe(key).getUnsafe(PlayerKeys.REGISTERED));
returnValue.putSupplier(PlayerKeys.NAME, () -> returnValue.getUnsafe(key).getUnsafe(PlayerKeys.NAME));
returnValue.putSupplier(PlayerKeys.KICK_COUNT, () -> returnValue.getUnsafe(key).getUnsafe(PlayerKeys.KICK_COUNT));
returnValue.putSupplier(PlayerKeys.REGISTERED, () -> returnValue.getUnsafe(user_data).getValue(PlayerKeys.REGISTERED).orElse(null));
returnValue.putSupplier(PlayerKeys.NAME, () -> returnValue.getUnsafe(user_data).getValue(PlayerKeys.NAME).orElse(null));
returnValue.putSupplier(PlayerKeys.KICK_COUNT, () -> returnValue.getUnsafe(user_data).getValue(PlayerKeys.KICK_COUNT).orElse(null));
return returnValue;
}
private DataContainer getUserInformationDataContainer(UUID uuid) {
String sql = "SELECT * FROM " + tableName + " WHERE " + Col.UUID + "=?";
return query(new QueryStatement<DataContainer>(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, uuid.toString());
}
@Override
public DataContainer processResults(ResultSet set) throws SQLException {
DataContainer container = new DataContainer();
if (set.next()) {
long registered = set.getLong(Col.REGISTERED.get());
String name = set.getString(Col.USER_NAME.get());
int timesKicked = set.getInt(Col.TIMES_KICKED.get());
container.putRawData(PlayerKeys.REGISTERED, registered);
container.putRawData(PlayerKeys.NAME, name);
container.putRawData(PlayerKeys.KICK_COUNT, timesKicked);
}
return container;
}
});
}
public enum Col implements Column {
ID("id"),
UUID("uuid"),

View File

@ -1,86 +0,0 @@
package com.djrapitops.plan.system.database.databases.sql.tables;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.processing.ExecStatement;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryAllStatement;
import com.djrapitops.plan.system.database.databases.sql.processing.QueryStatement;
import com.djrapitops.plan.system.database.databases.sql.statements.Sql;
import com.djrapitops.plan.system.database.databases.sql.statements.TableSqlParser;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author Rsl1122
*/
public class VersionTable extends Table {
public VersionTable(SQLDB db) {
super("plan_version", db);
}
@Override
public void createTable() throws DBInitException {
createTable(TableSqlParser.createTable(tableName)
.column("version", Sql.INT).notNull()
.toString()
);
}
public boolean isNewDatabase() {
String sql = usingMySQL ?
"SHOW TABLES LIKE ?" :
"SELECT tbl_name FROM sqlite_master WHERE tbl_name=?";
return query(new QueryStatement<Boolean>(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, tableName);
}
@Override
public Boolean processResults(ResultSet set) throws SQLException {
return !set.next();
}
});
}
/**
* @return @throws SQLException
*/
@Override
public int getVersion() {
String sql = "SELECT * FROM " + tableName;
return query(new QueryAllStatement<Integer>(sql) {
@Override
public Integer processResults(ResultSet set) throws SQLException {
int version = 0;
if (set.next()) {
version = set.getInt("version");
}
return version;
}
});
}
/**
* Set the DB Schema version
*
* @param version DB Schema version
*/
public void setVersion(int version) {
removeAllData();
String sql = "INSERT INTO " + tableName + " (version) VALUES (?)";
execute(new ExecStatement(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setInt(1, version);
}
});
}
}

View File

@ -10,14 +10,11 @@ import com.djrapitops.plan.system.database.databases.sql.statements.Sql;
import com.djrapitops.plan.system.database.databases.sql.statements.TableSqlParser;
import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plugin.utilities.Verify;
import com.google.common.base.Objects;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Table class representing database table plan_worlds.
@ -75,47 +72,6 @@ public class WorldTable extends Table {
});
}
public Map<UUID, List<String>> getWorldsPerServer() {
Map<Integer, UUID> serverUUIDsByID = serverTable.getServerUUIDsByID();
String sql = "SELECT * FROM " + tableName;
return query(new QueryAllStatement<Map<UUID, List<String>>>(sql, 1000) {
@Override
public Map<UUID, List<String>> processResults(ResultSet set) throws SQLException {
Map<UUID, List<String>> worldsPerServer = new HashMap<>();
while (set.next()) {
UUID serverUUID = serverUUIDsByID.get(set.getInt(Col.SERVER_ID.get()));
String worldName = set.getString(Col.NAME.get());
List<String> worlds = worldsPerServer.getOrDefault(serverUUID, new ArrayList<>());
worlds.add(worldName);
worldsPerServer.put(serverUUID, worlds);
}
return worldsPerServer;
}
});
}
public Map<Integer, UUID> getServerUUIDByWorldID() {
Map<Integer, UUID> serverUUIDsByID = serverTable.getServerUUIDsByID();
String sql = "SELECT DISTINCT " +
Col.ID + ", " +
Col.SERVER_ID +
" FROM " + tableName;
return query(new QueryAllStatement<Map<Integer, UUID>>(sql, 100) {
@Override
public Map<Integer, UUID> processResults(ResultSet set) throws SQLException {
Map<Integer, UUID> idMap = new HashMap<>();
while (set.next()) {
int worldId = set.getInt(Col.ID.get());
int serverId = set.getInt(Col.SERVER_ID.get());
UUID serverUUID = serverUUIDsByID.getOrDefault(serverId, ServerInfo.getServerUUID());
idMap.put(worldId, serverUUID);
}
return idMap;
}
});
}
public List<String> getWorlds() {
return getWorlds(ServerInfo.getServerUUID());
}
@ -201,143 +157,6 @@ public class WorldTable extends Table {
});
}
/**
* Used to get world names for this server.
*
* @param serverUUID UUID of the Server
* @return World names known for that server
* @deprecated Use getWorldNames instead, this method is slower.
*/
@Deprecated
public Set<String> getWorldNamesOld(UUID serverUUID) {
WorldTimesTable worldTimesTable = db.getWorldTimesTable();
SessionsTable sessionsTable = db.getSessionsTable();
String statementSelectServerID = serverTable.statementSelectServerID;
String worldIDColumn = worldTimesTable + "." + WorldTimesTable.Col.WORLD_ID;
String worldSessionIDColumn = worldTimesTable + "." + WorldTimesTable.Col.SESSION_ID;
String sessionIDColumn = sessionsTable + "." + SessionsTable.Col.ID;
String sessionServerIDColumn = sessionsTable + "." + SessionsTable.Col.SERVER_ID;
String sql = "SELECT DISTINCT " +
Col.NAME + " FROM " +
tableName +
" INNER JOIN " + worldTimesTable + " on " + worldIDColumn + "=" + tableName + "." + Col.ID +
" INNER JOIN " + sessionsTable + " on " + worldSessionIDColumn + "=" + sessionIDColumn +
" WHERE " + statementSelectServerID + "=" + sessionServerIDColumn;
return query(new QueryStatement<Set<String>>(sql, 1000) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, serverUUID.toString());
}
@Override
public Set<String> processResults(ResultSet set) throws SQLException {
Set<String> worldNames = new HashSet<>();
while (set.next()) {
worldNames.add(set.getString(Col.NAME.get()));
}
return worldNames;
}
});
}
public void alterTableV16() {
addColumns(Col.SERVER_ID + " integer NOT NULL DEFAULT 0");
List<UUID> serverUUIDs = serverTable.getServerUUIDs();
Map<UUID, Set<String>> worldsPerServer = new HashMap<>();
for (UUID serverUUID : serverUUIDs) {
worldsPerServer.put(serverUUID, getWorldNamesOld(serverUUID));
}
for (Map.Entry<UUID, Set<String>> entry : worldsPerServer.entrySet()) {
UUID serverUUID = entry.getKey();
Set<String> worlds = entry.getValue();
saveWorlds(worlds, serverUUID);
}
updateWorldTimesTableWorldIDs();
execute("DELETE FROM " + tableName + " WHERE " + Col.SERVER_ID + "=0");
}
private void updateWorldTimesTableWorldIDs() {
List<WorldObj> worldObjects = getWorldObjects();
Map<WorldObj, List<WorldObj>> oldToNewMap =
worldObjects.stream()
.filter(worldObj -> worldObj.serverId == 0)
.collect(Collectors.toMap(
Function.identity(),
oldWorld -> worldObjects.stream()
.filter(worldObj -> worldObj.serverId != 0)
.filter(worldObj -> worldObj.equals(oldWorld))
.collect(Collectors.toList()
)));
WorldTimesTable worldTimesTable = db.getWorldTimesTable();
String sql = "UPDATE " + worldTimesTable + " SET " +
WorldTimesTable.Col.WORLD_ID + "=?" +
" WHERE " + WorldTimesTable.Col.WORLD_ID + "=?" +
" AND " + WorldTimesTable.Col.SERVER_ID + "=?";
executeBatch(new ExecStatement(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
for (Map.Entry<WorldObj, List<WorldObj>> entry : oldToNewMap.entrySet()) {
WorldObj old = entry.getKey();
for (WorldObj newWorld : entry.getValue()) {
statement.setInt(1, newWorld.id);
statement.setInt(2, old.id);
statement.setInt(3, newWorld.serverId);
statement.addBatch();
}
}
}
});
}
public Map<Integer, List<Integer>> getWorldIDsByServerIDs() {
String sql = "SELECT " +
Col.ID + ", " +
Col.SERVER_ID +
" FROM " + tableName;
return query(new QueryAllStatement<Map<Integer, List<Integer>>>(sql, 100) {
@Override
public Map<Integer, List<Integer>> processResults(ResultSet set) throws SQLException {
Map<Integer, List<Integer>> map = new HashMap<>();
while (set.next()) {
int serverID = set.getInt(Col.SERVER_ID.get());
int worldID = set.getInt(Col.ID.get());
List<Integer> worldIDs = map.getOrDefault(serverID, new ArrayList<>());
worldIDs.add(worldID);
map.put(serverID, worldIDs);
}
return map;
}
});
}
public List<WorldObj> getWorldObjects() {
String sql = "SELECT * FROM " + tableName;
return query(new QueryAllStatement<List<WorldObj>>(sql, 100) {
@Override
public List<WorldObj> processResults(ResultSet set) throws SQLException {
List<WorldObj> objects = new ArrayList<>();
while (set.next()) {
int worldID = set.getInt(Col.ID.get());
int serverID = set.getInt(Col.SERVER_ID.get());
String worldName = set.getString(Col.NAME.get());
objects.add(new WorldObj(worldID, serverID, worldName));
}
return objects;
}
});
}
public enum Col implements Column {
ID("id"),
SERVER_ID("server_id"),
@ -361,36 +180,3 @@ public class WorldTable extends Table {
}
}
class WorldObj {
final int id;
final int serverId;
final String name;
public WorldObj(int id, int serverId, String name) {
this.id = id;
this.serverId = serverId;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WorldObj worldObj = (WorldObj) o;
return Objects.equal(name, worldObj.name);
}
@Override
public int hashCode() {
return Objects.hashCode(name);
}
@Override
public String toString() {
return "{" +
"id=" + id +
", serverId=" + serverId +
", name='" + name + '\'' +
'}';
}
}

View File

@ -1,7 +1,6 @@
package com.djrapitops.plan.system.database.databases.sql.tables;
import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.data.container.Session;
import com.djrapitops.plan.data.store.keys.SessionKeys;
import com.djrapitops.plan.data.time.GMTimes;
@ -14,10 +13,6 @@ import com.djrapitops.plan.system.database.databases.sql.statements.Column;
import com.djrapitops.plan.system.database.databases.sql.statements.Sql;
import com.djrapitops.plan.system.database.databases.sql.statements.TableSqlParser;
import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.RunnableFactory;
import com.djrapitops.plugin.utilities.Verify;
import java.sql.PreparedStatement;
@ -356,42 +351,6 @@ public class WorldTimesTable extends UserIDTable {
});
}
public void alterTableV16() {
addColumns(Col.SERVER_ID + " integer NOT NULL DEFAULT 0");
RunnableFactory.createNew("DB version -> 16", new AbsRunnable() {
@Override
public void run() {
try {
Map<Integer, Integer> sessionIDServerIDRelation = sessionsTable.getIDServerIDRelation();
String sql = "UPDATE " + tableName + " SET " +
Col.SERVER_ID + "=?" +
" WHERE " + Col.SESSION_ID + "=?";
executeBatch(new ExecStatement(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
for (Map.Entry<Integer, Integer> entry : sessionIDServerIDRelation.entrySet()) {
Integer sessionID = entry.getKey();
Integer serverID = entry.getValue();
statement.setInt(1, serverID);
statement.setInt(2, sessionID);
statement.addBatch();
}
}
});
worldTable.alterTableV16();
} catch (DBOpException e) {
Log.toLog(this.getClass().getName(), e);
} finally {
cancel();
}
}
}).runTaskLaterAsynchronously(TimeAmount.SECOND.ticks() * 2);
}
public enum Col implements Column {
USER_ID(UserIDTable.Col.USER_ID.get()),
SERVER_ID("server_id"),

View File

@ -1,6 +1,7 @@
package com.djrapitops.plan.system.database.databases.sql.tables.move;
import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.statements.TableSqlParser;
import com.djrapitops.plan.system.database.databases.sql.tables.Table;
/**
@ -27,8 +28,7 @@ public class TransferTable extends Table {
}
protected void dropTable(String name) {
String sql = "DROP TABLE " + name;
execute(sql);
execute(TableSqlParser.dropTable(name));
}
}

View File

@ -8,6 +8,8 @@ import com.djrapitops.plan.api.exceptions.ParseException;
import com.djrapitops.plan.api.exceptions.connection.NoServersException;
import com.djrapitops.plan.api.exceptions.connection.WebException;
import com.djrapitops.plan.api.exceptions.connection.WebFailException;
import com.djrapitops.plan.data.store.containers.NetworkContainer;
import com.djrapitops.plan.system.cache.CacheSystem;
import com.djrapitops.plan.system.info.connection.BungeeConnectionSystem;
import com.djrapitops.plan.system.info.request.CacheRequest;
import com.djrapitops.plan.system.info.request.GenerateInspectPageRequest;
@ -43,7 +45,8 @@ public class BungeeInfoSystem extends InfoSystem {
@Override
public void updateNetworkPage() throws WebException {
try {
String html = new NetworkPage().toHtml();
NetworkContainer networkContainer = CacheSystem.getInstance().getDataContainerCache().getNetworkContainer();
String html = new NetworkPage(networkContainer).toHtml();
ResponseCache.cacheResponse(PageId.SERVER.of(ServerInfo.getServerUUID()), () -> new AnalysisPageResponse(html));
} catch (ParseException e) {
throw new WebFailException("Exception during Network Page Parsing", e);

View File

@ -11,9 +11,12 @@ import com.djrapitops.plan.system.info.request.CacheNetworkPageContentRequest;
import com.djrapitops.plan.system.info.request.InfoRequest;
import com.djrapitops.plan.system.info.request.SetupRequest;
import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.utilities.html.HtmlStructure;
import com.djrapitops.plugin.api.utility.log.Log;
import java.util.function.Supplier;
/**
* InfoSystem for Bukkit servers.
*
@ -21,8 +24,8 @@ import com.djrapitops.plugin.api.utility.log.Log;
*/
public class ServerInfoSystem extends InfoSystem {
public ServerInfoSystem() {
super(new ServerConnectionSystem());
public ServerInfoSystem(Supplier<Locale> locale) {
super(new ServerConnectionSystem(locale));
}
@Override

View File

@ -46,14 +46,12 @@ public class BungeeConnectionSystem extends ConnectionSystem {
protected Server selectServerForRequest(InfoRequest infoRequest) throws NoServersException {
refreshServerMap();
Server server = null;
if (infoRequest instanceof CacheRequest) {
throw new NoServersException("Bungee should not send Cache requests.");
if (infoRequest instanceof CacheRequest || infoRequest instanceof GenerateInspectPageRequest) {
// Run locally
return ServerInfo.getServer();
} else if (infoRequest instanceof GenerateAnalysisPageRequest) {
UUID serverUUID = ((GenerateAnalysisPageRequest) infoRequest).getServerUUID();
server = bukkitServers.get(serverUUID);
} else if (infoRequest instanceof GenerateInspectPageRequest) {
// Run locally
server = ServerInfo.getServer();
}
if (server == null) {
throw new NoServersException("Proper server is not available to process request: " + infoRequest.getClass().getSimpleName());

Some files were not shown because too many files have changed in this diff Show More