[3.6.2] Merge pull request #225 from Rsl1122/3.7.0

Main pull request for 3.6.2
This commit is contained in:
Rsl1122 2017-08-11 10:21:37 +03:00 committed by GitHub
commit d0a7ac0f4d
125 changed files with 3409 additions and 2203 deletions

View File

@ -1,41 +1,13 @@
Feel free to use the template below to report your issue, for suggestions you can use whatever works for you :)
Remember to use the Preview button to ensure the errors are displayed properly
Instructions for issue reporting:
- Write description of the issue
- Use `/plan m dump` & Copy the hastebin address here
If your issue is about a command timeout, please follow the instructions at the bottom of the issue template.
For suggestions use any format you want. :)
----
**Plan Version:** <Version>
**Server Version:** <Server Version>
**Database Type:** <Mysql/sqlite>
**Issue Caused by:** <Caused by>
----
**Description:**
**Description of the issue**
**Steps to Reproduce:**
1.
2.
**Proposed Solution:**
----
**Console/Errors.txt/DebugLog.txt contents:**
```
Place any stack traces inside these symbols (```)
```
----
Instructions for reporting timeout issues:
- Enable file debug mode by changing config setting "Debug" to "file"
- Reload the plugin
- Run the command that causes the timeout message to show
- Copy the contents of DebugLog.txt inside the code brackets above
**Hastebin link**
Link:

View File

@ -1,13 +0,0 @@
<component name="libraryTable">
<library name="Maven: com.djrapitops:abstract-plugin-framework:2.0.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/djrapitops/abstract-plugin-framework/2.0.1/abstract-plugin-framework-2.0.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/djrapitops/abstract-plugin-framework/2.0.1/abstract-plugin-framework-2.0.1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/djrapitops/abstract-plugin-framework/2.0.1/abstract-plugin-framework-2.0.1-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

@ -1,13 +1,13 @@
<component name="libraryTable">
<library name="Maven: com.djrapitops:abstract-plugin-framework:2.0.1">
<library name="Maven: com.djrapitops:abstract-plugin-framework:2.0.2">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/djrapitops/abstract-plugin-framework/2.0.1/abstract-plugin-framework-2.0.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/com/djrapitops/abstract-plugin-framework/2.0.2/abstract-plugin-framework-2.0.2.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/djrapitops/abstract-plugin-framework/2.0.1/abstract-plugin-framework-2.0.1-javadoc.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/com/djrapitops/abstract-plugin-framework/2.0.2/abstract-plugin-framework-2.0.2-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/djrapitops/abstract-plugin-framework/2.0.1/abstract-plugin-framework-2.0.1-sources.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/com/djrapitops/abstract-plugin-framework/2.0.2/abstract-plugin-framework-2.0.2-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

@ -3,7 +3,6 @@
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name='Checker'>
<!-- asetetaan kieliasetukset englanniksi. -->
<property name="localeCountry" value="EN"/>
<property name="localeLanguage" value="en"/>

View File

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.djrapitops</groupId>
<artifactId>Plan</artifactId>
<version>3.6.1</version>
<version>3.6.2</version>
<packaging>jar</packaging>
<repositories>
<repository>
@ -28,7 +28,7 @@
<dependency>
<groupId>com.djrapitops</groupId>
<artifactId>abstract-plugin-framework</artifactId>
<version>2.0.1</version>
<version>2.0.2</version>
<scope>compile</scope>
</dependency>
<!-- SoftDepended Plugins-->
@ -109,6 +109,7 @@
<include>*.js</include>
<include>*.yml</include>
<include>*.html</include>
<include>*.txt</include>
</includes>
</resource>
</resources>

View File

@ -1,5 +1,8 @@
package main.java.com.djrapitops.plan;
import com.djrapitops.plugin.utilities.log.DebugInfo;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import java.util.Collection;
/**
@ -55,6 +58,48 @@ public class Log {
Plan.getInstance().getPluginLogger().debug(message);
}
/**
* Used for logging larger debug complexes.
*
* @param task complex this debug message is a part of.
* @param message message
* @return full debug complex so far.
*/
public static DebugInfo debug(String task, String message) {
DebugInfo debug = getDebug(task);
debug.addLine(message, MiscUtils.getTime());
return debug;
}
/**
* Used for logging larger debug complexes.
*
* @param task complex to get
* @return full debug complex so far.
*/
public static DebugInfo getDebug(String task) {
return Plan.getInstance().getPluginLogger().getDebug(task);
}
/**
* Logs the full debug complex to the debug log.
*
* @param task complex to log.
*/
public static void logDebug(String task) {
getDebug(task).toLog();
}
/**
* Logs the full debug complex to the debug log with an execution time.
*
* @param task complex to log.
* @param time execution time.
*/
public static void logDebug(String task, long time) {
getDebug(task).toLog(time);
}
/**
* Logs trace of caught Exception to Errors.txt and notifies on console.
*
@ -80,7 +125,10 @@ public class Log {
*
* @param message Message to log to Errors.txt [timestamp] Message
* @param filename Name of the file to write to.
* @deprecated Should no longer be used, may break other log handling mechanisms.
* If exception requires additional information it should be placed in the source string.
*/
@Deprecated
public static void toLog(String message, String filename) {
Plan.getInstance().getPluginLogger().toLog(message, filename);
}
@ -89,7 +137,9 @@ public class Log {
* Used to get the name for the error log file.
*
* @return Name of the error log file.
* @deprecated Should no longer be used, Errors.txt is handled by a separate class.
*/
@Deprecated
public static String getErrorsFilename() {
return Plan.getInstance().getPluginLogger().getErrorsFilename();
}

View File

@ -43,9 +43,7 @@ public enum Permissions {
}
/**
* Returns the permission node in plugin.yml.
* <p>
* Same as getPermission.
* Same as {@link #getPermission()}.
*
* @return permission node eg. plan.inspect
*/

View File

@ -1,271 +0,0 @@
package main.java.com.djrapitops.plan;
import org.bukkit.ChatColor;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Phrase contains every message that is used in placeholders or commands. The
* contents for each message can be changed. Every message can contain a String
* or ChatColor.
*
* @author Rsl1122
* @since 2.0.0
*/
public enum Phrase {
REPLACE0("REPLACE0"),
PREFIX("[Plan] "),
ENABLED("Player Analytics Enabled."),
DISABLED("Player Analytics Disabled."),
RELOAD_COMPLETE(ChatColor.GREEN.toString() + PREFIX + "Reload complete."),
CACHE_SAVE("Saving cached data.."),
CACHE_ADD("Added REPLACE0 to Cache."),
CACHE_REMOVE("Cleared REPLACE0 from Cache."),
CONFIG_HEADER("Plan Config | More info at https://www.spigotmc.org/wiki/plan-configuration/"),
DB_INIT("Database init.."),
WEBSERVER_INIT("Initializing Webserver.."),
WEBSERVER_CLOSE("Shutting down Webserver.."),
WEBSERVER_RUNNING("Webserver running on PORT " + REPLACE0),
DB_CONNECTION_FAIL("REPLACE0-Database Connection failed: REPLACE1"),
DB_ESTABLISHED(REPLACE0 + "-database connection established."),
DB_TYPE_DOES_NOT_EXIST("That database type doesn't exist."),
DB_FAILURE_DISABLE("Database initialization has failed, disabling Plan."),
NOTIFY_EMPTY_IP(ChatColor.YELLOW.toString() + PREFIX + "IP in server.properties is empty & AlternativeServerIP is not used, incorrect links will be given!"),
NOTIFY_DISABLED_CHATLISTENER(ChatColor.YELLOW + "Chat listener disabled, nickname info inaccurate."),
NOTIFY_DISABLED_GMLISTENER(ChatColor.YELLOW + "Gamemode change listener disabled, Gm times info inaccurate."),
NOTIFY_DISABLED_COMMANDLISTENER(ChatColor.YELLOW + "Command usage listener disabled."),
NOTIFY_DISABLED_DEATHLISTENER(ChatColor.YELLOW + "Death listener disabled, player & mob kills not recorded."),
//
CACHE_SAVETASK_DISABLED("Attempted to schedule data for save after task was shut down."),
CACHE_GETTASK_DISABLED("Attempted to schedule data grab after task was shut down."),
CACHE_CLEARTASK_DISABLED("Attempted to schedule data for clear after task was shut down."),
//
VERSION_NEW_AVAILABLE("New Version (" + REPLACE0 + ") is available at https://www.spigotmc.org/resources/plan-player-analytics.32536/"),
VERSION_LATEST("You're running the latest version"),
VERSION_CHECK_ERROR("Failed to compare versions."),
VERSION_FAIL("Failed to get newest version number."),
//
USERNAME_NOT_VALID(ChatColor.RED.toString() + PREFIX + "This Player doesn't exist."),
USERNAME_NOT_SEEN(ChatColor.RED.toString() + PREFIX + "This Player has not played on this server."),
USERNAME_NOT_KNOWN(ChatColor.RED.toString() + PREFIX + "Player not found from the database."),
//
COLOR_MAIN(ChatColor.getByChar(Settings.COLOR_MAIN.toString().charAt(1))),
COLOR_SEC(ChatColor.getByChar(Settings.COLOR_SEC.toString().charAt(1))),
COLOR_TER(ChatColor.getByChar(Settings.COLOR_TER.toString().charAt(1))),
//
ARROWS_RIGHT("»"),
BALL(""),
GRABBING_DATA_MESSAGE(COLOR_TER.toString() + ARROWS_RIGHT + COLOR_MAIN.color() + " Fetching data to cache.."),
//
DEM_UNKNOWN("Not Known"),
NOT_IN_TOWN("Not in a town"),
NOT_IN_FAC("Not in a faction"),
//
ANALYSIS("Analysis | "),
COMMAND_TIMEOUT(ChatColor.RED.toString() + PREFIX + "REPLACE0 Command timed out! Check '/plan status' & console."),
ANALYSIS_START(ANALYSIS + "Beginning analysis of user data.."),
ANALYSIS_BOOT_NOTIFY(ANALYSIS + "Boot analysis in 30 seconds.."),
ANALYSIS_BOOT(ANALYSIS + "Starting Boot Analysis.."),
ANALYSIS_FETCH_PLAYERS(ANALYSIS + "Checking for available players.."),
ANALYSIS_FETCH_DATA(ANALYSIS + "Fetching Data.."),
ANALYSIS_FAIL_NO_PLAYERS(ANALYSIS + "Analysis failed, no known players."),
ANALYSIS_FAIL_NO_DATA(ANALYSIS + "Analysis failed, no data in the database."),
ANALYSIS_BEGIN_ANALYSIS(ANALYSIS + "Data Fetched (REPLACE0 users, took REPLACE1ms), beginning Analysis of data.."),
ANALYSIS_THIRD_PARTY(ANALYSIS + "Analyzing additional data sources (3rd party)"),
ANALYSIS_COMPLETE(ANALYSIS + "Analysis Complete. (took REPLACE0ms) REPLACE1"),
DATA_CORRUPTION_WARN("Some data might be corrupted: " + REPLACE0),
//
ERROR_CONSOLE_PLAYER("This point of code should not be accessable on console. Inform author: " + REPLACE0 + " Console: REPLACE1"),
ERROR_NO_DATA_VIEW(ChatColor.YELLOW + "Webserver disabled but Alternative IP/PlanLite not used, no way to view data!"),
ERROR_WEBSERVER_OFF_ANALYSIS(ChatColor.YELLOW + "" + PREFIX + "This command can be only used if the webserver is running on this server."),
ERROR_WEBSERVER_OFF_INSPECT(ChatColor.YELLOW + "" + PREFIX + "This command can be only used if webserver is enabled on this server."),
ERROR_LOGGED("Caught " + REPLACE0 + ". It has been logged to the Errors.txt"),
ERROR_SESSIONDATA_INITIALIZATION("Player's session was initialized in a wrong way! (" + REPLACE0 + ")"),
ERROR_ANALYSIS_FETCH_FAIL("Failed to fetch data for Analysis, Exception occurred."),
ERROR_ANALYSIS_DISABLED_TEMPORARILY(ChatColor.YELLOW + "Analysis has been temporarily disabled due to expensive task, use /plan status for info."),
//
CMD_FOOTER(COLOR_TER.color().toString() + ARROWS_RIGHT),
MANAGE_ERROR_INCORRECT_PLUGIN(ChatColor.RED.toString() + PREFIX + "Plugin not supported: "),
MANAGE_PROCESS_START(ARROWS_RIGHT.toString() + COLOR_SEC.color() + " Processing data.."),
MANAGE_ERROR_PLUGIN_NOT_ENABLED(ChatColor.RED.toString() + PREFIX + "Plugin is not enabled: "),
MANAGE_ERROR_INCORRECT_DB(ChatColor.RED.toString() + PREFIX + "Incorrect database! (sqlite/mysql accepted): "),
MANAGE_ERROR_SAME_DB(ChatColor.RED.toString() + PREFIX + "Can't move to the same database!"),
MANAGE_DATABASE_FAILURE(ChatColor.RED.toString() + PREFIX + "One of the databases was not initialized properly."),
MANAGE_DB_CONFIG_REMINDER(ChatColor.YELLOW.toString() + PREFIX + "Remember to swap to the new database and reload plugin"),
MANAGE_ERROR_NO_PLAYERS(ChatColor.RED.toString() + PREFIX + "Database has no player data!"),
MANAGE_ERROR_BACKUP_FILE_NOT_FOUND(ChatColor.RED.toString() + PREFIX + "Backup file doesn't exist!"),
MANAGE_MOVE_SUCCESS(ChatColor.GREEN.toString() + PREFIX + "All data moved successfully!"),
MANAGE_COPY_SUCCESS(ChatColor.GREEN.toString() + PREFIX + "All data copied successfully!"),
MANAGE_PROCESS_FAIL(ChatColor.RED.toString() + PREFIX + "Something went wrong while processing the data!"),
MANAGE_CLEAR_SUCCESS(ChatColor.GREEN.toString() + PREFIX + "All data cleared successfully!"),
MANAGE_REMOVE_SUCCESS(CMD_FOOTER + " " + COLOR_MAIN.color() + "Data of " + COLOR_TER.color() + "REPLACE0" + COLOR_MAIN.color() + " was removed from Database " + COLOR_TER.color() + "REPLACE1" + COLOR_MAIN.color() + "."),
MANAGE_IMPORTING(CMD_FOOTER + " " + COLOR_MAIN.color() + " Importing Data.."),
MANAGE_SUCCESS(CMD_FOOTER + " " + COLOR_MAIN.color() + " Success!"),
//
CMD_BALL(COLOR_SEC.color() + " " + Phrase.BALL.toString() + COLOR_MAIN.color()),
CMD_ANALYZE_HEADER(CMD_FOOTER.toString() + COLOR_MAIN.color() + " Player Analytics - Analysis results"),
CMD_INSPECT_HEADER(CMD_FOOTER.toString() + COLOR_MAIN.color() + " Player Analytics - Inspect results: "),
CMD_INFO_HEADER(CMD_FOOTER.toString() + COLOR_MAIN.color() + " Player Analytics - Info"),
CMD_INFO_VERSION(CMD_BALL.toString() + COLOR_MAIN.color() + " Version: " + COLOR_SEC.color() + REPLACE0),
CMD_SEARCH_HEADER(CMD_FOOTER.toString() + COLOR_MAIN.color() + " Player Analytics - Search results for: "),
CMD_SEARCH_SEARCHING(CMD_FOOTER.toString() + COLOR_MAIN.color() + " Searching.."),
CMD_HELP_HEADER(CMD_FOOTER.toString() + COLOR_MAIN.color() + " Player Analytics - Help"),
CMD_MANAGE_HELP_HEADER(CMD_FOOTER.toString() + COLOR_MAIN.color() + " Player Analytics - Managment Help"),
CMD_MANAGE_STATUS_HEADER(CMD_FOOTER.toString() + COLOR_MAIN.color() + " Player Analytics - Database status"),
CMD_MANAGE_STATUS_ACTIVE_DB(CMD_BALL.toString() + COLOR_MAIN.color() + " Active Database: " + COLOR_SEC.color() + "REPLACE0"),
CMD_MANAGE_STATUS_QUEUE_SAVE(CMD_BALL.toString() + COLOR_MAIN.color() + " Save Queue Size: " + COLOR_SEC.color() + "REPLACE0/" + Settings.PROCESS_SAVE_LIMIT.getNumber()),
CMD_MANAGE_STATUS_QUEUE_GET(CMD_BALL.toString() + COLOR_MAIN.color() + " Get Queue Size: " + COLOR_SEC.color() + "REPLACE0/" + Settings.PROCESS_GET_LIMIT.getNumber()),
CMD_MANAGE_STATUS_QUEUE_CLEAR(CMD_BALL.toString() + COLOR_MAIN.color() + " Clear Queue Size: " + COLOR_SEC.color() + "REPLACE0/" + Settings.PROCESS_CLEAR_LIMIT.getNumber()),
CMD_MANAGE_STATUS_QUEUE_PROCESS(CMD_BALL.toString() + COLOR_MAIN.color() + " Process Queue Size: " + COLOR_SEC.color() + "REPLACE0/20000"),
CMD_CLICK_ME("Click Me"),
CMD_LINK(COLOR_SEC.color() + " " + BALL + COLOR_MAIN.color() + " Link: " + COLOR_TER.color()),
CMD_PASS_PLANLITE("UNUSED"),
CMD_RESULTS_AVAILABLE(COLOR_SEC.color() + " Results will be available for " + COLOR_TER.color() + REPLACE0 + COLOR_SEC.color() + " minutes."),
CMD_NO_RESULTS(CMD_BALL + " No results for " + COLOR_SEC.color() + REPLACE0 + COLOR_MAIN.color() + "."),
CMD_MATCH(COLOR_SEC.color() + " Matching players: " + COLOR_TER.color()),
//
CMD_USG_ANALYZE("View the Server Analysis"),
CMD_USG_QANALYZE("View the Server QuickAnalysis"),
CMD_USG_HELP("Show command list."),
CMD_USG_INFO("View Version of Plan"),
CMD_USG_INSPECT("Inspect Player's Data"),
CMD_USG_QINSPECT("QuickInspect Player's Data"),
CMD_USG_MANAGE("Database management command"),
CMD_USG_MANAGE_BACKUP("Backup a database to .db file"),
CMD_USG_MANAGE_RESTORE("Restore a database from a backup file"),
CMD_USG_MANAGE_MOVE("Copy data from one database to another & overwrite values"),
CMD_USG_MANAGE_COMBINE("Copy data from one database to another & combine values"),
CMD_USG_MANAGE_IMPORT("Import Data from supported plugins to Active Database."),
CMD_USG_MANAGE_CLEAR("Clear data from one database"),
CMD_USG_MANAGE_CLEAN("Clear incorrect data from the database"),
CMD_USG_MANAGE_REMOVE("Remove players's data from the Active Database."),
CMD_USG_MANAGE_STATUS("Check the status of the Active Database."),
CMD_USG_MANAGE_HELP("Show management help."),
CMD_USG_MANAGE_HOTSWAP("Hotswap to another database & restart the plugin"),
CMD_USG_RELOAD("Reload plugin config & save cached data"),
CMD_USG_SEARCH("Search for player"),
ARG_SEARCH("<part of playername>"),
ARG_PLAYER("<player>"),
ARG_RESTORE("<Filename.db> <dbTo> [-a]"),
ARG_IMPORT("<plugin>/list [import args]"),
ARG_MOVE("<fromDB> <toDB> [-a]"),
//
USE_BACKUP("Use /plan manage backup <DB>"),
USE_RESTORE("Use /plan manage restore <Filename.db> <dbTo> [-a]"),
USE_MANAGE("Use /plan manage for help"),
USE_PLAN("Use /plan for help"),
USE_MOVE("Use /plan manage move <fromDB> <toDB> [-a]"),
USE_COMBINE("Use /plan manage combine <fromDB> <toDB> [-a]"),
USE_IMPORT("Use /plan manage import " + ARG_IMPORT),
//
WARN_REWRITE("Data in REPLACE0-database will be rewritten!"),
WARN_OVERWRITE("Data in REPLACE0-database will be overwritten!"),
WARN_OVERWRITE_SOME("Some data in REPLACE0-database will be overwritten!"),
WARN_REMOVE("Data in REPLACE0-database will be removed!"),
//
COMMAND_SENDER_NOT_PLAYER(ChatColor.RED.toString() + PREFIX + "This command can be only used as a player."),
COMMAND_REQUIRES_ARGUMENTS(ChatColor.RED.toString() + PREFIX + "Command requires arguments. REPLACE0"),
COMMAND_ADD_CONFIRMATION_ARGUMENT(ChatColor.RED.toString() + PREFIX + "Add -a to confirm execution! REPLACE0"),
COMMAND_REQUIRES_ARGUMENTS_ONE(ChatColor.RED.toString() + PREFIX + "Command requires one argument."),
COMMAND_NO_PERMISSION(ChatColor.RED.toString() + PREFIX + "You do not have the required permission."),
ERROR_TOO_SMALL_QUEUE("Queue size is too small! (REPLACE0), change the setting to a higher number! (Currently REPLACE1)");
private String text;
private ChatColor color;
Phrase(String text) {
this.text = text;
this.color = null;
}
Phrase(ChatColor color) {
this.color = color;
this.text = "";
}
static void loadLocale(File localeFile) {
try (Scanner localeScanner = new Scanner(localeFile, "UTF-8")) {
List<String> localeRows = new ArrayList<>();
while (localeScanner.hasNextLine()) {
String line = localeScanner.nextLine();
if (!line.isEmpty()) {
if ("<<<<<<HTML>>>>>>".equals(line)) {
break;
}
localeRows.add(line);
}
}
for (String localeRow : localeRows) {
try {
String[] split = localeRow.split(" <> ");
Phrase.valueOf(split[0]).setText(split[1]);
} catch (IllegalArgumentException e) {
Log.error("There is a miswritten line in locale on line " + localeRows.indexOf(localeRow));
}
}
} catch (IOException e) {
Log.error("Error at Locale Scanning: " + e.getCause());
}
}
@Override
public String toString() {
return text;
}
/**
* Alternative for toString.
*
* @return toString()
*/
public String parse() {
return this.toString();
}
/**
* Replaces all REPLACE{x} strings with the given parameters.
*
* @param p Strings to replace REPLACE{x}:s with
* @return String with placeholders replaced.
*/
public String parse(Serializable... p) {
String returnValue = this.toString();
for (int i = 0; i < p.length; i++) {
returnValue = returnValue.replace("REPLACE" + i, p[i].toString());
}
return returnValue;
}
/**
* Used to get the ChatColor of COLOR_ enums.
*
* @return Color of the COLOR_ENUM
*/
public ChatColor color() {
return color;
}
/**
* Used to set the text of the Enum.
*
* @param text A String.
*/
public void setText(String text) {
this.text = text;
}
/**
* Set the ChatColor of any Enum.
*
* @param colorCode The character that determines a chatcolor. 1-9, a-f etc.
*/
public void setColor(char colorCode) {
this.color = ChatColor.getByChar(colorCode);
}
}

View File

@ -37,17 +37,16 @@ import main.java.com.djrapitops.plan.data.listeners.*;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.database.databases.MySQLDB;
import main.java.com.djrapitops.plan.database.databases.SQLiteDB;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.webserver.WebServer;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.metrics.BStats;
import org.apache.logging.log4j.LogManager;
import org.bukkit.ChatColor;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
@ -72,7 +71,7 @@ public class Plan extends BukkitPlugin<Plan> {
private HookHandler hookHandler; // Manages 3rd party data sources
private Database db;
private HashSet<Database> databases;
private Set<Database> databases;
private WebServer uiServer;
@ -85,8 +84,9 @@ public class Plan extends BukkitPlugin<Plan> {
* @return API of the current instance of Plan.
* @throws IllegalStateException If onEnable method has not been called on
* Plan and the instance is null.
* @throws NoClassDefFoundError If Plan is not installed.
*/
public static API getPlanAPI() throws IllegalStateException {
public static API getPlanAPI() throws IllegalStateException, NoClassDefFoundError {
Plan instance = getInstance();
if (instance == null) {
throw new IllegalStateException("Plugin not enabled properly, Singleton instance is null.");
@ -110,105 +110,121 @@ public class Plan extends BukkitPlugin<Plan> {
*/
@Override
public void onEnable() {
// Sets the Required variables for RslPlugin instance to function correctly
setInstance(this);
super.setDebugMode(Settings.DEBUG.toString());
super.setColorScheme(new ColorScheme(Phrase.COLOR_MAIN.color(), Phrase.COLOR_SEC.color(), Phrase.COLOR_TER.color()));
super.setLogPrefix("[Plan]");
super.setUpdateCheckUrl("https://raw.githubusercontent.com/Rsl1122/Plan-PlayerAnalytics/master/Plan/src/main/resources/plugin.yml");
super.setUpdateUrl("https://www.spigotmc.org/resources/plan-player-analytics.32536/");
// Initializes BukkitPlugin variables, Checks version & Logs the debug header
super.onEnableDefaultTasks();
processStatus().startExecution("Enable");
initLocale();
Benchmark.start("Enable: Reading server variables");
serverVariableHolder = new ServerVariableHolder(getServer());
Benchmark.stop("Enable: Reading server variables");
Benchmark.start("Enable: Copy default config");
getConfig().options().copyDefaults(true);
getConfig().options().header(Phrase.CONFIG_HEADER.toString());
saveConfig();
Benchmark.stop("Enable: Copy default config");
Benchmark.start("Enable: Init Database");
Log.info(Phrase.DB_INIT.toString());
if (Check.ErrorIfFalse(initDatabase(), Phrase.DB_FAILURE_DISABLE.toString())) {
Log.info(Phrase.DB_ESTABLISHED.parse(db.getConfigName()));
} else {
disablePlugin();
return;
}
Benchmark.stop("Enable: Init Database");
Benchmark.start("Enable: Init DataCache");
this.handler = new DataCacheHandler(this);
this.inspectCache = new InspectCacheHandler(this);
this.analysisCache = new AnalysisCacheHandler(this);
Benchmark.stop("Enable: Init DataCache");
super.getRunnableFactory().createNew(new TPSCountTimer(this)).runTaskTimer(1000, TimeAmount.SECOND.ticks());
registerListeners();
this.api = new API(this);
Benchmark.start("Enable: Handle Reload");
handler.handleReload();
Benchmark.stop("Enable: Handle Reload");
Benchmark.start("Enable: Analysis refresh task registration");
// Analysis refresh settings
boolean bootAnalysisIsEnabled = Settings.ANALYSIS_REFRESH_ON_ENABLE.isTrue();
int analysisRefreshMinutes = Settings.ANALYSIS_AUTO_REFRESH.getNumber();
boolean analysisRefreshTaskIsEnabled = analysisRefreshMinutes > 0;
// Analysis refresh tasks
if (bootAnalysisIsEnabled) {
startBootAnalysisTask();
}
if (analysisRefreshTaskIsEnabled) {
startAnalysisRefreshTask(analysisRefreshMinutes);
}
Benchmark.stop("Enable: Analysis refresh task registration");
Benchmark.start("Enable: WebServer Initialization");
// Data view settings
boolean webserverIsEnabled = Settings.WEBSERVER_ENABLED.isTrue();
boolean usingAlternativeIP = Settings.SHOW_ALTERNATIVE_IP.isTrue();
boolean usingAlternativeUI = Settings.USE_ALTERNATIVE_UI.isTrue();
boolean hasDataViewCapability = usingAlternativeIP || usingAlternativeUI || webserverIsEnabled;
if (webserverIsEnabled) {
uiServer = new WebServer(this);
uiServer.initServer();
if (!uiServer.isEnabled()) {
Log.error("WebServer was not successfully initialized.");
try {
// Sets the Required variables for BukkitPlugin instance to function correctly
setInstance(this);
super.setDebugMode(Settings.DEBUG.toString());
try {
ChatColor mainColor = ChatColor.getByChar(Settings.COLOR_MAIN.toString().charAt(1));
ChatColor secColor = ChatColor.getByChar(Settings.COLOR_SEC.toString().charAt(1));
ChatColor terColor = ChatColor.getByChar(Settings.COLOR_TER.toString().charAt(1));
super.setColorScheme(new ColorScheme(mainColor, secColor, terColor));
} catch (Exception e) {
Log.infoColor(ChatColor.RED + "Customization, Chat colors set-up wrong, using defaults.");
super.setColorScheme(new ColorScheme(ChatColor.DARK_GREEN, ChatColor.GRAY, ChatColor.WHITE));
}
super.setLogPrefix("[Plan]");
super.setUpdateCheckUrl("https://raw.githubusercontent.com/Rsl1122/Plan-PlayerAnalytics/master/Plan/src/main/resources/plugin.yml");
super.setUpdateUrl("https://www.spigotmc.org/resources/plan-player-analytics.32536/");
setupFilter();
} else if (!hasDataViewCapability) {
Log.infoColor(Phrase.ERROR_NO_DATA_VIEW.toString());
// Initializes BukkitPlugin variables, Checks version & Logs the debug header
super.onEnableDefaultTasks();
Benchmark.start("Enable");
// Initialize Locale
new Locale(this).loadLocale();
Benchmark.start("Reading server variables");
serverVariableHolder = new ServerVariableHolder(getServer());
Benchmark.stop("Enable", "Reading server variables");
Benchmark.start("Copy default config");
getConfig().options().copyDefaults(true);
getConfig().options().header("Plan Config | More info at https://www.spigotmc.org/wiki/plan-configuration/");
saveConfig();
Benchmark.stop("Enable", "Copy default config");
Benchmark.start("Init Database");
Log.info(Locale.get(Msg.ENABLE_DB_INIT).toString());
if (Check.ErrorIfFalse(initDatabase(), Locale.get(Msg.ENABLE_DB_FAIL_DISABLE_INFO).toString())) {
Log.info(Locale.get(Msg.ENABLE_DB_INFO).parse(db.getConfigName()));
} else {
disablePlugin();
return;
}
Benchmark.stop("Enable", "Init Database");
Benchmark.start("Init DataCache");
this.handler = new DataCacheHandler(this);
this.inspectCache = new InspectCacheHandler(this);
this.analysisCache = new AnalysisCacheHandler(this);
Benchmark.stop("Enable", "Init DataCache");
super.getRunnableFactory().createNew(new TPSCountTimer(this)).runTaskTimer(1000, TimeAmount.SECOND.ticks());
registerListeners();
this.api = new API(this);
Benchmark.start("Handle Reload");
handler.handleReload();
Benchmark.stop("Enable", "Handle Reload");
Benchmark.start("Analysis refresh task registration");
// Analysis refresh settings
boolean bootAnalysisIsEnabled = Settings.ANALYSIS_REFRESH_ON_ENABLE.isTrue();
int analysisRefreshMinutes = Settings.ANALYSIS_AUTO_REFRESH.getNumber();
boolean analysisRefreshTaskIsEnabled = analysisRefreshMinutes > 0;
// Analysis refresh tasks
if (bootAnalysisIsEnabled) {
startBootAnalysisTask();
}
if (analysisRefreshTaskIsEnabled) {
startAnalysisRefreshTask(analysisRefreshMinutes);
}
Benchmark.stop("Enable", "Analysis refresh task registration");
Benchmark.start("WebServer Initialization");
// Data view settings
boolean webserverIsEnabled = Settings.WEBSERVER_ENABLED.isTrue();
boolean usingAlternativeIP = Settings.SHOW_ALTERNATIVE_IP.isTrue();
boolean usingAlternativeUI = Settings.USE_ALTERNATIVE_UI.isTrue();
boolean hasDataViewCapability = usingAlternativeIP || usingAlternativeUI || webserverIsEnabled;
uiServer = new WebServer(this);
if (webserverIsEnabled) {
uiServer.initServer();
if (!uiServer.isEnabled()) {
Log.error("WebServer was not successfully initialized.");
}
setupFilter();
} else if (!hasDataViewCapability) {
Log.infoColor(Locale.get(Msg.ENABLE_NOTIFY_NO_DATA_VIEW).toString());
}
if (!usingAlternativeIP && serverVariableHolder.getIp().isEmpty()) {
Log.infoColor(Locale.get(Msg.ENABLE_NOTIFY_EMPTY_IP).toString());
}
Benchmark.stop("Enable", "WebServer Initialization");
registerCommand(new PlanCommand(this));
Benchmark.start("Hook to 3rd party plugins");
hookHandler = new HookHandler(this);
Benchmark.stop("Enable", "Hook to 3rd party plugins");
BStats bStats = new BStats(this);
bStats.registerMetrics();
Log.debug("Verbose debug messages are enabled.");
Log.logDebug("Enable", Benchmark.stop("Enable", "Enable"));
Log.info(Locale.get(Msg.ENABLED).toString());
} catch (Exception e) {
Log.error("Plugin Failed to Initialize Correctly.");
Log.toLog(this.getClass().getName(), e);
disablePlugin();
}
if (!usingAlternativeIP && serverVariableHolder.getIp().isEmpty()) {
Log.infoColor(Phrase.NOTIFY_EMPTY_IP.toString());
}
Benchmark.stop("Enable: WebServer Initialization");
registerCommand(new PlanCommand(this));
Benchmark.start("Enable: Hook to 3rd party plugins");
hookHandler = new HookHandler(this);
Benchmark.stop("Enable: Hook to 3rd party plugins");
BStats bStats = new BStats(this);
bStats.registerMetrics();
Log.debug("Verbose debug messages are enabled.");
Log.info(Phrase.ENABLED.toString());
processStatus().finishExecution("Enable");
}
/**
@ -231,7 +247,7 @@ public class Plan extends BukkitPlugin<Plan> {
if (Verify.notNull(handler, db)) {
Benchmark.start("Disable: DataCache Save");
// Saves the DataCache to the database without Bukkit's Schedulers.
Log.info(Phrase.CACHE_SAVE.toString());
Log.info(Locale.get(Msg.DISABLE_CACHE_SAVE).toString());
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.execute(() -> {
@ -243,15 +259,16 @@ public class Plan extends BukkitPlugin<Plan> {
scheduler.shutdown(); // Schedules the save to shutdown after it has ran the execute method.
}
Log.info(Phrase.DISABLED.toString());
Log.info(Locale.get(Msg.DISABLED).toString());
Locale.unload();
}
private void registerListeners() {
Benchmark.start("Enable: Register Listeners");
Benchmark.start("Register Listeners");
registerListener(new PlanPlayerListener(this));
boolean chatListenerIsEnabled = Check.isTrue(Settings.GATHERCHAT.isTrue(), Phrase.NOTIFY_DISABLED_CHATLISTENER.toString());
boolean commandListenerIsEnabled = Check.isTrue(Settings.GATHERCOMMANDS.isTrue(), Phrase.NOTIFY_DISABLED_COMMANDLISTENER.toString());
boolean deathListenerIsEnabled = Check.isTrue(Settings.GATHERKILLS.isTrue(), Phrase.NOTIFY_DISABLED_DEATHLISTENER.toString());
boolean chatListenerIsEnabled = Check.isTrue(Settings.GATHERCHAT.isTrue(), Locale.get(Msg.ENABLE_NOTIFY_DISABLED_CHATLISTENER).toString());
boolean commandListenerIsEnabled = Check.isTrue(Settings.GATHERCOMMANDS.isTrue(), Locale.get(Msg.ENABLE_NOTIFY_DISABLED_COMMANDLISTENER).toString());
boolean deathListenerIsEnabled = Check.isTrue(Settings.GATHERKILLS.isTrue(), Locale.get(Msg.ENABLE_NOTIFY_DISABLED_DEATHLISTENER).toString());
if (chatListenerIsEnabled) {
registerListener(new PlanChatListener(this));
@ -268,7 +285,7 @@ public class Plan extends BukkitPlugin<Plan> {
registerListener(new PlanDeathEventListener(this));
}
Benchmark.stop("Enable: Register Listeners");
Benchmark.stop("Enable", "Register Listeners");
}
/**
@ -287,7 +304,6 @@ public class Plan extends BukkitPlugin<Plan> {
for (Database database : databases) {
String databaseType = database.getConfigName().toLowerCase().trim();
Log.debug(databaseType + ": " + Verify.equalsIgnoreCase(dbType, databaseType));
if (Verify.equalsIgnoreCase(dbType, databaseType)) {
this.db = database;
break;
@ -295,15 +311,15 @@ public class Plan extends BukkitPlugin<Plan> {
}
if (!Verify.notNull(db)) {
Log.info(Phrase.DB_TYPE_DOES_NOT_EXIST.toString() + " " + dbType);
Log.info(Locale.get(Msg.ENABLE_FAIL_WRONG_DB).toString() + " " + dbType);
return false;
}
return Check.ErrorIfFalse(db.init(), Phrase.DB_FAILURE_DISABLE.toString());
return Check.ErrorIfFalse(db.init(), Locale.get(Msg.ENABLE_DB_FAIL_DISABLE_INFO).toString());
}
private void startAnalysisRefreshTask(int everyXMinutes) throws IllegalStateException {
Benchmark.start("Enable: Schedule PeriodicAnalysisTask");
Benchmark.start("Schedule PeriodicAnalysisTask");
if (everyXMinutes <= 0) {
return;
}
@ -316,113 +332,28 @@ public class Plan extends BukkitPlugin<Plan> {
}
}
}).runTaskTimerAsynchronously(everyXMinutes * TimeAmount.MINUTE.ticks(), everyXMinutes * TimeAmount.MINUTE.ticks());
Benchmark.stop("Enable: Schedule PeriodicAnalysisTask");
Benchmark.stop("Schedule PeriodicAnalysisTask");
}
private void startBootAnalysisTask() throws IllegalStateException {
Benchmark.start("Enable: Schedule boot analysis task");
Log.info(Phrase.ANALYSIS_BOOT_NOTIFY + "");
Benchmark.start("Schedule boot analysis task");
String bootAnalysisMsg = Locale.get(Msg.ENABLE_BOOT_ANALYSIS_INFO).toString();
String bootAnalysisRunMsg = Locale.get(Msg.ENABLE_BOOT_ANALYSIS_RUN_INFO).toString();
Log.info(bootAnalysisMsg);
ITask bootAnalysisTask = getRunnableFactory().createNew("BootAnalysisTask", new AbsRunnable() {
@Override
public void run() {
Log.debug("Running BootAnalysisTask");
Log.info(Phrase.ANALYSIS_BOOT + "");
Log.info(bootAnalysisRunMsg);
analysisCache.updateCache();
this.cancel();
}
}).runTaskLaterAsynchronously(30 * TimeAmount.SECOND.ticks());
bootAnalysisTaskID = bootAnalysisTask.getTaskId();
Benchmark.stop("Enable: Schedule boot analysis task");
}
/**
* Used to write a new Locale file in the plugin's datafolder.
*/
public void writeNewLocaleFile() {
File genLocale = new File(getDataFolder(), "locale_EN.txt");
try (
FileWriter fw = new FileWriter(genLocale, true);
PrintWriter pw = new PrintWriter(fw)
) {
if (genLocale.createNewFile()) {
Log.debug(genLocale.getAbsoluteFile() + " created");
}
for (Phrase p : Phrase.values()) {
pw.println(p.name() + " <> " + p.parse());
pw.flush();
}
pw.println("<<<<<<HTML>>>>>>");
for (Html h : Html.values()) {
pw.println(h.name() + " <> " + h.parse());
pw.flush();
}
} catch (IOException ex) {
Log.toLog(this.getClass().getName(), ex);
}
}
private void initLocale() {
String defaultLocale = "Default: EN";
String locale = Settings.LOCALE.toString().toUpperCase();
Benchmark.start("Enable: Initializing locale");
File localeFile = new File(getDataFolder(), "locale.txt");
String usingLocale;
if (localeFile.exists()) {
Phrase.loadLocale(localeFile);
Html.loadLocale(localeFile);
stopInitLocale(defaultLocale);
return;
}
if (locale.equals("DEFAULT")) {
stopInitLocale(defaultLocale);
return;
}
String urlString = "https://raw.githubusercontent.com/Rsl1122/Plan-PlayerAnalytics/master/Plan/localization/locale_" + locale + ".txt";
URL localeURL;
try {
localeURL = new URL(urlString);
} catch (MalformedURLException e) {
Log.error("Error at parsing \"" + urlString + "\" to an URL"); //Shouldn't ever happen
stopInitLocale(defaultLocale);
return;
}
try (InputStream inputStream = localeURL.openStream();
OutputStream outputStream = new FileOutputStream(localeFile)) {
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
Phrase.loadLocale(localeFile);
Html.loadLocale(localeFile);
usingLocale = locale;
if (localeFile.delete()) {
Log.debug(localeFile.getAbsoluteFile() + " (Locale File) deleted");
}
stopInitLocale(usingLocale);
} catch (FileNotFoundException ex) {
Log.error("Attempted using locale that doesn't exist.");
stopInitLocale(defaultLocale);
} catch (IOException e) {
Log.error("Error at loading locale from GitHub, using default locale.");
stopInitLocale(defaultLocale);
}
Benchmark.stop("Enable", "Schedule boot analysis task");
}
/**
@ -433,17 +364,6 @@ public class Plan extends BukkitPlugin<Plan> {
logger.addFilter(new RegisterCommandFilter());
}
/**
* Stops initializing the locale
*
* @param usingLocale The locale that's used
* @implNote Removes clutter in the method
*/
private void stopInitLocale(String usingLocale) {
Benchmark.stop("Enable: Initializing locale");
Log.info("Using locale: " + usingLocale);
}
/**
* Used to access AnalysisCache.
*

View File

@ -25,6 +25,7 @@ public enum Settings {
COMBINE_COMMAND_ALIASES_TO_MAIN_COMMAND("Customization.Data.CombineCommandAliasesToMainCommand"),
SECURITY_IP_UUID("Settings.WebServer.Security.DisplayIPsAndUUIDs"),
PLAYERLIST_SHOW_IMAGES("Customization.SmallHeadImagesOnAnalysisPlayerlist"),
WRITE_NEW_LOCALE("Settings.WriteNewLocaleFileOnStart"),
// Integer
ANALYSIS_MINUTES_FOR_ACTIVE("Settings.Analysis.MinutesPlayedUntilConsidiredActive"),
SAVE_CACHE_MIN("Settings.Cache.DataCache.SaveEveryXMinutes"),

View File

@ -3,10 +3,11 @@ package main.java.com.djrapitops.plan.command;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.TreeCommand;
import com.djrapitops.plugin.command.defaultcmds.StatusCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.command.commands.*;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
/**
* TreeCommand for the /plan command, and all subcommands.
@ -28,24 +29,11 @@ public class PlanCommand extends TreeCommand<Plan> {
public PlanCommand(Plan plugin) {
super(plugin, "plan", CommandType.CONSOLE, "", "", "plan");
super.setDefaultCommand("inspect");
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "/plan - Main Command",
tCol + " Used to access all SubCommands & help",
sCol + " /plan - List subcommands",
sCol + " /plan <subcommand> ? - in depth help"
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_PLAN).toArray();
}
@Override

View File

@ -5,11 +5,15 @@ import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.CommandUtils;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import main.java.com.djrapitops.plan.*;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.command.ConditionUtils;
import main.java.com.djrapitops.plan.data.cache.AnalysisCacheHandler;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.text.TextUI;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
@ -33,51 +37,39 @@ public class AnalyzeCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public AnalyzeCommand(Plan plugin) {
super("analyze, analyse, analysis, a", CommandType.CONSOLE, Permissions.ANALYZE.getPermission(), Phrase.CMD_USG_ANALYZE.parse());
super("analyze, analyse, analysis, a",
CommandType.CONSOLE,
Permissions.ANALYZE.getPermission(),
Locale.get(Msg.CMD_USG_ANALYZE).parse());
this.plugin = plugin;
analysisCache = plugin.getAnalysisCache();
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Analysis Command",
tCol + " Used to Refresh analysis cache & Access the result page",
sCol + " /plan status can be used to check status of analysis while it is running.",
sCol + " Aliases: analyze, analyse, analysis, a"
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_ANALYZE).toArray();
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Phrase.ERROR_WEBSERVER_OFF_ANALYSIS.toString(), sender)) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Locale.get(Msg.CMD_FAIL_NO_DATA_VIEW).toString(), sender)) {
return true;
}
if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Phrase.ERROR_ANALYSIS_DISABLED_TEMPORARILY.toString(), sender)
if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Locale.get(Msg.CMD_INFO_ANALYSIS_TEMP_DISABLE).toString(), sender)
&& !analysisCache.isCached()) {
return true;
}
sender.sendMessage(Phrase.GRABBING_DATA_MESSAGE + "");
if (plugin.getUiServer().isAuthRequired()) {
sender.sendMessage(Locale.get(Msg.CMD_INFO_FETCH_DATA).toString());
if (plugin.getUiServer().isAuthRequired() && CommandUtils.isPlayer(sender)) {
plugin.getRunnableFactory().createNew(new AbsRunnable("WebUser exist check task") {
@Override
public void run() {
try {
if (CommandUtils.isPlayer(sender)) {
boolean senderHasWebUser = plugin.getDB().getSecurityTable().userExists(sender.getName());
if (!senderHasWebUser) {
sender.sendMessage(ChatColor.YELLOW + "[Plan] You might not have a web user, use /plan register <password>");
}
boolean senderHasWebUser = plugin.getDB().getSecurityTable().userExists(sender.getName());
if (!senderHasWebUser) {
sender.sendMessage(ChatColor.YELLOW + "[Plan] You might not have a web user, use /plan register <password>");
}
} catch (Exception e) {
Log.toLog(this.getClass().getName() + getName(), e);
@ -116,7 +108,7 @@ public class AnalyzeCommand extends SubCommand {
}
if (timesRun > 10) {
Log.debug("Command Timeout Message, Analysis.");
sender.sendMessage(Phrase.COMMAND_TIMEOUT.parse("Analysis"));
sender.sendMessage(Locale.get(Msg.CMD_FAIL_TIMEOUT).parse("Analysis"));
this.cancel();
}
}
@ -132,21 +124,21 @@ public class AnalyzeCommand extends SubCommand {
*/
private void sendAnalysisMessage(ISender sender) {
boolean textUI = Settings.USE_ALTERNATIVE_UI.isTrue();
sender.sendMessage(Phrase.CMD_ANALYZE_HEADER.toString());
sender.sendMessage(Locale.get(Msg.CMD_HEADER_ANALYZE).toString());
if (textUI) {
sender.sendMessage(TextUI.getAnalysisMessages());
} else {
// Link
String url = HtmlUtils.getServerAnalysisUrlWithProtocol();
String message = Phrase.CMD_LINK.toString();
String message = Locale.get(Msg.CMD_INFO_LINK).toString();
boolean console = !CommandUtils.isPlayer(sender);
if (console) {
sender.sendMessage(message + url);
} else {
sender.sendMessage(message);
sender.sendLink(" ", Phrase.CMD_CLICK_ME.toString(), url);
sender.sendLink(" ", Locale.get(Msg.CMD_INFO_CLICK_ME).toString(), url);
}
}
sender.sendMessage(Phrase.CMD_FOOTER.toString());
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
}
}

View File

@ -3,11 +3,12 @@ package main.java.com.djrapitops.plan.command.commands;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.settings.Version;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import org.bukkit.ChatColor;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
/**
* This subcommand is used to view the version and the database type in use.
@ -25,20 +26,26 @@ public class InfoCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public InfoCommand(Plan plugin) {
super("info", CommandType.CONSOLE, Permissions.INFO.getPermission(), Phrase.CMD_USG_INFO.toString());
super("info",
CommandType.CONSOLE,
Permissions.INFO.getPermission(),
Locale.get(Msg.CMD_USG_INFO).toString());
this.plugin = plugin;
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
ChatColor tColor = Phrase.COLOR_SEC.color();
ColorScheme cs = plugin.getColorScheme();
String mColor = cs.getMainColor();
String sColor = cs.getSecondaryColor();
String tColor = cs.getTertiaryColor();
String[] messages = {
Phrase.CMD_INFO_HEADER.toString(),
Phrase.CMD_INFO_VERSION.parse(plugin.getDescription().getVersion()),
Phrase.CMD_BALL.toString() + tColor + " " + Version.checkVersion(plugin),
Phrase.CMD_MANAGE_STATUS_ACTIVE_DB.parse(plugin.getDB().getConfigName()),
Phrase.CMD_FOOTER.toString()
Locale.get(Msg.CMD_HEADER_INFO).toString(),
Locale.get(Msg.CMD_CONSTANT_LIST_BALL).toString() + mColor + " Version: " + sColor + plugin.getDescription().getVersion(),
Locale.get(Msg.CMD_CONSTANT_LIST_BALL).toString() + tColor + " " + Version.checkVersion(plugin),
Locale.get(Msg.CMD_CONSTANT_LIST_BALL).toString() + mColor + " Active Database: " + tColor + plugin.getDB().getConfigName(),
Locale.get(Msg.CMD_CONSTANT_FOOTER).toString()
};
sender.sendMessage(messages);
return true;

View File

@ -5,12 +5,16 @@ import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.CommandUtils;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.*;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.command.ConditionUtils;
import main.java.com.djrapitops.plan.data.cache.InspectCacheHandler;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.text.TextUI;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
@ -38,33 +42,25 @@ public class InspectCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public InspectCommand(Plan plugin) {
super("inspect", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.INSPECT.getPermission(), Phrase.CMD_USG_INSPECT.toString(), Phrase.ARG_PLAYER.toString());
super("inspect",
CommandType.CONSOLE_WITH_ARGUMENTS,
Permissions.INSPECT.getPermission(),
Locale.get(Msg.CMD_USG_INSPECT).toString(),
"<player>");
this.plugin = plugin;
inspectCache = plugin.getInspectCache();
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Inspect command",
tCol + " Used to get a link to User's inspect page.",
sCol + " Own inspect page can be accessed with /plan inspect",
sCol + " Alias: /plan <name>"
};
super.setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_INSPECT).toArray();
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Phrase.ERROR_WEBSERVER_OFF_INSPECT.toString(), sender)) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Locale.get(Msg.CMD_FAIL_NO_DATA_VIEW).toString(), sender)) {
return true;
}
@ -80,16 +76,16 @@ public class InspectCommand extends SubCommand {
public void run() {
try {
UUID uuid = UUIDUtility.getUUIDOf(playerName);
if (!Check.isTrue(Verify.notNull(uuid), Phrase.USERNAME_NOT_VALID.toString(), sender)) {
if (!Check.isTrue(Verify.notNull(uuid), Locale.get(Msg.CMD_FAIL_USERNAME_NOT_VALID).toString(), sender)) {
return;
}
if (!Check.isTrue(ConditionUtils.playerHasPlayed(uuid), Phrase.USERNAME_NOT_SEEN.toString(), sender)) {
if (!Check.isTrue(ConditionUtils.playerHasPlayed(uuid), Locale.get(Msg.CMD_FAIL_USERNAME_NOT_SEEN).toString(), sender)) {
return;
}
if (!Check.isTrue(plugin.getDB().wasSeenBefore(uuid), Phrase.USERNAME_NOT_KNOWN.toString(), sender)) {
if (!Check.isTrue(plugin.getDB().wasSeenBefore(uuid), Locale.get(Msg.CMD_FAIL_USERNAME_NOT_KNOWN).toString(), sender)) {
return;
}
sender.sendMessage(Phrase.GRABBING_DATA_MESSAGE.toString());
sender.sendMessage(Locale.get(Msg.CMD_INFO_FETCH_DATA).toString());
if (CommandUtils.isPlayer(sender) && plugin.getUiServer().isAuthRequired()) {
boolean senderHasWebUser = plugin.getDB().getSecurityTable().userExists(sender.getName());
if (!senderHasWebUser) {
@ -121,7 +117,7 @@ public class InspectCommand extends SubCommand {
}
if (timesrun > 10) {
Log.debug("Command Timeout Message, Inspect.");
sender.sendMessage(Phrase.COMMAND_TIMEOUT.parse("Inspect"));
sender.sendMessage(Locale.get(Msg.CMD_FAIL_TIMEOUT).parse("Inspect"));
this.cancel();
}
}
@ -133,23 +129,23 @@ public class InspectCommand extends SubCommand {
boolean usingTextUI = Settings.USE_ALTERNATIVE_UI.isTrue();
sender.sendMessage(Phrase.CMD_INSPECT_HEADER + playerName);
sender.sendMessage(Locale.get(Msg.CMD_HEADER_INSPECT) + playerName);
if (usingTextUI) {
sender.sendMessage(TextUI.getInspectMessages(uuid));
} else {
// Link
String url = HtmlUtils.getInspectUrlWithProtocol(playerName);
String message = Phrase.CMD_LINK.toString();
String message = Locale.get(Msg.CMD_INFO_LINK).toString();
boolean console = !CommandUtils.isPlayer(sender);
if (console) {
sender.sendMessage(message + url);
} else {
sender.sendMessage(message);
sender.sendLink(" ", Phrase.CMD_CLICK_ME.toString(), url);
sender.sendLink(" ", Locale.get(Msg.CMD_INFO_CLICK_ME).toString(), url);
}
}
sender.sendMessage(Phrase.CMD_FOOTER.toString());
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
}
}

View File

@ -4,11 +4,11 @@ import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.CommandUtils;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.command.ConditionUtils;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
@ -28,50 +28,38 @@ public class ListCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public ListCommand(Plan plugin) {
super("list, pl", CommandType.CONSOLE, Permissions.INSPECT_OTHER.getPermission(), "List to all cached players", "");
super("list, pl", CommandType.CONSOLE, Permissions.INSPECT_OTHER.getPermission(), Locale.get(Msg.CMD_USG_LIST).toString(), "");
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "List command",
tCol + " Used to get a link to players page.",
sCol + " Players page contains links to all cached inspect pages.",
sCol + " Alias: /plan pl"
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_LIST).toArray();
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Phrase.ERROR_WEBSERVER_OFF_INSPECT + "", sender)) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Locale.get(Msg.CMD_FAIL_NO_DATA_VIEW) + "", sender)) {
return true;
}
sendListMsg(sender);
return true;
}
private void sendListMsg(ISender sender) {
sender.sendMessage(Phrase.CMD_FOOTER.parse());
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).parse());
// Link
String url = HtmlUtils.getServerAnalysisUrlWithProtocol().replace("server", "players");
String message = Phrase.CMD_LINK.toString();
String message = Locale.get(Msg.CMD_INFO_LINK).toString();
boolean console = !CommandUtils.isPlayer(sender);
if (console) {
sender.sendMessage(message + url);
} else {
sender.sendMessage(message);
sender.sendLink(" ", Phrase.CMD_CLICK_ME.toString(), url);
sender.sendLink(" ", Locale.get(Msg.CMD_INFO_CLICK_ME).toString(), url);
}
sender.sendMessage(Phrase.CMD_FOOTER.toString());
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
}
}

View File

@ -2,11 +2,11 @@ package main.java.com.djrapitops.plan.command.commands;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.TreeCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.command.commands.manage.*;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
/**
* This command is used to manage the database of the plugin.
@ -24,26 +24,13 @@ public class ManageCommand extends TreeCommand<Plan> {
* @param plugin Current instance of Plan
*/
public ManageCommand(Plan plugin) {
super(plugin, "manage,m", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE + "", "plan m");
setHelp(plugin);
super(plugin, "manage,m", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Locale.get(Msg.CMD_USG_MANAGE) + "", "plan m");
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Manage command",
tCol + " Used to Manage Database of the plugin.",
sCol + " Alias: /plan m",
sCol + " /plan m - List subcommands",
sCol + " /plan m <subcommand> ? - in depth help"
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_MANAGE).toArray();
}
@Override
@ -52,10 +39,10 @@ public class ManageCommand extends TreeCommand<Plan> {
commands.add(new ManageHotswapCommand(plugin));
// commands.add(new ManageBackupCommand(plugin));
// commands.add(new ManageRestoreCommand(plugin));
commands.add(new ManageStatusCommand(plugin));
commands.add(new ManageImportCommand(plugin));
commands.add(new ManageRemoveCommand(plugin));
// commands.add(new ManageCleanCommand(plugin));
commands.add(new ManageClearCommand(plugin));
commands.add(new ManageDumpCommand(plugin));
}
}

View File

@ -4,14 +4,14 @@ import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.command.ConditionUtils;
import main.java.com.djrapitops.plan.data.cache.AnalysisCacheHandler;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.text.TextUI;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
@ -34,35 +34,26 @@ public class QuickAnalyzeCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public QuickAnalyzeCommand(Plan plugin) {
super("qanalyze, qanalyse, qanalysis, qa", CommandType.CONSOLE, Permissions.QUICK_ANALYZE.getPermission(), Phrase.CMD_USG_QANALYZE.parse());
super("qanalyze, qanalyse, qanalysis, qa",
CommandType.CONSOLE,
Permissions.QUICK_ANALYZE.getPermission(),
Locale.get(Msg.CMD_USG_QANALYZE).parse());
this.plugin = plugin;
analysisCache = plugin.getAnalysisCache();
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Quick Analysis command",
tCol + " Used to get in game info about analysis.",
sCol + " Has less info than full Analysis web page.",
sCol + " Aliases: qanalyze, ganalyse, qanalysis, qa"
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_PLAN).toArray();
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Phrase.ERROR_WEBSERVER_OFF_ANALYSIS.toString(), sender)) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Locale.get(Msg.CMD_FAIL_NO_DATA_VIEW).toString(), sender)) {
return true;
}
if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Phrase.ERROR_ANALYSIS_DISABLED_TEMPORARILY.toString(), sender)
if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Locale.get(Msg.CMD_INFO_ANALYSIS_TEMP_DISABLE).toString(), sender)
&& !analysisCache.isCached()) {
return true;
}
@ -91,14 +82,14 @@ public class QuickAnalyzeCommand extends SubCommand {
public void run() {
timesRun++;
if (analysisCache.isCached() && (!analysisCache.isAnalysisBeingRun() || !analysisCache.isAnalysisEnabled())) {
sender.sendMessage(Phrase.CMD_ANALYZE_HEADER + "");
sender.sendMessage(Locale.get(Msg.CMD_HEADER_ANALYZE) + "");
sender.sendMessage(TextUI.getAnalysisMessages());
sender.sendMessage(Phrase.CMD_FOOTER + "");
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER) + "");
this.cancel();
}
if (timesRun > 10) {
Log.debug("Command Timeout Message, QuickAnalyze.");
sender.sendMessage(Phrase.COMMAND_TIMEOUT.parse("Analysis"));
sender.sendMessage(Locale.get(Msg.CMD_FAIL_TIMEOUT).parse("Analysis"));
this.cancel();
}
}

View File

@ -4,15 +4,15 @@ import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.command.ConditionUtils;
import main.java.com.djrapitops.plan.data.cache.InspectCacheHandler;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.text.TextUI;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
@ -38,28 +38,19 @@ public class QuickInspectCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public QuickInspectCommand(Plan plugin) {
super("qinspect, qi", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.QUICK_INSPECT.getPermission(), Phrase.CMD_USG_QINSPECT + "", Phrase.ARG_PLAYER + "");
super("qinspect, qi",
CommandType.CONSOLE_WITH_ARGUMENTS,
Permissions.QUICK_INSPECT.getPermission(),
Locale.get(Msg.CMD_USG_QINSPECT).toString(), "<player>");
this.plugin = plugin;
inspectCache = plugin.getInspectCache();
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Quick Inspect command",
tCol + " Used to get some inspect info in game.",
sCol + " Has less info than full Inspect web page.",
sCol + " Alias: /plan qi"
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_QINSPECT).toArray();
}
@Override
@ -70,16 +61,16 @@ public class QuickInspectCommand extends SubCommand {
public void run() {
try {
UUID uuid = UUIDUtility.getUUIDOf(playerName);
if (!Check.isTrue(Verify.notNull(uuid), Phrase.USERNAME_NOT_VALID.toString(), sender)) {
if (!Check.isTrue(Verify.notNull(uuid), Locale.get(Msg.CMD_FAIL_USERNAME_NOT_VALID).toString(), sender)) {
return;
}
if (!Check.isTrue(ConditionUtils.playerHasPlayed(uuid), Phrase.USERNAME_NOT_SEEN.toString(), sender)) {
if (!Check.isTrue(ConditionUtils.playerHasPlayed(uuid), Locale.get(Msg.CMD_FAIL_USERNAME_NOT_SEEN).toString(), sender)) {
return;
}
if (!Check.isTrue(plugin.getDB().wasSeenBefore(uuid), Phrase.USERNAME_NOT_KNOWN.toString(), sender)) {
if (!Check.isTrue(plugin.getDB().wasSeenBefore(uuid), Locale.get(Msg.CMD_FAIL_USERNAME_NOT_KNOWN).toString(), sender)) {
return;
}
sender.sendMessage(Phrase.GRABBING_DATA_MESSAGE + "");
sender.sendMessage(Locale.get(Msg.CMD_INFO_FETCH_DATA).toString());
inspectCache.cache(uuid);
runMessageSenderTask(uuid, sender, playerName);
} finally {
@ -98,14 +89,14 @@ public class QuickInspectCommand extends SubCommand {
public void run() {
timesrun++;
if (inspectCache.isCached(uuid)) {
sender.sendMessage(Phrase.CMD_INSPECT_HEADER + playerName);
sender.sendMessage(Locale.get(Msg.CMD_HEADER_INSPECT) + playerName);
sender.sendMessage(TextUI.getInspectMessages(uuid));
sender.sendMessage(Phrase.CMD_FOOTER + "");
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER) + "");
this.cancel();
}
if (timesrun > 10) {
Log.debug("Command Timeout Message, QuickInspect.");
sender.sendMessage(Phrase.COMMAND_TIMEOUT.parse("Qinspect"));
sender.sendMessage(Locale.get(Msg.CMD_FAIL_TIMEOUT).parse("Qinspect"));
this.cancel();
}
}

View File

@ -4,14 +4,14 @@ import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.CommandUtils;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.database.tables.SecurityTable;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.PassEncryptUtil;
import org.bukkit.ChatColor;
@ -33,31 +33,23 @@ public class RegisterCommand extends SubCommand {
private final Plan plugin;
public RegisterCommand(Plan plugin) {
super("register", CommandType.CONSOLE_WITH_ARGUMENTS, "", "Register a user for the webserver", "<password> [name] [access lvl]");
super("register",
CommandType.CONSOLE_WITH_ARGUMENTS,
"", // No Permission Requirement
Locale.get(Msg.CMD_USG_WEB_REGISTER).toString(),
"<password> [name] [access lvl]");
this.plugin = plugin;
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Web Register command",
tCol + " Used to register a new user for the webserver.",
sCol + " Registering a user for another player requires " + Permissions.MANAGE_WEB.getPerm() + " permission.",
sCol + " Passwords are hashed with PBKDF2 (64,000 iterations of SHA1) using a cryptographically-random salt."
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_WEB_REGISTER).toArray();
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
String notEnoughArgsMsg = Phrase.COMMAND_REQUIRES_ARGUMENTS.parse("(3) " + super.getArguments());
String notEnoughArgsMsg = Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse("(3) " + super.getArguments());
String hashErrorMsg = ChatColor.RED + "Password hash error.";
String permLvlErrorMsg = ChatColor.RED + "Incorrect perm level, not a number: ";
try {
@ -88,7 +80,7 @@ public class RegisterCommand extends SubCommand {
}
private void playerRegister(String[] args, ISender sender) throws PassEncryptUtil.CannotPerformOperationException {
final String notEnoughArgsMsg = Phrase.COMMAND_REQUIRES_ARGUMENTS.parse("(1 or 3) " + super.getArguments());
final String notEnoughArgsMsg = Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse("(1 or 3) " + super.getArguments());
boolean registerSenderAsUser = args.length == 1;
if (registerSenderAsUser) {
String user = sender.getName();
@ -98,7 +90,7 @@ public class RegisterCommand extends SubCommand {
} else if (sender.hasPermission(Permissions.MANAGE_WEB.getPermission())) {
consoleRegister(args, sender, notEnoughArgsMsg);
} else {
sender.sendMessage(Phrase.COMMAND_NO_PERMISSION.parse());
sender.sendMessage(Locale.get(Msg.CMD_FAIL_NO_PERMISSION).parse());
}
}

View File

@ -4,8 +4,9 @@ import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
/**
* This subcommand is used to reload the plugin.
@ -23,7 +24,10 @@ public class ReloadCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public ReloadCommand(Plan plugin) {
super("reload", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_RELOAD.toString());
super("reload",
CommandType.CONSOLE,
Permissions.MANAGE.getPermission(),
Locale.get(Msg.CMD_USG_RELOAD).toString());
this.plugin = plugin;
}
@ -33,7 +37,7 @@ public class ReloadCommand extends SubCommand {
plugin.onDisable();
plugin.reloadConfig();
plugin.onEnable();
sender.sendMessage(Phrase.RELOAD_COMPLETE.toString());
sender.sendMessage(Locale.get(Msg.CMD_INFO_RELOAD_COMPLETE).toString());
return true;
}

View File

@ -3,12 +3,12 @@ package main.java.com.djrapitops.plan.command.commands;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.FormattingUtils;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
@ -31,33 +31,26 @@ public class SearchCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public SearchCommand(Plan plugin) {
super("search", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.SEARCH.getPermission(), Phrase.CMD_USG_SEARCH.toString(), Phrase.ARG_SEARCH.toString());
super("search",
CommandType.CONSOLE_WITH_ARGUMENTS,
Permissions.SEARCH.getPermission(),
Locale.get(Msg.CMD_USG_SEARCH).toString(),
"<part of playername>");
this.plugin = plugin;
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Search command",
tCol + " Used to get a list of Player names that match the given argument.",
sCol + " Example: /plan search 123 - Finds all users with 123 in their name."
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_SEARCH).toArray();
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE.toString(), sender)) {
if (!Check.isTrue(args.length >= 1, Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString(), sender)) {
return true;
}
sender.sendMessage(Phrase.CMD_SEARCH_SEARCHING.toString());
sender.sendMessage(Locale.get(Msg.CMD_INFO_SEARCHING).toString());
runSearchTask(args, sender);
return true;
@ -69,15 +62,15 @@ public class SearchCommand extends SubCommand {
public void run() {
try {
List<String> names = MiscUtils.getMatchingPlayerNames(args[0]);
sender.sendMessage(Phrase.CMD_SEARCH_HEADER + args[0] + " (" + names.size() + ")");
sender.sendMessage(Locale.get(Msg.CMD_HEADER_SEARCH) + args[0] + " (" + names.size() + ")");
// Results
if (names.isEmpty()) {
sender.sendMessage(Phrase.CMD_NO_RESULTS.parse(Arrays.toString(args)));
sender.sendMessage(Locale.get(Msg.CMD_INFO_NO_RESULTS).parse(Arrays.toString(args)));
} else {
sender.sendMessage(Phrase.CMD_MATCH.toString() + FormattingUtils.collectionToStringNoBrackets(names));
sender.sendMessage(Locale.get(Msg.CMD_INFO_RESULTS).toString() + FormattingUtils.collectionToStringNoBrackets(names));
}
sender.sendMessage(Phrase.CMD_FOOTER.toString());
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
} finally {
this.cancel();
}

View File

@ -2,13 +2,14 @@ package main.java.com.djrapitops.plan.command.commands;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.TreeCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.command.commands.webuser.WebCheckCommand;
import main.java.com.djrapitops.plan.command.commands.webuser.WebDeleteCommand;
import main.java.com.djrapitops.plan.command.commands.webuser.WebLevelCommand;
import main.java.com.djrapitops.plan.command.commands.webuser.WebListUsersCommand;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
/**
* Web subcommand used to manage Web users.
@ -19,29 +20,18 @@ import main.java.com.djrapitops.plan.command.commands.webuser.WebListUsersComman
public class WebUserCommand extends TreeCommand<Plan> {
public WebUserCommand(Plan plugin, RegisterCommand register) {
super(plugin, "webuser, web", CommandType.CONSOLE, Permissions.MANAGE_WEB.getPerm(), "Manage Webusers", "plan web");
super(plugin, "webuser, web",
CommandType.CONSOLE,
Permissions.MANAGE_WEB.getPerm(),
Locale.get(Msg.CMD_USG_WEB).toString(),
"plan web");
commands.add(register);
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Web User Manage command",
tCol + " Used to manage web users of the plugin",
sCol + " Users have a permission level:",
tCol + " 0 - Access to all pages",
tCol + " 1 - Access to /players & all inspect pages",
tCol + " 2 - Access to own inspect page",
sCol + " Alias: /plan web"
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_WEB).toArray();
}
@Override

View File

@ -7,9 +7,10 @@ import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.ManageUtils;
@ -29,7 +30,11 @@ public class ManageBackupCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public ManageBackupCommand(Plan plugin) {
super("backup", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_BACKUP.toString(), "<DB>");
super("backup",
CommandType.CONSOLE,
Permissions.MANAGE.getPermission(),
Locale.get(Msg.CMD_USG_MANAGE_BACKUP).toString(),
"<DB>");
this.plugin = plugin;
}
@ -37,26 +42,26 @@ public class ManageBackupCommand extends SubCommand {
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
try {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS.parse(Phrase.USE_BACKUP.toString()), sender)) {
if (!Check.isTrue(args.length >= 1, Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse(this.getArguments()), sender)) {
return true;
}
String dbName = args[0].toLowerCase();
boolean isCorrectDB = "sqlite".equals(dbName) || "mysql".equals(dbName);
if (Check.isTrue(isCorrectDB, Phrase.MANAGE_ERROR_INCORRECT_DB + dbName, sender)) {
if (Check.isTrue(isCorrectDB, Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + dbName, sender)) {
return true;
}
final Database database = ManageUtils.getDB(plugin, dbName);
// If DB is null return
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
if (!Check.isTrue(Verify.notNull(database), Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString(), sender)) {
Log.error(dbName + " was null!");
return true;
}
runBackupTask(sender, args, database);
} catch (NullPointerException e) {
sender.sendMessage(Phrase.MANAGE_DATABASE_FAILURE.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString());
}
return true;
}
@ -66,15 +71,15 @@ public class ManageBackupCommand extends SubCommand {
@Override
public void run() {
try {
sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
if (ManageUtils.backup(args[0], database)) {
sender.sendMessage(Phrase.MANAGE_COPY_SUCCESS.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_COPY_SUCCESS).toString());
} else {
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
}
} catch (Exception e) {
Log.toLog(this.getClass().getName() + " " + getTaskName(), e);
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
} finally {
this.cancel();
}

View File

@ -7,9 +7,10 @@ import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.ManageUtils;
@ -29,28 +30,32 @@ public class ManageCleanCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public ManageCleanCommand(Plan plugin) {
super("clean", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_CLEAN.toString(), "<DB>");
super("clean",
CommandType.CONSOLE_WITH_ARGUMENTS,
Permissions.MANAGE.getPermission(),
Locale.get(Msg.CMD_USG_MANAGE_CLEAN).toString(),
"<DB>");
this.plugin = plugin;
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length != 0, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE.toString(), sender)) {
if (!Check.isTrue(args.length != 0, Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString(), sender)) {
return true;
}
String dbName = args[0].toLowerCase();
boolean isCorrectDB = "sqlite".equals(dbName) || "mysql".equals(dbName);
if (!Check.isTrue(isCorrectDB, Phrase.MANAGE_ERROR_INCORRECT_DB + dbName, sender)) {
if (!Check.isTrue(isCorrectDB, Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + dbName, sender)) {
return true;
}
final Database database = ManageUtils.getDB(plugin, dbName);
// If DB is null return
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
if (!Check.isTrue(Verify.notNull(database), Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString(), sender)) {
Log.error(dbName + " was null!");
return true;
}
@ -63,9 +68,9 @@ public class ManageCleanCommand extends SubCommand {
plugin.getRunnableFactory().createNew(new AbsRunnable("DBCleanTask") {
@Override
public void run() {
sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
database.clean();
sender.sendMessage(Phrase.MANAGE_SUCCESS.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_SUCCESS).toString());
this.cancel();
}
}).runTaskAsynchronously();

View File

@ -3,14 +3,14 @@ package main.java.com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.ManageUtils;
@ -30,50 +30,42 @@ public class ManageClearCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public ManageClearCommand(Plan plugin) {
super("clear", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_CLEAR + "", "<DB> [-a]");
super("clear",
CommandType.CONSOLE_WITH_ARGUMENTS,
Permissions.MANAGE.getPermission(),
Locale.get(Msg.CMD_USG_MANAGE_CLEAR).toString(),
"<DB> [-a]");
this.plugin = plugin;
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Manage Clear command",
tCol + " Used to delete ALL data in the active database.",
sCol + " Plugin should be reloaded after successful clear.",
sCol + " Alias: /plan pl"
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_MANAGE_CLEAR).toArray();
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE.toString(), sender)) {
if (!Check.isTrue(args.length >= 1, Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString(), sender)) {
return true;
}
String dbName = args[0].toLowerCase();
boolean isCorrectDB = "sqlite".equals(dbName) || "mysql".equals(dbName);
if (!Check.isTrue(isCorrectDB, Phrase.MANAGE_ERROR_INCORRECT_DB + dbName, sender)) {
if (!Check.isTrue(isCorrectDB, Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + dbName, sender)) {
return true;
}
if (!Check.isTrue(Verify.contains("-a", args), Phrase.COMMAND_ADD_CONFIRMATION_ARGUMENT.parse(Phrase.WARN_REMOVE.parse(args[0])), sender)) {
if (!Check.isTrue(Verify.contains("-a", args), Locale.get(Msg.MANAGE_FAIL_CONFIRM).parse(Locale.get(Msg.MANAGE_NOTIFY_REMOVE).parse(args[0])), sender)) {
return true;
}
final Database database = ManageUtils.getDB(plugin, dbName);
// If DB is null return
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
if (!Check.isTrue(Verify.notNull(database), Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString(), sender)) {
Log.error(dbName + " was null!");
return true;
}
@ -87,13 +79,13 @@ public class ManageClearCommand extends SubCommand {
@Override
public void run() {
try {
sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
if (database.removeAllData()) {
plugin.getHandler().getDataCache().clear();
sender.sendMessage(Phrase.MANAGE_CLEAR_SUCCESS.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_CLEAR_SUCCESS).toString());
} else {
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
}
} finally {
this.cancel();

View File

@ -0,0 +1,58 @@
package main.java.com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.task.AbsRunnable;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.file.dump.DumpUtils;
/**
* This manage subcommand is used to dump important data to pastebin, so it's
* easier to write an issue.
*
* @author Fuzzlemann
* @since 3.7.0
*/
public class ManageDumpCommand extends SubCommand {
private final Plan plugin;
/**
* Class Constructor.
*
* @param plugin Current instance of Plan
*/
public ManageDumpCommand(Plan plugin) {
super("dump",
CommandType.CONSOLE,
Permissions.MANAGE.getPermission(),
Locale.get(Msg.CMD_USG_MANAGE_DUMP).toString());
this.plugin = plugin;
}
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_MANAGE_DUMP).toArray();
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
dump(sender);
return true;
}
private void dump(ISender sender) {
plugin.getRunnableFactory().createNew(new AbsRunnable("DumpTask") {
@Override
public void run() {
sender.sendLink("Link to the Dump", DumpUtils.dump(plugin));
sender.sendLink("Report Issues here", "https://github.com/Rsl1122/Plan-PlayerAnalytics/issues/new");
}
}).runTaskAsynchronously();
}
}

View File

@ -3,13 +3,13 @@ package main.java.com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.ManageUtils;
@ -30,48 +30,41 @@ public class ManageHotswapCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public ManageHotswapCommand(Plan plugin) {
super("hotswap", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_HOTSWAP.toString(), "<DB>");
super("hotswap",
CommandType.CONSOLE_WITH_ARGUMENTS,
Permissions.MANAGE.getPermission(),
Locale.get(Msg.CMD_USG_MANAGE_HOTSWAP).toString(),
"<DB>");
this.plugin = plugin;
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Manage Hotswap command",
tCol + " Used to change database in use on the fly.",
sCol + " Does not change database if connection fails"
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_MANAGE_HOTSWAP).toArray();
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE.toString(), sender)) {
if (!Check.isTrue(args.length >= 1, Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString(), sender)) {
return true;
}
String dbName = args[0].toLowerCase();
boolean isCorrectDB = "sqlite".equals(dbName) || "mysql".equals(dbName);
if (!Check.isTrue(isCorrectDB, Phrase.MANAGE_ERROR_INCORRECT_DB + dbName, sender)) {
if (!Check.isTrue(isCorrectDB, Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + dbName, sender)) {
return true;
}
if (Check.isTrue(dbName.equals(plugin.getDB().getConfigName()), Phrase.MANAGE_ERROR_SAME_DB.toString(), sender)) {
if (Check.isTrue(dbName.equals(plugin.getDB().getConfigName()), Locale.get(Msg.MANAGE_FAIL_SAME_DB).toString(), sender)) {
return true;
}
final Database database = ManageUtils.getDB(plugin, dbName);
// If DB is null return
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
if (!Check.isTrue(Verify.notNull(database), Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString(), sender)) {
Log.error(dbName + " was null!");
return true;
}
@ -80,7 +73,7 @@ public class ManageHotswapCommand extends SubCommand {
database.getVersion(); //Test db connection
} catch (Exception e) {
Log.toLog(this.getClass().getName(), e);
sender.sendMessage(Phrase.MANAGE_DATABASE_FAILURE.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString());
return true;
}

View File

@ -3,16 +3,16 @@ package main.java.com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.FormattingUtils;
import com.djrapitops.plugin.utilities.player.Fetch;
import com.djrapitops.plugin.utilities.player.IOfflinePlayer;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.handling.importing.ImportUtils;
import main.java.com.djrapitops.plan.data.handling.importing.Importer;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import java.util.List;
@ -38,31 +38,24 @@ public class ManageImportCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public ManageImportCommand(Plan plugin) {
super("import", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_IMPORT.toString(), Phrase.ARG_IMPORT.toString());
super("import",
CommandType.CONSOLE,
Permissions.MANAGE.getPermission(),
Locale.get(Msg.CMD_USG_MANAGE_IMPORT).toString(),
"<plugin>/list [import args]");
this.plugin = plugin;
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Manage Import command",
tCol + " Used to import data from other sources",
sCol + " Analysis will be disabled during import.",
sCol + " If a lot of users are not in the database, saving may take a long time."
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_MANAGE_IMPORT).toArray();
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE + " " + Phrase.USE_IMPORT, sender)) {
if (!Check.isTrue(args.length >= 1, Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG) + " " + this.getArguments(), sender)) {
return true;
}
@ -74,11 +67,11 @@ public class ManageImportCommand extends SubCommand {
return true;
}
if (!Check.isTrue(importPlugins.keySet().contains(importFromPlugin), Phrase.MANAGE_ERROR_INCORRECT_PLUGIN + importFromPlugin, sender)) {
if (!Check.isTrue(importPlugins.keySet().contains(importFromPlugin), Locale.get(Msg.MANAGE_FAIL_INCORRECT_PLUGIN) + importFromPlugin, sender)) {
return true;
}
if (!Check.isTrue(ImportUtils.isPluginEnabled(importFromPlugin), Phrase.MANAGE_ERROR_PLUGIN_NOT_ENABLED + importFromPlugin, sender)) {
if (!Check.isTrue(ImportUtils.isPluginEnabled(importFromPlugin), Locale.get(Msg.MANAGE_FAIL_PLUGIN_NOT_ENABLED) + importFromPlugin, sender)) {
return true;
}
@ -94,12 +87,12 @@ public class ManageImportCommand extends SubCommand {
@Override
public void run() {
try {
sender.sendMessage(Phrase.MANAGE_IMPORTING.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_IMPORT).toString());
List<UUID> uuids = Fetch.getIOfflinePlayers().stream().map(IOfflinePlayer::getUniqueId).collect(Collectors.toList());
if (importer.importData(uuids, importArguments)) {
sender.sendMessage(Phrase.MANAGE_SUCCESS.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_SUCCESS).toString());
} else {
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
}
} finally {
this.cancel();
@ -109,8 +102,8 @@ public class ManageImportCommand extends SubCommand {
}
private void list(Map<String, Importer> importers, ISender sender) {
sender.sendMessage(Phrase.CMD_FOOTER.parse());
importers.forEach((string, importer) -> sender.sendMessage(Phrase.CMD_BALL + " " + string + ": " + importer.getInfo()));
sender.sendMessage(Phrase.CMD_FOOTER.parse());
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).parse());
importers.forEach((string, importer) -> sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_LIST_BALL) + " " + string + ": " + importer.getInfo()));
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).parse());
}
}

View File

@ -7,9 +7,10 @@ import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.ManageUtils;
@ -34,49 +35,53 @@ public class ManageMoveCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public ManageMoveCommand(Plan plugin) {
super("move", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_MOVE.toString(), Phrase.ARG_MOVE.toString());
super("move",
CommandType.CONSOLE_WITH_ARGUMENTS,
Permissions.MANAGE.getPermission(),
Locale.get(Msg.CMD_USG_MANAGE_MOVE).toString(),
"<fromDB> <toDB> [-a]");
this.plugin = plugin;
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length >= 2, Phrase.COMMAND_REQUIRES_ARGUMENTS.parse(Phrase.USE_MOVE.toString()), sender)) {
if (!Check.isTrue(args.length >= 2, Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse(this.getArguments()), sender)) {
return true;
}
String fromDB = args[0].toLowerCase();
boolean isCorrectDB = "sqlite".equals(fromDB) || "mysql".equals(fromDB);
if (!Check.isTrue(isCorrectDB, Phrase.MANAGE_ERROR_INCORRECT_DB + fromDB, sender)) {
if (!Check.isTrue(isCorrectDB, Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + fromDB, sender)) {
return true;
}
String toDB = args[1].toLowerCase();
isCorrectDB = "sqlite".equals(toDB) || "mysql".equals(toDB);
if (!Check.isTrue(isCorrectDB, Phrase.MANAGE_ERROR_INCORRECT_DB + toDB, sender)) {
if (!Check.isTrue(isCorrectDB, Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + toDB, sender)) {
return true;
}
if (!Check.isTrue(!Verify.equalsIgnoreCase(fromDB, toDB), Phrase.MANAGE_ERROR_SAME_DB.toString(), sender)) {
if (!Check.isTrue(!Verify.equalsIgnoreCase(fromDB, toDB), Locale.get(Msg.MANAGE_FAIL_SAME_DB).toString(), sender)) {
return true;
}
if (!Check.isTrue(Verify.contains("-a", args), Phrase.COMMAND_ADD_CONFIRMATION_ARGUMENT.parse(Phrase.WARN_REMOVE.parse(args[1])), sender)) {
if (!Check.isTrue(Verify.contains("-a", args), Locale.get(Msg.MANAGE_FAIL_CONFIRM).parse(Locale.get(Msg.MANAGE_NOTIFY_REMOVE).parse(args[1])), sender)) {
return true;
}
final Database fromDatabase = ManageUtils.getDB(plugin, fromDB);
if (!Check.isTrue(Verify.notNull(fromDatabase), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
if (!Check.isTrue(Verify.notNull(fromDatabase), Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString(), sender)) {
Log.error(fromDB + " was null!");
return true;
}
final Database toDatabase = ManageUtils.getDB(plugin, toDB);
if (!Check.isTrue(Verify.notNull(toDatabase), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
if (!Check.isTrue(Verify.notNull(toDatabase), Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString(), sender)) {
Log.error(toDB + " was null!");
return true;
}
@ -91,23 +96,23 @@ public class ManageMoveCommand extends SubCommand {
public void run() {
try {
final Collection<UUID> uuids = ManageUtils.getUUIDS(fromDatabase);
if (Check.isTrue(Verify.isEmpty(uuids), Phrase.MANAGE_ERROR_NO_PLAYERS + " (" + fromDatabase.getName() + ")", sender)) {
if (Check.isTrue(Verify.isEmpty(uuids), Locale.get(Msg.MANAGE_FAIL_NO_PLAYERS) + " (" + fromDatabase.getName() + ")", sender)) {
return;
}
sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
if (ManageUtils.clearAndCopy(toDatabase, fromDatabase, uuids)) {
sender.sendMessage(Phrase.MANAGE_MOVE_SUCCESS.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_MOVE_SUCCESS).toString());
boolean movedToCurrentDatabase = Verify.equalsIgnoreCase(toDatabase.getConfigName(), plugin.getDB().getConfigName());
Check.isTrue(!movedToCurrentDatabase, Phrase.MANAGE_DB_CONFIG_REMINDER.toString(), sender);
Check.isTrue(!movedToCurrentDatabase, Locale.get(Msg.MANAGE_INFO_CONFIG_REMINDER).toString(), sender);
} else {
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
}
} catch (Exception e) {
Log.toLog(this.getClass().getName() + " " + getTaskName(), e);
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
} finally {
this.cancel();
}

View File

@ -3,13 +3,13 @@ package main.java.com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.uuid.UUIDUtility;
@ -33,29 +33,24 @@ public class ManageRemoveCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public ManageRemoveCommand(Plan plugin) {
super("remove", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_REMOVE.toString(), Phrase.ARG_PLAYER + " [-a]");
super("remove",
CommandType.CONSOLE_WITH_ARGUMENTS,
Permissions.MANAGE.getPermission(),
Locale.get(Msg.CMD_USG_MANAGE_REMOVE).toString(),
"<player> [-a]");
this.plugin = plugin;
setHelp(plugin);
}
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String mCol = colorScheme.getMainColor();
String tCol = colorScheme.getTertiaryColor();
String[] help = new String[]{
mCol + "Manage Remove command",
tCol + " Used to Remove user's data from the active database."
};
setInDepthHelp(help);
@Override
public String[] addHelp() {
return Locale.get(Msg.CMD_HELP_MANAGE_REMOVE).toArray();
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE.toString(), sender)) {
if (!Check.isTrue(args.length >= 1, Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).toString(), sender)) {
return true;
}
@ -71,33 +66,33 @@ public class ManageRemoveCommand extends SubCommand {
public void run() {
try {
UUID uuid = UUIDUtility.getUUIDOf(playerName);
String message = Phrase.USERNAME_NOT_VALID.toString();
String message = Locale.get(Msg.CMD_FAIL_USERNAME_NOT_VALID).toString();
if (!Check.isTrue(Verify.notNull(uuid), message, sender)) {
return;
}
message = Phrase.USERNAME_NOT_KNOWN.toString();
message = Locale.get(Msg.CMD_FAIL_USERNAME_NOT_KNOWN).toString();
if (!Check.isTrue(plugin.getDB().wasSeenBefore(uuid), message, sender)) {
return;
}
message = Phrase.COMMAND_ADD_CONFIRMATION_ARGUMENT.parse(Phrase.WARN_REMOVE.parse(plugin.getDB().getConfigName()));
message = Locale.get(Msg.MANAGE_FAIL_CONFIRM).parse(Locale.get(Msg.MANAGE_NOTIFY_REMOVE).parse(plugin.getDB().getConfigName()));
if (!Check.isTrue(Verify.contains("-a", args), message, sender)) {
return;
}
sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
try {
plugin.getHandler().getDataCache().remove(uuid);
if (plugin.getDB().removeAccount(uuid.toString())) {
sender.sendMessage(Phrase.MANAGE_REMOVE_SUCCESS.parse(playerName, plugin.getDB().getConfigName()));
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_REMOVE_SUCCESS).parse(playerName, plugin.getDB().getConfigName()));
} else {
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
}
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
}
} finally {
this.cancel();

View File

@ -7,10 +7,11 @@ import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.database.databases.SQLiteDB;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.ManageUtils;
@ -34,31 +35,35 @@ public class ManageRestoreCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public ManageRestoreCommand(Plan plugin) {
super("restore", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_RESTORE.toString(), Phrase.ARG_RESTORE.toString());
super("restore",
CommandType.CONSOLE,
Permissions.MANAGE.getPermission(),
Locale.get(Msg.CMD_USG_MANAGE_RESTORE).toString(),
"<Filename.db> <dbTo> [-a]");
this.plugin = plugin;
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length >= 2, Phrase.COMMAND_REQUIRES_ARGUMENTS.parse(Phrase.USE_RESTORE.toString()), sender)) {
if (!Check.isTrue(args.length >= 2, Locale.get(Msg.CMD_FAIL_REQ_ARGS).parse(this.getArguments()), sender)) {
return true;
}
String db = args[1].toLowerCase();
boolean isCorrectDB = "sqlite".equals(db) || "mysql".equals(db);
if (!Check.isTrue(isCorrectDB, Phrase.MANAGE_ERROR_INCORRECT_DB + db, sender)) {
if (!Check.isTrue(isCorrectDB, Locale.get(Msg.MANAGE_FAIL_INCORRECT_DB) + db, sender)) {
return true;
}
if (!Check.isTrue(Verify.contains("-a", args), Phrase.COMMAND_ADD_CONFIRMATION_ARGUMENT.parse(Phrase.WARN_REWRITE.parse(args[1])), sender)) {
if (!Check.isTrue(Verify.contains("-a", args), Locale.get(Msg.MANAGE_FAIL_CONFIRM).parse(Locale.get(Msg.MANAGE_NOTIFY_REWRITE).parse(args[1])), sender)) {
return true;
}
final Database database = ManageUtils.getDB(plugin, db);
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
if (!Check.isTrue(Verify.notNull(database), Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString(), sender)) {
Log.error(db + " was null!");
return true;
}
@ -76,7 +81,7 @@ public class ManageRestoreCommand extends SubCommand {
boolean containsDBFileExtension = backupDBName.endsWith(".db");
File backupDBFile = new File(plugin.getDataFolder(), backupDBName + (containsDBFileExtension ? "" : ".db"));
if (!Check.isTrue(Verify.exists(backupDBFile), Phrase.MANAGE_ERROR_BACKUP_FILE_NOT_FOUND + " " + args[0], sender)) {
if (!Check.isTrue(Verify.exists(backupDBFile), Locale.get(Msg.MANAGE_FAIL_FILE_NOT_FOUND) + " " + args[0], sender)) {
return;
}
@ -86,14 +91,14 @@ public class ManageRestoreCommand extends SubCommand {
SQLiteDB backupDB = new SQLiteDB(plugin, backupDBName);
if (!backupDB.init()) {
sender.sendMessage(Phrase.MANAGE_DATABASE_FAILURE.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_FAIL_FAULTY_DB).toString());
return;
}
sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
final Collection<UUID> uuids = ManageUtils.getUUIDS(backupDB);
if (!Check.isTrue(!Verify.isEmpty(uuids), Phrase.MANAGE_ERROR_NO_PLAYERS + " (" + backupDBName + ")", sender)) {
if (!Check.isTrue(!Verify.isEmpty(uuids), Locale.get(Msg.MANAGE_FAIL_NO_PLAYERS) + " (" + backupDBName + ")", sender)) {
return;
}
@ -102,13 +107,13 @@ public class ManageRestoreCommand extends SubCommand {
plugin.getHandler().getCommandUseFromDb();
}
sender.sendMessage(Phrase.MANAGE_COPY_SUCCESS.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_COPY_SUCCESS).toString());
} else {
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
}
} catch (Exception e) {
Log.toLog(this.getClass().getName() + " " + getTaskName(), e);
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());
} finally {
this.cancel();
}

View File

@ -1,45 +0,0 @@
package main.java.com.djrapitops.plan.command.commands.manage;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
/**
* This manage subcommand is used to check the status of the database.
*
* @author Rsl1122
*/
public class ManageStatusCommand extends SubCommand {
private final Plan plugin;
/**
* Class Constructor.
*
* @param plugin Current instance of Plan
*/
public ManageStatusCommand(Plan plugin) {
super("status", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_STATUS.toString());
this.plugin = plugin;
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
String[] messages = new String[]{
Phrase.CMD_MANAGE_STATUS_HEADER.toString(),
Phrase.CMD_MANAGE_STATUS_ACTIVE_DB.parse(plugin.getDB().getConfigName()),
Phrase.CMD_MANAGE_STATUS_QUEUE_PROCESS.parse(String.valueOf(plugin.getHandler().getProcessTask().size())),
Phrase.CMD_MANAGE_STATUS_QUEUE_SAVE.parse(String.valueOf(plugin.getHandler().getSaveTask().size())),
Phrase.CMD_MANAGE_STATUS_QUEUE_GET.parse(String.valueOf(plugin.getHandler().getGetTask().size())),
Phrase.CMD_MANAGE_STATUS_QUEUE_CLEAR.parse(String.valueOf(plugin.getHandler().getClearTask().size())),
Phrase.CMD_FOOTER.toString()
};
sender.sendMessage(messages);
return true;
}
}

View File

@ -6,10 +6,11 @@ import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.task.AbsRunnable;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.database.tables.SecurityTable;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import org.bukkit.ChatColor;
@ -24,13 +25,17 @@ public class WebCheckCommand extends SubCommand {
private final Plan plugin;
public WebCheckCommand(Plan plugin) {
super("check", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.MANAGE_WEB.getPerm(), "Check a webuser and their permission level.", "<username>");
super("check",
CommandType.CONSOLE_WITH_ARGUMENTS,
Permissions.MANAGE_WEB.getPerm(),
Locale.get(Msg.CMD_USG_WEB_CHECK).toString(),
"<username>");
this.plugin = plugin;
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE.parse() + " <username>", sender)) {
if (!Check.isTrue(args.length >= 1, Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).parse() + " <username>", sender)) {
return true;
}
SecurityTable table = plugin.getDB().getSecurityTable();
@ -43,11 +48,11 @@ public class WebCheckCommand extends SubCommand {
if (!Check.isTrue(table.userExists(user), ChatColor.RED + "[Plan] User Doesn't exist.", sender)) {
return;
}
WebUser info = table.getSecurityInfo(user);
WebUser info = table.getWebUser(user);
sender.sendMessage(info.getName() + ": Permission level: " + info.getPermLevel());
} catch (Exception ex) {
Log.toLog(this.getClass().getName(), ex);
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.parse());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).parse());
} finally {
this.cancel();
}

View File

@ -6,9 +6,10 @@ import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.task.AbsRunnable;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.tables.SecurityTable;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import net.md_5.bungee.api.ChatColor;
@ -23,13 +24,17 @@ public class WebDeleteCommand extends SubCommand {
private final Plan plugin;
public WebDeleteCommand(Plan plugin) {
super("delete", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.MANAGE_WEB.getPerm(), "Delete a webuser", "<username>");
super("delete, remove",
CommandType.CONSOLE_WITH_ARGUMENTS,
Permissions.MANAGE_WEB.getPerm(),
Locale.get(Msg.CMD_USG_WEB_DELETE).toString(),
"<username>");
this.plugin = plugin;
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE.parse() + " <username>", sender)) {
if (!Check.isTrue(args.length >= 1, Locale.get(Msg.CMD_FAIL_REQ_ONE_ARG).parse() + " <username>", sender)) {
return true;
}
SecurityTable table = plugin.getDB().getSecurityTable();
@ -43,13 +48,13 @@ public class WebDeleteCommand extends SubCommand {
return;
}
if (table.removeUser(user)) {
sender.sendMessage(Phrase.MANAGE_SUCCESS.parse());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_SUCCESS).parse());
} else {
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.parse());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).parse());
}
} catch (Exception ex) {
Log.toLog(this.getClass().getName(), ex);
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.parse());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).parse());
} finally {
this.cancel();
}

View File

@ -5,8 +5,9 @@ import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
/**
* Subcommand for info about permission levels.
@ -19,7 +20,10 @@ public class WebLevelCommand extends SubCommand {
private final Plan plugin;
public WebLevelCommand(Plan plugin) {
super("check", CommandType.CONSOLE, Permissions.MANAGE_WEB.getPerm(), "Info about permission levels.");
super("level",
CommandType.CONSOLE,
Permissions.MANAGE_WEB.getPerm(),
Locale.get(Msg.CMD_USG_WEB_LEVEL).toString());
this.plugin = plugin;
}
@ -27,14 +31,14 @@ public class WebLevelCommand extends SubCommand {
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
ColorScheme cs = plugin.getColorScheme();
String sCol = cs.getSecondaryColor();
String cmdBall = Phrase.CMD_BALL.parse();
String cmdBall = Locale.get(Msg.CMD_CONSTANT_LIST_BALL).parse();
String[] messages = new String[]{
Phrase.CMD_FOOTER.parse(),
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",
Phrase.CMD_FOOTER.parse()
Locale.get(Msg.CMD_CONSTANT_FOOTER).parse(),
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",
Locale.get(Msg.CMD_CONSTANT_FOOTER).parse()
};
sender.sendMessage(messages);
return true;

View File

@ -7,9 +7,10 @@ import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.comparators.WebUserComparator;
import java.util.List;
@ -39,14 +40,14 @@ public class WebListUsersCommand extends SubCommand {
String mCol = cs.getMainColor();
List<WebUser> users = plugin.getDB().getSecurityTable().getUsers();
users.sort(new WebUserComparator());
sender.sendMessage(Phrase.CMD_FOOTER.parse() + mCol + " WebUsers (" + users.size() + ")");
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).parse() + mCol + " WebUsers (" + users.size() + ")");
for (WebUser user : users) {
sender.sendMessage(" " + user.getPermLevel() + " : " + user.getName());
}
sender.sendMessage(Phrase.CMD_FOOTER.parse());
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).parse());
} catch (Exception ex) {
Log.toLog(this.getClass().getName(), ex);
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.parse());
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).parse());
} finally {
this.cancel();
}

View File

@ -7,6 +7,7 @@ import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@ -40,7 +41,7 @@ public class AnalysisData extends RawData {
private long refreshDate;
private String planVersion;
private String pluginsTabLayout;
private Map<String, String> additionalDataReplaceMap;
private Map<String, Serializable> additionalDataReplaceMap;
private String playersTable;
public AnalysisData(Map<String, Integer> commandUsage, List<TPS> tpsData) {
@ -118,11 +119,11 @@ public class AnalysisData extends RawData {
this.pluginsTabLayout = pluginsTabLayout;
}
public Map<String, String> getAdditionalDataReplaceMap() {
public Map<String, Serializable> getAdditionalDataReplaceMap() {
return additionalDataReplaceMap;
}
public void setAdditionalDataReplaceMap(Map<String, String> additionalDataReplaceMap) {
public void setAdditionalDataReplaceMap(Map<String, Serializable> additionalDataReplaceMap) {
this.additionalDataReplaceMap = additionalDataReplaceMap;
}
@ -142,9 +143,9 @@ public class AnalysisData extends RawData {
final List<RawData> parts = getAllParts();
parts.forEach(part -> {
try {
Benchmark.start("Analysis Phase: " + part.getClass().getSimpleName());
Benchmark.start(part.getClass().getSimpleName());
part.analyseData();
Benchmark.stop("Analysis Phase: " + part.getClass().getSimpleName());
Benchmark.stop("Analysis", part.getClass().getSimpleName());
if (part.isAnalysed()) {
addValues(part.getReplaceMap());
}

View File

@ -18,36 +18,29 @@ import java.util.stream.Collectors;
*/
public class UserData {
private final List<SessionData> sessions;
private int accessing;
private boolean clearAfterSave;
private UUID uuid;
private String name;
private Set<String> nicknames;
private String lastNick;
private String geolocation;
private Set<InetAddress> ips;
private int loginTimes;
private int timesKicked;
private boolean isOp;
private boolean isBanned;
private boolean isOnline;
private int mobKills;
private List<KillData> playerKills;
private int deaths;
private long registered;
private long lastPlayed;
private long playTime;
private GMTimes gmTimes;
private WorldTimes worldTimes;
private final List<SessionData> sessions;
/**
* Creates a new UserData object with given values and default values.
* <p>
@ -491,6 +484,14 @@ public class UserData {
return gmTimes;
}
public void setGmTimes(Map<String, Long> times) {
if (Verify.notNull(times)) {
for (Map.Entry<String, Long> entry : times.entrySet()) {
gmTimes.setTime(entry.getKey(), entry.getValue());
}
}
}
/**
* Set the GM Times object containing playtime in each gamemode.
*
@ -502,14 +503,6 @@ public class UserData {
}
}
public void setGmTimes(Map<String, Long> times) {
if (Verify.notNull(times)) {
for (Map.Entry<String, Long> entry : times.entrySet()) {
gmTimes.setTime(entry.getKey(), entry.getValue());
}
}
}
/**
* Is the user Operator?
*

View File

@ -30,4 +30,23 @@ public class WebUser {
return permLevel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WebUser webUser = (WebUser) o;
return permLevel == webUser.permLevel
&& user.equals(webUser.user)
&& saltedPassHash.equals(webUser.saltedPassHash);
}
@Override
public int hashCode() {
int result = user.hashCode();
result = 31 * result + saltedPassHash.hashCode();
result = 31 * result + permLevel;
return result;
}
}

View File

@ -5,6 +5,7 @@ import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
@ -155,8 +156,8 @@ public class HookHandler {
* @param uuid UUID of the player whose page is being inspected.
* @return Map: key|value - %placeholder%|value
*/
public Map<String, String> getAdditionalInspectReplaceRules(UUID uuid) {
Map<String, String> addReplace = new HashMap<>();
public Map<String, Serializable> getAdditionalInspectReplaceRules(UUID uuid) {
Map<String, Serializable> addReplace = new HashMap<>();
for (PluginData source : additionalDataSources) {
if (source.analysisOnly()) {
continue;
@ -166,8 +167,7 @@ public class HookHandler {
} catch (Exception e) {
addReplace.put(source.getPlaceholder(""), "Error occurred: " + e);
Log.error("PluginDataSource caused an exception: " + source.getSourcePlugin());
Log.toLog("PluginDataSource caused an exception: " + source.getSourcePlugin(), Log.getErrorsFilename());
Log.toLog(this.getClass().getName(), e);
Log.toLog("PluginDataSource " + source.getSourcePlugin(), e);
}
}
return addReplace;

View File

@ -31,7 +31,7 @@ public abstract class PluginData {
* <p>
* Second parameter of any super constructor.
*/
protected String placeholder;
protected final String placeholder;
/**
* Name of the plugin the data is coming from.
* <p>
@ -43,7 +43,7 @@ public abstract class PluginData {
* <p>
* First parameter of any super constructor.
*/
protected String sourcePlugin;
protected final String sourcePlugin;
/**
* Determines if the datapoint should only be used for the analysis page.
* <p>
@ -203,6 +203,10 @@ public abstract class PluginData {
*/
public abstract Serializable getValue(UUID uuid);
public Map<UUID, Serializable> getValues(Collection<UUID> uuids) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not overridden.");
}
/**
* Used to set the Font Awesome icon.
*
@ -269,6 +273,11 @@ public abstract class PluginData {
this.suffix = suffix;
}
public final boolean isBanData() {
return placeholder.contains("banned")
&& analysisTypes.contains(AnalysisType.BOOLEAN_TOTAL);
}
/**
* If a PluginData object has same placeholder, sourcePlugin and
* analysisTypes, it is considered equal.

View File

@ -5,7 +5,6 @@ import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.SessionData;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.ui.html.RecentPlayersButtonsCreator;
import main.java.com.djrapitops.plan.ui.html.graphs.PlayerActivityGraphCreator;
import main.java.com.djrapitops.plan.ui.html.graphs.PunchCardGraphCreator;
@ -104,8 +103,7 @@ public class ActivityPart extends RawData {
addValue("%activitycolors%", activityColors);
String activityLabels = "[" + HtmlUtils.separateWithQuotes(
Html.GRAPH_ACTIVE.parse(), Html.GRAPH_INACTIVE.parse(),
Html.GRAPH_UNKNOWN.parse(), Html.GRAPH_BANNED.parse()) + "]";
"Active", "Inactive", "Unknown", "Banned") + "]";
addValue("%labelsactivity%", activityLabels);
addValue("activitydata", Arrays.toString(counts));

View File

@ -3,7 +3,6 @@ package main.java.com.djrapitops.plan.data.cache;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.player.IPlayer;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.TPS;
@ -16,6 +15,8 @@ import main.java.com.djrapitops.plan.data.handling.info.HandlingInfo;
import main.java.com.djrapitops.plan.data.handling.info.LogoutInfo;
import main.java.com.djrapitops.plan.data.handling.info.ReloadInfo;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.NewPlayerCreator;
@ -81,7 +82,7 @@ public class DataCacheHandler extends SessionCache {
commandUse = new HashMap<>();
if (!getCommandUseFromDb()) {
Log.error(Phrase.DB_FAILURE_DISABLE + "");
Log.error(Locale.get(Msg.ENABLE_DB_FAIL_DISABLE_INFO).toString());
plugin.disablePlugin();
return;
}
@ -144,6 +145,7 @@ public class DataCacheHandler extends SessionCache {
}
try {
periodicTaskIsSaving = true;
Log.debug("Database", "Periodic Cache Save");
handler.saveHandlerDataToCache();
handler.saveCachedUserData();
if (timesSaved % clearAfterXsaves == 0) {
@ -158,7 +160,7 @@ public class DataCacheHandler extends SessionCache {
periodicTaskIsSaving = false;
}
}
}).runTaskTimerAsynchronously(60 * 20 * minutes, 60 * 20 * minutes);
}).runTaskTimerAsynchronously(60L * 20L * minutes, 60L * 20L * minutes);
}
/**
@ -197,7 +199,7 @@ public class DataCacheHandler extends SessionCache {
public void cache(UserData data) {
data.setOnline(true);
dataCache.put(data.getUuid(), data);
Log.debug(Phrase.CACHE_ADD.parse(data.getUuid().toString()));
Log.debug("Added " + data.getUuid().toString() + " to Cache.");
}
/**
@ -340,6 +342,7 @@ public class DataCacheHandler extends SessionCache {
return;
}
try {
Log.debug("Database", "Periodic TPS Save");
db.getTpsTable().saveTPSData(averages);
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
@ -413,7 +416,7 @@ public class DataCacheHandler extends SessionCache {
}
} else {
dataCache.remove(uuid);
Log.debug(Phrase.CACHE_REMOVE.parse(uuid.toString()));
Log.debug("Cleared " + uuid.toString() + " from Cache.");
}
}

View File

@ -23,6 +23,9 @@ import java.util.Map;
*/
public class GeolocationCacheHandler {
private static final Cache<String, String> geolocationCache = CacheBuilder.newBuilder()
.build();
/**
* Constructor used to hide the public constructor
*/
@ -30,9 +33,6 @@ public class GeolocationCacheHandler {
throw new IllegalStateException("Utility class");
}
private static final Cache<String, String> geolocationCache = CacheBuilder.newBuilder()
.build();
/**
* Retrieves the country in full length (e.g. United States) from the IP Address.
* <p>

View File

@ -5,10 +5,11 @@ import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.ui.webserver.response.InspectPageResponse;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.ExportUtility;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.util.*;
@ -48,10 +49,11 @@ public class InspectCacheHandler {
cache.put(uuid, new UserData(data));
cacheTimes.put(uuid, MiscUtils.getTime());
PageCacheHandler.cachePage("inspectPage: " + uuid.toString(), () -> new InspectPageResponse(Plan.getInstance().getUiServer().getDataReqHandler(), uuid));
try {
ExportUtility.writeInspectHtml(data, ExportUtility.getPlayersFolder(ExportUtility.getFolder()));
} catch (IOException ex) {
Log.toLog(this.getClass().getName(), ex);
ExportUtility.writeInspectHtml(data, ExportUtility.getPlayersFolder(ExportUtility.getFolder()), HtmlUtils.getStringFromResource("player.html"));
} catch (FileNotFoundException e) {
Log.toLog(this.getClass().getName(), e);
}
};

View File

@ -18,6 +18,9 @@ import main.java.com.djrapitops.plan.ui.webserver.response.Response;
*/
public class PageCacheHandler {
private static final Cache<String, Response> pageCache = CacheBuilder.newBuilder()
.build();
/**
* Constructor used to hide the public constructor
*/
@ -25,9 +28,6 @@ public class PageCacheHandler {
throw new IllegalStateException("Utility class");
}
private static final Cache<String, Response> pageCache = CacheBuilder.newBuilder()
.build();
/**
* Loads the page from the page cache.
* <p>

View File

@ -1,9 +1,10 @@
package main.java.com.djrapitops.plan.data.cache.queue;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.cache.DataCacheHandler;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import java.util.Collection;
import java.util.Objects;
@ -55,7 +56,7 @@ public class DataCacheClearQueue extends Queue<UUID> {
try {
queue.addAll(uuids);
} catch (IllegalStateException e) {
Log.error(Phrase.ERROR_TOO_SMALL_QUEUE.parse("Clear Queue", Settings.PROCESS_CLEAR_LIMIT.getNumber() + ""));
Log.error(Locale.get(Msg.RUN_WARN_QUEUE_SIZE).parse("Clear Queue", Settings.PROCESS_CLEAR_LIMIT.getNumber()));
}
}
}

View File

@ -1,11 +1,12 @@
package main.java.com.djrapitops.plan.data.cache.queue;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.cache.DBCallableProcessor;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import java.sql.SQLException;
import java.util.*;
@ -45,7 +46,7 @@ public class DataCacheGetQueue extends Queue<Map<UUID, List<DBCallableProcessor>
map.put(uuid, Arrays.asList(processors));
queue.add(map);
} catch (IllegalStateException e) {
Log.error(Phrase.ERROR_TOO_SMALL_QUEUE.parse("Get Queue", String.valueOf(Settings.PROCESS_GET_LIMIT.getNumber())));
Log.error(Locale.get(Msg.RUN_WARN_QUEUE_SIZE).parse("Get Queue", Settings.PROCESS_GET_LIMIT.getNumber()));
}
}

View File

@ -1,12 +1,13 @@
package main.java.com.djrapitops.plan.data.cache.queue;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.cache.DataCacheHandler;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import java.sql.SQLException;
import java.util.Collection;
@ -45,7 +46,7 @@ public class DataCacheSaveQueue extends Queue<UserData> {
try {
queue.add(data);
} catch (IllegalStateException e) {
Log.error(Phrase.ERROR_TOO_SMALL_QUEUE.parse("Save Queue", Settings.PROCESS_SAVE_LIMIT.getNumber() + ""));
Log.error(Locale.get(Msg.RUN_WARN_QUEUE_SIZE).parse("Save Queue", Settings.PROCESS_SAVE_LIMIT.getNumber()));
}
}
@ -59,7 +60,7 @@ public class DataCacheSaveQueue extends Queue<UserData> {
try {
queue.addAll(data);
} catch (IllegalStateException e) {
Log.error(Phrase.ERROR_TOO_SMALL_QUEUE.parse("Save Queue", Settings.PROCESS_SAVE_LIMIT.getNumber() + ""));
Log.error(Locale.get(Msg.RUN_WARN_QUEUE_SIZE).parse("Save Queue", Settings.PROCESS_SAVE_LIMIT.getNumber()));
}
}
@ -73,7 +74,7 @@ public class DataCacheSaveQueue extends Queue<UserData> {
try {
queue.add(data);
} catch (IllegalStateException e) {
Log.error(Phrase.ERROR_TOO_SMALL_QUEUE.parse("Save Queue", Settings.PROCESS_SAVE_LIMIT.getNumber() + ""));
Log.error(Locale.get(Msg.RUN_WARN_QUEUE_SIZE).parse("Save Queue", Settings.PROCESS_SAVE_LIMIT.getNumber()));
}
}
@ -117,8 +118,7 @@ class SaveConsumer extends Consumer<UserData> {
db.saveUserData(data);
data.stopAccessing();
Log.debug(uuid + ": Saved!");
if (data.shouldClearAfterSave()
&& handler != null) {
if (data.shouldClearAfterSave()) {
handler.getClearTask().scheduleForClear(uuid);
}
} catch (SQLException ex) {

View File

@ -11,6 +11,13 @@ import main.java.com.djrapitops.plan.data.UserData;
*/
public class LogoutHandling {
/**
* Constructor used to hide the public constructor
*/
private LogoutHandling() {
throw new IllegalStateException("Utility class");
}
/**
* Processes the information of the Event and changes UserData object
* accordingly.

View File

@ -6,6 +6,13 @@ import main.java.com.djrapitops.plan.data.time.WorldTimes;
public class PlaytimeHandling {
/**
* Constructor used to hide the public constructor
*/
private PlaytimeHandling() {
throw new IllegalStateException("Utility class");
}
public static void processPlaytimeDependentInfo(UserData data, long time, String gamemode, String worldName) {
long diff = time - data.getLastPlayed();
long playTime = data.getPlayTime() + diff;

View File

@ -16,6 +16,13 @@ import static org.bukkit.Bukkit.getPluginManager;
*/
public class ImportUtils {
/**
* Constructor used to hide the public constructor
*/
private ImportUtils() {
throw new IllegalStateException("Utility class");
}
/**
* Checks if a plugin is enabled.
*

View File

@ -130,7 +130,7 @@ public abstract class Importer {
handler.addToPool(importData(uuid, args));
}
plan.processStatus().finishExecution(processName);
processStatus.finishExecution(processName);
} finally {
plan.getAnalysisCache().enableAnalysis();
}

View File

@ -42,9 +42,13 @@ public class PlanGamemodeChangeListener implements Listener {
if (event.isCancelled()) {
return;
}
Player p = event.getPlayer();
UUID uuid = p.getUniqueId();
long time = MiscUtils.getTime();
handler.addToPool(new PlaytimeDependentInfo(uuid, InfoType.GM, time, event.getNewGameMode().name(), p.getWorld().getName()));
String gameMode = event.getNewGameMode().name();
String worldName = p.getWorld().getName();
handler.addToPool(new PlaytimeDependentInfo(uuid, InfoType.GM, time, gameMode, worldName));
}
}

View File

@ -108,6 +108,7 @@ public class PlanPlayerListener implements Listener {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
handler.endSession(uuid);
Log.debug(uuid + ": PlayerQuitEvent");
long time = MiscUtils.getTime();
boolean banned = player.isBanned();
@ -116,6 +117,7 @@ public class PlanPlayerListener implements Listener {
handler.addToPool(new LogoutInfo(uuid, time, banned, gm.name(), handler.getSession(uuid), worldName));
handler.saveCachedData(uuid);
Log.debug(uuid + ": PlayerQuitEvent_END");
}
@ -131,10 +133,13 @@ public class PlanPlayerListener implements Listener {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
handler.endSession(uuid);
Log.debug(uuid + ": PlayerKickEvent");
long time = MiscUtils.getTime();
boolean banned = player.isBanned();
Gamemode gm = Gamemode.wrap(player.getGameMode());
@ -143,6 +148,7 @@ public class PlanPlayerListener implements Listener {
handler.addToPool(new LogoutInfo(uuid, time, banned, gm.name(), handler.getSession(uuid), worldName));
handler.addToPool(new KickInfo(uuid));
handler.saveCachedData(uuid);
Log.debug(uuid + ": PlayerKickEvent_END");
}
}

View File

@ -23,13 +23,17 @@ public class PlanWorldChangeListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
public void onWorldChange(PlayerChangedWorldEvent event) {
Player p = event.getPlayer();
String previousWorld = event.getFrom().getName();
String worldName = p.getWorld().getName();
if (previousWorld.equals(worldName)) {
return;
}
UUID uuid = p.getUniqueId();
String gameMode = p.getGameMode().name();
long time = MiscUtils.getTime();
handler.addToPool(new PlaytimeDependentInfo(uuid, InfoType.WORLD, time, p.getGameMode().name(), p.getWorld().getName()));
handler.addToPool(new PlaytimeDependentInfo(uuid, InfoType.WORLD, time, gameMode, worldName));
}
}

View File

@ -70,9 +70,9 @@ public abstract class TimeKeeper {
*/
public void changeState(String newState, long playTime) throws IllegalArgumentException, IllegalStateException {
Verify.nullCheck(newState);
if (playTime < lastStateChange) {
throw new IllegalStateException("Given Playtime is lower than last status change time: " + playTime + " / " + lastStateChange);
}
// if (playTime < lastStateChange) {
// throw new IllegalStateException("Given Playtime is lower than last status change time: " + playTime + " / " + lastStateChange);
// }
if (state == null) {
state = newState;
}
@ -81,7 +81,7 @@ public abstract class TimeKeeper {
currentTime = 0L;
}
long diff = playTime - lastStateChange;
times.put(state, currentTime + diff);
times.put(state, currentTime + Math.abs(diff));
state = newState;
lastStateChange = playTime;
}
@ -109,30 +109,30 @@ public abstract class TimeKeeper {
return times.values().stream().mapToLong(i -> i).sum();
}
public void setTimes(Map<String, Long> times) {
this.times = times;
}
public Map<String, Long> getTimes() {
return times;
}
public void setState(String state) {
this.state = state;
}
public void setLastStateChange(long lastStateChange) {
this.lastStateChange = lastStateChange;
public void setTimes(Map<String, Long> times) {
this.times = times;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public long getLastStateChange() {
return lastStateChange;
}
public void setLastStateChange(long lastStateChange) {
this.lastStateChange = lastStateChange;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
@ -155,7 +155,7 @@ public abstract class TimeKeeper {
@Override
public String toString() {
return getClass().getSimpleName()+"{" +
return getClass().getSimpleName() + "{" +
"times=" + times +
", state='" + state + '\'' +
", lastStateChange=" + lastStateChange +

View File

@ -19,6 +19,8 @@ import java.util.Map.Entry;
*/
public class DBUtils {
private static final int BATCH_SIZE = 10192;
/**
* Constructor used to hide the public constructor
*/
@ -26,8 +28,6 @@ public class DBUtils {
throw new IllegalStateException("Utility class");
}
private static final int BATCH_SIZE = 2048;
/**
* Splits a collection of objects into lists with the size defined by
* BATCH_SIZE.

View File

@ -1,8 +1,9 @@
package main.java.com.djrapitops.plan.database.databases;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import org.bukkit.configuration.file.FileConfiguration;
import java.sql.Connection;
@ -41,7 +42,7 @@ public class MySQLDB extends SQLDB {
return DriverManager.getConnection(url, config.getString("mysql.user"), config.getString("mysql.password"));
} catch (ClassNotFoundException | SQLException e) {
Log.error(Phrase.DB_CONNECTION_FAIL.parse(getConfigName(), e.getMessage()));
Log.error(Locale.get(Msg.ENABLE_FAIL_DB).parse(getConfigName(), e.getMessage()));
return null;
}
}

View File

@ -12,6 +12,7 @@ import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.database.tables.*;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import java.net.InetAddress;
import java.sql.Connection;
@ -30,6 +31,7 @@ import java.util.stream.Collectors;
public abstract class SQLDB extends Database {
private final boolean supportsModification;
private final boolean usingMySQL;
private Connection connection;
@ -40,7 +42,7 @@ public abstract class SQLDB extends Database {
public SQLDB(Plan plugin, boolean supportsModification) {
super(plugin);
this.supportsModification = supportsModification;
boolean usingMySQL = getName().equals("MySQL");
usingMySQL = getName().equals("MySQL");
usersTable = new UsersTable(this, usingMySQL);
gmTimesTable = new GMTimesTable(this, usingMySQL);
@ -60,10 +62,9 @@ public abstract class SQLDB extends Database {
}
/**
* @throws IllegalArgumentException
* @throws IllegalStateException
* Starts repeating Async task that maintains the Database connection.
*/
public void startConnectionPingTask() throws IllegalArgumentException, IllegalStateException {
public void startConnectionPingTask() {
// Maintains Connection.
plugin.getRunnableFactory().createNew(new AbsRunnable("DBConnectionPingTask " + getName()) {
@Override
@ -77,26 +78,28 @@ public abstract class SQLDB extends Database {
} catch (SQLException e) {
connection = getNewConnection();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
Log.error("Error at closing statement");
}
}
MiscUtils.close(statement);
}
}
}).runTaskTimerAsynchronously(60 * 20, 60 * 20);
}).runTaskTimerAsynchronously(60L * 20L, 60L * 20L);
}
/**
* @return
* Initializes the Database.
* <p>
* All tables exist in the database after call to this.
* Updates Schema to latest version.
* Converts Unsaved Bukkit player files to database data.
* Cleans the database.
*
* @return Was the Initialization successful.
*/
@Override
public boolean init() {
super.init();
setStatus("Init");
Benchmark.start("Database: Init " + getConfigName());
String benchName = "Init " + getConfigName();
Benchmark.start(benchName);
try {
if (!checkConnection()) {
return false;
@ -108,12 +111,18 @@ public abstract class SQLDB extends Database {
Log.toLog(this.getClass().getName(), e);
return false;
} finally {
Benchmark.stop("Database: Init " + getConfigName());
Benchmark.stop("Database", benchName);
Log.logDebug("Database");
}
}
/**
* @return @throws SQLException
* Ensures connection functions correctly and all tables exist.
* <p>
* Updates to latest schema.
*
* @return Is the connection usable?
* @throws SQLException
*/
public boolean checkConnection() throws SQLException {
if (connection == null || connection.isClosed()) {
@ -140,7 +149,7 @@ public abstract class SQLDB extends Database {
setVersion(8);
}
Benchmark.start("Database: Create tables");
Benchmark.start("DCreate tables");
for (Table table : getAllTables()) {
if (!table.createTable()) {
@ -153,8 +162,7 @@ public abstract class SQLDB extends Database {
Log.error("Failed to create table: " + securityTable.getTableName());
return false;
}
Benchmark.stop("Database: Create tables");
Benchmark.stop("Database", "Create tables");
if (!newDatabase && getVersion() < 8) {
setVersion(8);
@ -171,11 +179,12 @@ public abstract class SQLDB extends Database {
@Override
public void run() {
try {
Benchmark.start("Database: Convert Bukkitdata to DB data");
Benchmark.start("Convert BukkitData to DB data");
Log.debug("Database", "Bukkit Data Conversion");
Set<UUID> uuids = usersTable.getSavedUUIDs();
uuids.removeAll(usersTable.getContainsBukkitData(uuids));
if (uuids.isEmpty()) {
Log.debug("No conversion necessary.");
Log.debug("Database", "No conversion necessary.");
return;
}
setStatus("Bukkit Data Conversion");
@ -186,7 +195,7 @@ public abstract class SQLDB extends Database {
plugin.getServer().getScheduler().cancelTask(id);
}
saveMultipleUserData(getUserDataForUUIDS(uuids));
Log.info("Conversion complete, took: " + FormatUtils.formatTimeAmount(Benchmark.stop("Database: Convert Bukkitdata to DB data")) + " ms");
Log.info("Conversion complete, took: " + FormatUtils.formatTimeAmount(Benchmark.stop("Database", "Convert BukkitData to DB data")) + " ms");
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
} finally {
@ -232,6 +241,7 @@ public abstract class SQLDB extends Database {
if (connection != null) {
connection.close();
}
Log.logDebug("Database"); // Log remaining Debug info if present
setStatus("Closed");
}
@ -250,6 +260,7 @@ public abstract class SQLDB extends Database {
@Override
public void setVersion(int version) throws SQLException {
versionTable.setVersion(version);
commit();
}
/**
@ -284,8 +295,8 @@ public abstract class SQLDB extends Database {
}
try {
setStatus("Remove account " + uuid);
Benchmark.start("Database: Remove Account");
Log.debug("Removing Account: " + uuid);
Benchmark.start("Remove Account");
Log.debug("Database", "Removing Account: " + uuid);
try {
checkConnection();
} catch (Exception e) {
@ -293,7 +304,7 @@ public abstract class SQLDB extends Database {
return false;
}
int userId = usersTable.getUserId(uuid);
return userId != -1
boolean success = userId != -1
&& locationsTable.removeUserLocations(userId)
&& ipsTable.removeUserIps(userId)
&& nicknamesTable.removeUserNicknames(userId)
@ -302,8 +313,14 @@ public abstract class SQLDB extends Database {
&& killsTable.removeUserKillsAndVictims(userId)
&& worldTimesTable.removeUserWorldTimes(userId)
&& usersTable.removeUser(uuid);
if (success) {
commit();
} else {
rollback();
}
return success;
} finally {
Benchmark.stop("Database: Remove Account");
Benchmark.stop("Database", "Remove Account");
setAvailable();
}
}
@ -315,7 +332,7 @@ public abstract class SQLDB extends Database {
*/
@Override
public void giveUserDataToProcessors(UUID uuid, Collection<DBCallableProcessor> processors) throws SQLException {
Benchmark.start("Database: Give userdata to processors");
Benchmark.start("Give userdata to processors");
try {
checkConnection();
} catch (Exception e) {
@ -354,7 +371,7 @@ public abstract class SQLDB extends Database {
data.addSessions(sessions);
data.setPlayerKills(killsTable.getPlayerKills(userId));
processors.forEach(processor -> processor.process(data));
Benchmark.stop("Database: Give userdata to processors");
Benchmark.stop("Database", "Give userdata to processors");
setAvailable();
}
@ -369,30 +386,40 @@ public abstract class SQLDB extends Database {
return new ArrayList<>();
}
setStatus("Get userdata (multiple) for: " + uuidsCol.size());
Benchmark.start("Database: Get UserData for " + uuidsCol.size());
Benchmark.start("Get UserData for " + uuidsCol.size());
Map<UUID, Integer> userIds = usersTable.getAllUserIds();
Set<UUID> remove = uuidsCol.stream()
.filter(uuid -> !userIds.containsKey(uuid))
.collect(Collectors.toSet());
List<UUID> uuids = new ArrayList<>(uuidsCol);
Log.debug("Data not found for: " + remove.size());
Log.debug("Database", "Data not found for: " + remove.size());
uuids.removeAll(remove);
Benchmark.start("Database: Create UserData objects for " + userIds.size());
Benchmark.start("Create UserData objects for " + userIds.size());
List<UserData> data = usersTable.getUserData(new ArrayList<>(uuids));
Benchmark.stop("Database: Create UserData objects for " + userIds.size());
Benchmark.stop("Database", "Create UserData objects for " + userIds.size());
if (data.isEmpty()) {
return data;
}
Map<Integer, UUID> idUuidRel = userIds.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
List<Integer> ids = userIds.entrySet().stream().filter(e -> uuids.contains(e.getKey())).map(Map.Entry::getValue).collect(Collectors.toList());
Log.debug("Ids: " + ids.size());
Log.debug("Database", "Using IDs: " + ids.size());
Map<Integer, List<String>> nicknames = nicknamesTable.getNicknames(ids);
Map<Integer, Set<InetAddress>> ipList = ipsTable.getIPList(ids);
Map<Integer, List<KillData>> playerKills = killsTable.getPlayerKills(ids, idUuidRel);
Map<Integer, List<SessionData>> sessionData = sessionsTable.getSessionData(ids);
Map<Integer, Map<String, Long>> gmTimes = gmTimesTable.getGMTimes(ids);
Map<Integer, Map<String, Long>> worldTimes = worldTimesTable.getWorldTimes(ids);
Log.debug("Sizes: UUID:" + uuids.size() + " DATA:" + data.size() + " ID:" + userIds.size() + " N:" + nicknames.size() + " I:" + ipList.size() + " K:" + playerKills.size() + " S:" + sessionData.size());
Log.debug("Database", "Data found for:");
Log.debug("Database", " UUIDs: " + uuids.size());
Log.debug("Database", " IDs: " + userIds.size());
Log.debug("Database", " UserData: " + data.size());
Log.debug("Database", " Nicknames: " + nicknames.size());
Log.debug("Database", " IPs: " + ipList.size());
Log.debug("Database", " Kills: " + playerKills.size());
Log.debug("Database", " Sessions: " + sessionData.size());
Log.debug("Database", " GM Times: " + gmTimes.size());
Log.debug("Database", " World Times: " + worldTimes.size());
for (UserData uData : data) {
UUID uuid = uData.getUuid();
@ -413,7 +440,7 @@ public abstract class SQLDB extends Database {
}
}
Benchmark.stop("Database: Get UserData for " + uuidsCol.size());
Benchmark.stop("Database", "Get UserData for " + uuidsCol.size());
setAvailable();
return data;
}
@ -428,7 +455,7 @@ public abstract class SQLDB extends Database {
return;
}
Benchmark.start("Database: Save multiple Userdata");
Benchmark.start("Save multiple Userdata");
data.removeIf(Objects::isNull);
checkConnection();
@ -466,7 +493,7 @@ public abstract class SQLDB extends Database {
Integer id = userIds.get(uuid);
if (id == -1) {
Log.debug("User not seen before, saving last: " + uuid);
Log.debug("Database", "User not seen before, saving last: " + uuid);
continue;
}
@ -488,11 +515,12 @@ public abstract class SQLDB extends Database {
gmTimesTable.saveGMTimes(gmTimes);
worldTable.saveWorlds(worldNames);
worldTimesTable.saveWorldTimes(worldTimes);
commit();
userDatas.values().stream()
.filter(Objects::nonNull)
.filter(UserData::isAccessed)
.forEach(UserData::stopAccessing);
Benchmark.stop("Database: Save multiple Userdata");
Benchmark.stop("Database", "Save multiple Userdata");
setAvailable();
}
@ -511,7 +539,8 @@ public abstract class SQLDB extends Database {
}
setStatus("Save userdata: " + uuid);
checkConnection();
Log.debug("DB_Save: " + data);
Log.debug("Database", "DB_Save:");
Log.debug("Database", data.toString());
data.access();
usersTable.saveUserDataInformation(data);
int userId = usersTable.getUserId(uuid.toString());
@ -523,6 +552,7 @@ public abstract class SQLDB extends Database {
worldTable.saveWorlds(new HashSet<>(data.getWorldTimes().getTimes().keySet()));
worldTimesTable.saveWorldTimes(userId, data.getWorldTimes().getTimes());
data.stopAccessing();
commit();
setAvailable();
}
@ -547,14 +577,25 @@ public abstract class SQLDB extends Database {
*/
@Override
public boolean removeAllData() {
boolean success = true;
setStatus("Clearing all data");
for (Table table : getAllTablesInRemoveOrder()) {
if (!table.removeAllData()) {
return false;
try {
for (Table table : getAllTablesInRemoveOrder()) {
if (!table.removeAllData()) {
success = false;
break;
}
}
if (success) {
commit();
} else {
rollback();
}
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
setAvailable();
return true;
return success;
}
/**
@ -575,7 +616,30 @@ public abstract class SQLDB extends Database {
plugin.processStatus().setStatus("DB-" + getName(), status);
}
private void setAvailable() {
public void setAvailable() {
setStatus("Running");
Log.logDebug("Database");
}
/**
* Commits changes to the .db file when using SQLite Database.
* <p>
* MySQL has Auto Commit enabled.
*/
public void commit() throws SQLException {
if (!usingMySQL) {
getConnection().commit();
}
}
/**
* Reverts transaction when using SQLite Database.
* <p>
* MySQL has Auto Commit enabled.
*/
public void rollback() throws SQLException {
if (!usingMySQL) {
connection.rollback();
}
}
}

View File

@ -50,7 +50,9 @@ public class SQLiteDB extends SQLDB {
try {
Class.forName("org.sqlite.JDBC");
return DriverManager.getConnection("jdbc:sqlite:" + new File(plugin.getDataFolder(), dbName + ".db").getAbsolutePath());
Connection connection = DriverManager.getConnection("jdbc:sqlite:" + new File(plugin.getDataFolder(), dbName + ".db").getAbsolutePath());
connection.setAutoCommit(false);
return connection;
} catch (ClassNotFoundException | SQLException e) {
return null;
}

View File

@ -50,7 +50,7 @@ public class CommandUseTable extends Table {
* @return @throws SQLException
*/
public Map<String, Integer> getCommandUse() throws SQLException {
Benchmark.start("Database: Get CommandUse");
Benchmark.start("Get CommandUse");
Map<String, Integer> commandUse = new HashMap<>();
PreparedStatement statement = null;
ResultSet set = null;
@ -70,7 +70,7 @@ public class CommandUseTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get CommandUse");
Benchmark.stop("Database", "Get CommandUse");
}
}
@ -84,7 +84,7 @@ public class CommandUseTable extends Table {
return;
}
Benchmark.start("Database: Save Commanduse");
Benchmark.start("Save Commanduse");
Map<String, Integer> newData = new HashMap<>(data);
Map<String, Integer> saved = getCommandUse();
newData.keySet().removeAll(saved.keySet());
@ -105,7 +105,9 @@ public class CommandUseTable extends Table {
}
updateCommands(updateData);
Benchmark.stop("Database: Save Commanduse");
commit();
Benchmark.stop("Database", "Save Commanduse");
db.setAvailable();
}
private void updateCommands(Map<String, Integer> data) throws SQLException {

View File

@ -201,7 +201,7 @@ public class GMTimesTable extends Table {
return;
}
Benchmark.start("Database: Save GMTimes");
Benchmark.start("Save GMTimes");
Set<Integer> savedIDs = getSavedIDs();
@ -220,7 +220,7 @@ public class GMTimesTable extends Table {
List<List<Container<GMTimes>>> batches = DBUtils.splitIntoBatchesWithID(gmTimes);
batches.stream().forEach(batch -> {
batches.forEach(batch -> {
try {
saveGMTimesBatch(batch);
} catch (SQLException e) {
@ -231,7 +231,7 @@ public class GMTimesTable extends Table {
gamemodeTimes.keySet().removeAll(savedIDs);
addNewGMTimesRows(gamemodeTimes);
Benchmark.stop("Database: Save GMTimes");
Benchmark.stop("Database", "Save GMTimes");
}
private void saveGMTimesBatch(List<Container<GMTimes>> batch) throws SQLException {
@ -240,7 +240,7 @@ public class GMTimesTable extends Table {
}
int batchSize = batch.size();
Log.debug("Preparing insertion of GM Times... Batch Size: " + batchSize);
Log.debug("Database", "Preparing update of GM Times - Batch Size: " + batchSize);
String[] gms = getGMKeyArray();
Set<Integer> savedIDs = getSavedIDs();
@ -274,19 +274,19 @@ public class GMTimesTable extends Table {
statement.addBatch();
}
Log.debug("Executing GM Times batch: " + batchSize);
Log.debug("Database", "Executing GM Times batch: " + batchSize);
statement.executeBatch();
} finally {
close(statement);
}
}
private void addNewGMTimesRows(Map<Integer, Map<String, Long>> gamemodeTimes) throws SQLException {
private void addNewGMTimesRows(Map<Integer, Map<String, Long>> gamemodeTimes) {
if (Verify.isEmpty(gamemodeTimes)) {
return;
}
Benchmark.start("Database: Add GMTimes Rows");
Benchmark.start("Add GMTimes Rows");
Map<Integer, GMTimes> gmTimes = new HashMap<>();
@ -298,15 +298,15 @@ public class GMTimesTable extends Table {
List<List<Container<GMTimes>>> batches = DBUtils.splitIntoBatchesWithID(gmTimes);
batches.stream().forEach(batch -> {
batches.forEach(batch -> {
try {
addNewGMTimesBatch(batch);
} catch (SQLException e) {
e.printStackTrace();
Log.toLog("GMTimesTable.addNewGMTimesRows", e);
}
});
Benchmark.stop("Database: Add GMTimes Rows");
Benchmark.stop("Database", "Add GMTimes Rows");
}
private void addNewGMTimesBatch(List<Container<GMTimes>> batch) throws SQLException {
@ -315,7 +315,7 @@ public class GMTimesTable extends Table {
}
int batchSize = batch.size();
Log.debug("Preparing insertion of GM Times... Batch Size: " + batchSize);
Log.debug("Database", "Preparing insertion of GM Times - Batch Size: " + batchSize);
String[] gms = getGMKeyArray();
@ -343,7 +343,7 @@ public class GMTimesTable extends Table {
statement.addBatch();
}
Log.debug("Executing GM Times batch: " + batchSize);
Log.debug("Database", "Executing GM Times batch: " + batchSize);
statement.executeBatch();
} finally {
close(statement);

View File

@ -74,7 +74,7 @@ public class IPsTable extends Table {
* @throws SQLException
*/
public List<InetAddress> getIPAddresses(int userId) throws SQLException {
Benchmark.start("Database: Get Ips");
Benchmark.start("Get Ips");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -95,7 +95,7 @@ public class IPsTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get Ips");
Benchmark.stop("Database", "Get Ips");
}
}
@ -109,7 +109,7 @@ public class IPsTable extends Table {
return;
}
Benchmark.start("Database: Save Ips");
Benchmark.start("Save Ips");
ips.removeAll(getIPAddresses(userId));
if (ips.isEmpty()) {
@ -141,7 +141,7 @@ public class IPsTable extends Table {
}
} finally {
close(statement);
Benchmark.stop("Database: Save Ips");
Benchmark.stop("Database", "Save Ips");
}
}
@ -155,7 +155,7 @@ public class IPsTable extends Table {
return new HashMap<>();
}
Benchmark.start("Database: Get Ips Multiple");
Benchmark.start("Get Ips Multiple");
PreparedStatement statement = null;
ResultSet set = null;
@ -188,7 +188,7 @@ public class IPsTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get Ips Multiple");
Benchmark.stop("Database", "Get Ips Multiple");
}
}
@ -200,7 +200,7 @@ public class IPsTable extends Table {
if (ips == null || ips.isEmpty()) {
return;
}
Benchmark.start("Database: Save Ips Multiple");
Benchmark.start("Save Ips Multiple");
Map<Integer, Set<InetAddress>> saved = getIPList(ips.keySet());
PreparedStatement statement = null;
try {
@ -209,7 +209,7 @@ public class IPsTable extends Table {
+ columnIP
+ ") VALUES (?, ?)");
boolean commitRequired = false;
int i = 0;
int batchSize = 0;
for (Map.Entry<Integer, Set<InetAddress>> entrySet : ips.entrySet()) {
Integer id = entrySet.getKey();
Set<InetAddress> ipAddresses = entrySet.getValue();
@ -233,17 +233,17 @@ public class IPsTable extends Table {
statement.setString(2, ip.getHostAddress());
statement.addBatch();
commitRequired = true;
i++;
batchSize++;
}
}
if (commitRequired) {
Log.debug("Executing ips batch: " + i);
Log.debug("Database", "Executing ips batch: " + batchSize);
statement.executeBatch();
}
} finally {
close(statement);
Benchmark.stop("Database: Save Ips Multiple");
Benchmark.stop("Database", "Save Ips Multiple");
}
}
}

View File

@ -82,7 +82,7 @@ public class KillsTable extends Table {
* @throws SQLException
*/
public List<KillData> getPlayerKills(int userId) throws SQLException {
Benchmark.start("Database: Get Kills");
Benchmark.start("Get Kills");
UsersTable usersTable = db.getUsersTable();
PreparedStatement statement = null;
ResultSet set = null;
@ -100,7 +100,7 @@ public class KillsTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get Kills");
Benchmark.stop("Database", "Get Kills");
}
}
@ -113,7 +113,7 @@ public class KillsTable extends Table {
if (kills == null) {
return;
}
Benchmark.start("Database: Save Kills");
Benchmark.start("Save Kills");
kills.removeAll(getPlayerKills(userId));
if (kills.isEmpty()) {
return;
@ -154,7 +154,7 @@ public class KillsTable extends Table {
}
} finally {
close(statement);
Benchmark.stop("Database: Save Kills");
Benchmark.stop("Database", "Save Kills");
}
}
@ -168,7 +168,7 @@ public class KillsTable extends Table {
if (ids == null || ids.isEmpty()) {
return new HashMap<>();
}
Benchmark.start("Database: Get Kills multiple");
Benchmark.start("Get Kills multiple");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -191,7 +191,7 @@ public class KillsTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get Kills multiple");
Benchmark.stop("Database", "Get Kills multiple");
}
}
@ -205,7 +205,7 @@ public class KillsTable extends Table {
return;
}
Benchmark.start("Database: Save Kills multiple");
Benchmark.start("Save Kills multiple");
Map<Integer, List<KillData>> saved = getPlayerKills(kills.keySet(), uuids);
PreparedStatement statement = null;
@ -258,13 +258,13 @@ public class KillsTable extends Table {
}
if (commitRequired) {
Log.debug("Executing kills batch: " + i);
Log.debug("Database", "Executing kills batch: " + i);
statement.executeBatch();
}
}
} finally {
close(statement);
Benchmark.stop("Database: Save Kills multiple");
Benchmark.stop("Database", "Save Kills multiple");
}
}
}

View File

@ -82,7 +82,7 @@ public class NicknamesTable extends Table {
* @throws SQLException
*/
public List<String> getNicknames(int userId) throws SQLException {
Benchmark.start("Database: Get Nicknames");
Benchmark.start("Get Nicknames");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -109,7 +109,7 @@ public class NicknamesTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get Nicknames");
Benchmark.stop("Database", "Get Nicknames");
}
}
@ -123,7 +123,7 @@ public class NicknamesTable extends Table {
if (names == null || names.isEmpty()) {
return;
}
Benchmark.start("Database: Save Nicknames");
Benchmark.start("Save Nicknames");
names.removeAll(getNicknames(userId));
if (names.isEmpty()) {
return;
@ -146,13 +146,13 @@ public class NicknamesTable extends Table {
i++;
}
if (commitRequired) {
Log.debug("Executing nicknames batch: " + i);
Log.debug("Database", "Executing nicknames batch: " + i);
statement.executeBatch();
}
} finally {
close(statement);
Benchmark.stop("Database: Save Nicknames");
Benchmark.stop("Database", "Save Nicknames");
}
}
@ -165,7 +165,7 @@ public class NicknamesTable extends Table {
if (ids == null || ids.isEmpty()) {
return new HashMap<>();
}
Benchmark.start("Database: Get Nicknames Multiple");
Benchmark.start("Get Nicknames Multiple");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -208,7 +208,7 @@ public class NicknamesTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get Nicknames Multiple");
Benchmark.stop("Database", "Get Nicknames Multiple");
}
}
@ -222,7 +222,7 @@ public class NicknamesTable extends Table {
return;
}
Benchmark.start("Database: Save Nicknames Multiple");
Benchmark.start("Save Nicknames Multiple");
Map<Integer, List<String>> saved = getNicknames(nicknames.keySet());
PreparedStatement statement = null;
@ -263,7 +263,7 @@ public class NicknamesTable extends Table {
}
} finally {
close(statement);
Benchmark.stop("Database: Save Nicknames Multiple");
Benchmark.stop("Database", "Save Nicknames Multiple");
}
}
}

View File

@ -77,16 +77,17 @@ public class SecurityTable extends Table {
statement.setString(2, saltPassHash);
statement.setInt(3, permLevel);
statement.execute();
commit();
} finally {
close(statement);
}
}
public boolean userExists(String user) throws SQLException {
return getSecurityInfo(user) != null;
return getWebUser(user) != null;
}
public WebUser getSecurityInfo(String user) throws SQLException {
public WebUser getWebUser(String user) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {

View File

@ -58,7 +58,7 @@ public class SessionsTable extends Table {
* @throws SQLException
*/
public List<SessionData> getSessionData(int userId) throws SQLException {
Benchmark.start("Database: Get Sessions");
Benchmark.start("Get Sessions");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -75,7 +75,7 @@ public class SessionsTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get Sessions");
Benchmark.stop("Database", "Get Sessions");
}
}
@ -108,16 +108,14 @@ public class SessionsTable extends Table {
return;
}
Benchmark.start("Database: Save Sessions");
sessions.removeAll(getSessionData(userId));
if (sessions.isEmpty()) {
Benchmark.stop("Database: Save Sessions");
return;
}
Benchmark.start("Save Sessions");
PreparedStatement statement = null;
try {
statement = prepareStatement("INSERT INTO " + tableName + " ("
+ columnUserID + ", "
@ -141,7 +139,7 @@ public class SessionsTable extends Table {
statement.executeBatch();
} finally {
close(statement);
Benchmark.stop("Database: Save Sessions");
Benchmark.stop("Database", "Save Sessions");
}
}
@ -155,7 +153,7 @@ public class SessionsTable extends Table {
return new HashMap<>();
}
Benchmark.start("Database: Get Sessions multiple");
Benchmark.start("Get Sessions multiple");
PreparedStatement statement = null;
ResultSet set = null;
@ -184,7 +182,7 @@ public class SessionsTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get Sessions multiple");
Benchmark.stop("Database", "Get Sessions multiple");
}
}
@ -197,7 +195,7 @@ public class SessionsTable extends Table {
return;
}
Benchmark.start("Database: Save Sessions multiple");
Benchmark.start("Save Sessions multiple");
Map<Integer, List<SessionData>> saved = getSessionData(sessions.keySet());
for (Map.Entry<Integer, List<SessionData>> entrySet : sessions.entrySet()) {
@ -218,15 +216,15 @@ public class SessionsTable extends Table {
List<List<Container<SessionData>>> batches = splitIntoBatches(sessions);
batches.stream().forEach(batch -> {
batches.forEach(batch -> {
try {
saveSessionBatch(batch);
} catch (SQLException e) {
e.printStackTrace();
Log.toLog("SessionsTable.saveSessionData", e);
}
});
Benchmark.stop("Database: Save Sessions multiple");
Benchmark.stop("Database", "Save Sessions multiple");
}
private void saveSessionBatch(List<Container<SessionData>> batch) throws SQLException {
@ -235,7 +233,7 @@ public class SessionsTable extends Table {
}
int batchSize = batch.size();
Log.debug("Preparing insertion of sessions... Batch Size: " + batchSize);
Log.debug("Database", "Preparing insertion of sessions - Batch Size: " + batchSize);
PreparedStatement statement = null;
try {
@ -258,17 +256,14 @@ public class SessionsTable extends Table {
statement.addBatch();
}
Log.debug("Executing session batch: " + batchSize);
Log.debug("Database", "Executing session batch: " + batchSize);
statement.executeBatch();
} finally {
close(statement);
}
}
/**
* @throws SQLException
*/
public void clean() throws SQLException {
public void clean() {
// TODO Clean sessions before Configurable time span
}
}

View File

@ -88,7 +88,7 @@ public class TPSTable extends Table {
* @return @throws SQLException
*/
public List<TPS> getTPSData() throws SQLException {
Benchmark.start("Database: Get TPS");
Benchmark.start("Get TPS");
List<TPS> data = new ArrayList<>();
PreparedStatement statement = null;
ResultSet set = null;
@ -109,7 +109,7 @@ public class TPSTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get TPS");
Benchmark.stop("Database", "Get TPS");
}
}
@ -119,14 +119,15 @@ public class TPSTable extends Table {
*/
public void saveTPSData(List<TPS> data) throws SQLException {
List<List<TPS>> batches = DBUtils.splitIntoBatches(data);
batches.stream()
.forEach(batch -> {
try {
saveTPSBatch(batch);
} catch (SQLException e) {
Log.toLog("UsersTable.saveUserDataInformationBatch", e);
}
});
batches.forEach(batch -> {
try {
saveTPSBatch(batch);
} catch (SQLException e) {
Log.toLog("UsersTable.saveUserDataInformationBatch", e);
}
});
db.setAvailable();
commit();
}
private void saveTPSBatch(List<TPS> batch) throws SQLException {
@ -135,7 +136,7 @@ public class TPSTable extends Table {
}
int batchSize = batch.size();
Log.debug("Preparing insertion of TPS... Batch Size: " + batchSize);
Log.debug("Database", "Preparing insertion of TPS - Batch Size: " + batchSize);
PreparedStatement statement = null;
try {
@ -160,7 +161,7 @@ public class TPSTable extends Table {
statement.addBatch();
}
Log.debug("Executing tps batch: " + batchSize);
Log.debug("Database", "Executing tps batch: " + batchSize);
statement.executeBatch();
} finally {
close(statement);

View File

@ -107,7 +107,7 @@ public abstract class Table {
* @throws SQLException
*/
protected PreparedStatement prepareStatement(String sql) throws SQLException {
Log.debug(sql);
Log.debug("Database", sql);
return getConnection().prepareStatement(sql);
}
@ -172,4 +172,15 @@ public abstract class Table {
public String toString() {
return tableName;
}
/**
* Commits changes to .db file when using SQLite databse.
* <p>
* Auto Commit enabled when using MySQL
*
* @throws SQLException If commit fails or there is nothing to commit.
*/
protected void commit() throws SQLException {
db.commit();
}
}

View File

@ -223,7 +223,7 @@ public class UsersTable extends Table {
* @return @throws SQLException
*/
public Set<UUID> getSavedUUIDs() throws SQLException {
Benchmark.start("Database: Get Saved UUIDS");
Benchmark.start("Get Saved UUIDS");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -238,7 +238,7 @@ public class UsersTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get Saved UUIDS");
Benchmark.stop("Database", "Get Saved UUIDS");
}
}
@ -274,7 +274,7 @@ public class UsersTable extends Table {
* @throws SQLException
*/
public UserData getUserData(UUID uuid) throws SQLException {
Benchmark.start("Database: Get UserData");
Benchmark.start("Get UserData");
boolean containsBukkitData = getContainsBukkitData(uuid);
UserData data = null;
if (containsBukkitData) {
@ -284,7 +284,7 @@ public class UsersTable extends Table {
data = new UserData(Fetch.getIOfflinePlayer(uuid));
addUserInformationToUserData(data);
}
Benchmark.stop("Database: Get UserData");
Benchmark.stop("Database", "Get UserData");
return data;
}
@ -312,7 +312,7 @@ public class UsersTable extends Table {
* @throws SQLException
*/
public List<UserData> getUserData(Collection<UUID> uuids) throws SQLException {
Benchmark.start("Database: Get UserData Multiple");
Benchmark.start("Get UserData Multiple");
List<UUID> containsBukkitData = getContainsBukkitData(uuids);
List<UserData> datas = new ArrayList<>();
datas.addAll(getUserDataForKnown(containsBukkitData));
@ -320,17 +320,17 @@ public class UsersTable extends Table {
uuids.removeAll(containsBukkitData);
if (!uuids.isEmpty()) {
List<UserData> noBukkitData = new ArrayList<>();
Benchmark.start("Database: Create UserData objects for No BukkitData players");
Benchmark.start("Create UserData objects for No BukkitData players");
for (UUID uuid : uuids) {
UserData uData = new UserData(Fetch.getIOfflinePlayer(uuid));
noBukkitData.add(uData);
}
Benchmark.stop("Database: Create UserData objects for No BukkitData players");
Benchmark.stop("Database", "Create UserData objects for No BukkitData players");
addUserInformationToUserData(noBukkitData);
datas.addAll(noBukkitData);
}
Benchmark.stop("Database: Get UserData Multiple");
Benchmark.stop("Database", "Get UserData Multiple");
return datas;
}
@ -365,7 +365,7 @@ public class UsersTable extends Table {
}
private UserData getUserDataForKnown(UUID uuid) throws SQLException {
Benchmark.start("Database: getUserDataForKnown UserData");
Benchmark.start("getUserDataForKnown UserData");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -401,13 +401,13 @@ public class UsersTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: getUserDataForKnown UserData");
Benchmark.stop("Database", "getUserDataForKnown UserData");
}
return null;
}
private List<UserData> getUserDataForKnown(Collection<UUID> uuids) throws SQLException {
Benchmark.start("Database: getUserDataForKnown Multiple");
Benchmark.start("getUserDataForKnown Multiple");
PreparedStatement statement = null;
ResultSet set = null;
List<UserData> datas = new ArrayList<>();
@ -448,7 +448,7 @@ public class UsersTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: getUserDataForKnown Multiple");
Benchmark.stop("Database", "getUserDataForKnown Multiple");
}
return datas;
}
@ -458,7 +458,7 @@ public class UsersTable extends Table {
* @throws SQLException
*/
public void addUserInformationToUserData(UserData data) throws SQLException {
Benchmark.start("Database: addUserInformationToUserData");
Benchmark.start("addUserInformationToUserData");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -488,7 +488,7 @@ public class UsersTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: addUserInformationToUserData");
Benchmark.stop("Database", "addUserInformationToUserData");
}
}
@ -497,7 +497,7 @@ public class UsersTable extends Table {
* @throws SQLException
*/
public void addUserInformationToUserData(List<UserData> data) throws SQLException {
Benchmark.start("Database: addUserInformationToUserData Multiple");
Benchmark.start("addUserInformationToUserData Multiple");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -533,7 +533,7 @@ public class UsersTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: addUserInformationToUserData Multiple");
Benchmark.stop("Database", "addUserInformationToUserData Multiple");
}
}
@ -542,7 +542,7 @@ public class UsersTable extends Table {
* @throws SQLException
*/
public void saveUserDataInformation(UserData data) throws SQLException {
Benchmark.start("Database: Save UserInfo");
Benchmark.start("Save UserInfo");
PreparedStatement statement = null;
try {
UUID uuid = data.getUuid();
@ -598,7 +598,7 @@ public class UsersTable extends Table {
}
} finally {
close(statement);
Benchmark.stop("Database: Save UserInfo");
Benchmark.stop("Database", "Save UserInfo");
}
}
@ -612,7 +612,7 @@ public class UsersTable extends Table {
try {
statement = prepareStatement("SELECT age FROM " + tableName + " LIMIT 1");
set = statement.executeQuery();
Log.debug("UsersTable has V4 columns.");
Log.debug("Database", "UsersTable has V4 columns.");
return true;
} catch (SQLException e) {
return false;
@ -676,14 +676,14 @@ public class UsersTable extends Table {
* @throws SQLException
*/
public void saveUserDataInformationBatch(Collection<UserData> data) throws SQLException {
Benchmark.start("Database: Save UserInfo multiple");
Benchmark.start("Save UserInfo multiple");
try {
List<UserData> newUserdata = updateExistingUserData(data);
Benchmark.start("Database: Insert new UserInfo multiple");
Benchmark.start("Insert new UserInfo multiple");
List<List<UserData>> batches = DBUtils.splitIntoBatches(newUserdata);
batches.stream()
batches
.forEach(batch -> {
try {
insertNewUserData(batch);
@ -692,9 +692,9 @@ public class UsersTable extends Table {
}
});
Benchmark.stop("Database: Insert new UserInfo multiple");
Benchmark.stop("Database", "Insert new UserInfo multiple");
} finally {
Benchmark.stop("Database: Save UserInfo multiple");
Benchmark.stop("Database", "Save UserInfo multiple");
}
}
@ -704,7 +704,7 @@ public class UsersTable extends Table {
}
int batchSize = data.size();
Log.debug("Preparing insertion of new users... Batch Size: " + batchSize);
Log.debug("Database", "Preparing insertion of new users - Batch Size: " + batchSize);
PreparedStatement statement = null;
try {
@ -738,7 +738,7 @@ public class UsersTable extends Table {
statement.addBatch();
}
Log.debug("Executing users batch: " + batchSize);
Log.debug("Database", "Executing users batch: " + batchSize);
statement.executeBatch();
} finally {
close(statement);
@ -801,7 +801,7 @@ public class UsersTable extends Table {
i++;
}
if (commitRequired) {
Log.debug("Executing userinfo batch update: " + i);
Log.debug("Database", "Executing userinfo batch update: " + i);
statement.executeBatch();
}
return saveLast;
@ -816,7 +816,7 @@ public class UsersTable extends Table {
* @throws SQLException
*/
public Map<UUID, Integer> getUserIds(Collection<UUID> uuids) throws SQLException {
Benchmark.start("Database: Get User IDS Multiple");
Benchmark.start("Get User IDS Multiple");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -835,7 +835,7 @@ public class UsersTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get User IDS Multiple");
Benchmark.stop("Database", "Get User IDS Multiple");
}
}
@ -843,7 +843,7 @@ public class UsersTable extends Table {
* @return @throws SQLException
*/
public Map<UUID, Integer> getAllUserIds() throws SQLException {
Benchmark.start("Database: Get User IDS ALL");
Benchmark.start("Get User IDS ALL");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -859,7 +859,7 @@ public class UsersTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get User IDS ALL");
Benchmark.stop("Database", "Get User IDS ALL");
}
}
@ -867,7 +867,7 @@ public class UsersTable extends Table {
* @return @throws SQLException
*/
public Map<Integer, Integer> getLoginTimes() throws SQLException {
Benchmark.start("Database: Get Logintimes");
Benchmark.start("Get Logintimes");
PreparedStatement statement = null;
ResultSet set = null;
try {
@ -882,7 +882,7 @@ public class UsersTable extends Table {
} finally {
close(set);
close(statement);
Benchmark.stop("Database: Get Logintimes");
Benchmark.stop("Database", "Get Logintimes");
}
}

View File

@ -51,6 +51,7 @@ public class VersionTable extends Table {
if (set.next()) {
version = set.getInt("version");
}
Log.debug("Database", "DB Schema version: " + version);
return version;
} finally {
close(set);

View File

@ -0,0 +1,356 @@
package main.java.com.djrapitops.plan.locale;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.settings.DefaultMessages;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.comparators.LocaleEntryComparator;
import main.java.com.djrapitops.plan.utilities.comparators.StringLengthComparator;
import main.java.com.djrapitops.plan.utilities.file.FileUtil;
import org.bukkit.ChatColor;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Class responsible for message localization.
* <p>
* Successor to Phrase Enum system.
*
* @author Rsl1122
* @since 3.6.2
*/
public class Locale implements Closeable {
private final Plan plugin;
private final Map<Msg, Message> messages;
public Locale(Plan plugin) {
LocaleHolder.setLOCALE(this);
this.plugin = plugin;
messages = new HashMap<>();
}
public void loadLocale() {
String locale = Settings.LOCALE.toString().toUpperCase();
Benchmark.start("Initializing locale");
loadDefault();
try {
if (Settings.WRITE_NEW_LOCALE.isTrue()) {
writeNewDefaultLocale();
}
File localeFile = new File(plugin.getDataFolder(), "locale.txt");
if (localeFile.exists()) {
loadFromFile(localeFile);
} else if (locale.equals("DEFAULT")) {
Log.info("Using Locale: Default (EN)");
} else {
loadFromResource("locale_" + locale + ".txt");
}
} catch (IOException e) {
Log.toLog(this.getClass().getName(), e);
}
Benchmark.stop("Enable", "Initializing locale");
}
private void writeNewDefaultLocale() throws IOException {
final int length = messages.keySet().stream()
.map(Msg::getIdentifier)
.sorted(new StringLengthComparator())
.findFirst()
.get().length() + 2;
List<String> lines = messages.entrySet().stream()
.sorted(new LocaleEntryComparator())
.map(entry -> getSpacedIdentifier(entry.getKey().getIdentifier(), length) + "|| " + entry.getValue().toString())
.collect(Collectors.toList());
Files.write(new File(plugin.getDataFolder(), "locale.txt").toPath(), lines, StandardCharsets.UTF_8);
plugin.getConfig().set(Settings.WRITE_NEW_LOCALE.getPath(), false);
}
private String getSpacedIdentifier(String identifier, int length) {
StringBuilder b = new StringBuilder(identifier);
while (b.length() < length) {
b.append(" ");
}
return b.toString();
}
private void loadDefault() {
String analysis = "Analysis | ";
String prefix = "[Plan] ";
String green = ChatColor.GREEN.toString();
String yellow = ChatColor.YELLOW.toString();
String red = ChatColor.RED.toString();
String arrowsRight = DefaultMessages.ARROWS_RIGHT.parse();
ColorScheme cs = plugin.getColorScheme();
String mCol = cs.getMainColor();
String sCol = cs.getSecondaryColor();
String tCol = cs.getTertiaryColor();
String cmdFooter = tCol + arrowsRight;
add(Msg.ENABLED, "Player Analytics Enabled.");
add(Msg.ENABLE_DB_INIT, "Database init..");
add(Msg.ENABLE_DB_INFO, "REPLACE0-database connection established.");
add(Msg.ENABLE_WEBSERVER, "Initializing Webserver..");
add(Msg.ENABLE_WEBSERVER_INFO, "Webserver running on PORT REPLACE0");
add(Msg.ENABLE_BOOT_ANALYSIS_INFO, analysis + "Boot analysis in 30 seconds..");
add(Msg.ENABLE_BOOT_ANALYSIS_RUN_INFO, analysis + "Starting Boot Analysis..");
add(Msg.ENABLE_NOTIFY_EMPTY_IP, yellow + "IP in server.properties is empty & AlternativeServerIP is not used, incorrect links will be given!");
add(Msg.ENABLE_NOTIFY_NO_DATA_VIEW, yellow + "Webserver disabled but Alternative IP/TextUI not used, no way to view data!");
add(Msg.ENABLE_NOTIFY_DISABLED_CHATLISTENER, yellow + "Chat listener disabled, nickname info inaccurate.");
add(Msg.ENABLE_NOTIFY_DISABLED_COMMANDLISTENER, yellow + "Command usage listener disabled.");
add(Msg.ENABLE_NOTIFY_DISABLED_DEATHLISTENER, yellow + "Death listener disabled, player & mob kills not recorded.");
add(Msg.ENABLE_FAIL_WRONG_DB, "That database type doesn't exist.");
add(Msg.ENABLE_FAIL_DB, "REPLACE0-Database Connection failed: REPLACE1");
add(Msg.ENABLE_DB_FAIL_DISABLE_INFO, "Database initialization has failed, disabling Plan.");
add(Msg.RUN_WARN_QUEUE_SIZE, "Queue size is too small! (REPLACE0), change the setting to a higher number! (Currently REPLACE1)");
add(Msg.DISABLED, "Player Analytics Disabled.");
add(Msg.DISABLE_CACHE_SAVE, "Saving cached data..");
add(Msg.DISABLE_WEBSERVER, "Shutting down Webserver..");
add(Msg.ANALYSIS_START, analysis + "Beginning analysis of user data..");
add(Msg.ANALYSIS_FETCH_UUID, analysis + "Checking for available players..");
add(Msg.ANALYSIS_FETCH, analysis + "Fetching Data..");
add(Msg.ANALYSIS_PHASE_START, analysis + "Data Fetched (REPLACE0 users, took REPLACE1ms), beginning Analysis of data..");
add(Msg.ANALYSIS_3RD_PARTY, analysis + "Analyzing additional data sources (3rd party)");
add(Msg.ANALYSIS_FINISHED, analysis + "Analysis Complete. (took REPLACE0ms) REPLACE1");
add(Msg.ANALYSIS_FAIL_NO_PLAYERS, analysis + "Analysis failed, no known players.");
add(Msg.ANALYSIS_FAIL_NO_DATA, analysis + "Analysis failed, no data in the database.");
add(Msg.ANALYSIS_FAIL_FETCH_EXCEPTION, analysis + "Failed to fetch data for Analysis, Exception occurred.");
add(Msg.MANAGE_INFO_CONFIG_REMINDER, yellow + prefix + "Remember to swap to the new database and reload plugin");
add(Msg.MANAGE_INFO_START, arrowsRight + sCol + " Processing data..");
add(Msg.MANAGE_INFO_IMPORT, cmdFooter + " " + mCol + " Importing Data..");
add(Msg.MANAGE_INFO_FAIL, red + prefix + "Something went wrong while processing the data!");
add(Msg.MANAGE_INFO_SUCCESS, cmdFooter + " " + mCol + " Success!");
add(Msg.MANAGE_INFO_COPY_SUCCESS, green + prefix + "All data copied successfully!");
add(Msg.MANAGE_INFO_MOVE_SUCCESS, green + prefix + "All data moved successfully!");
add(Msg.MANAGE_INFO_CLEAR_SUCCESS, green + prefix + "All data cleared successfully!");
add(Msg.MANAGE_INFO_REMOVE_SUCCESS, cmdFooter + " " + mCol + "Data of " + tCol + "REPLACE0" + mCol + " was removed from Database " + tCol + "REPLACE1" + mCol + ".");
add(Msg.MANAGE_FAIL_INCORRECT_PLUGIN, red + prefix + "Plugin not supported: ");
add(Msg.MANAGE_FAIL_PLUGIN_NOT_ENABLED, red + prefix + "Plugin is not enabled: ");
add(Msg.MANAGE_FAIL_SAME_DB, red + prefix + "Can't move to the same database!");
add(Msg.MANAGE_FAIL_INCORRECT_DB, red + prefix + "Incorrect database! (sqlite/mysql accepted): ");
add(Msg.MANAGE_FAIL_FAULTY_DB, red + prefix + "One of the databases was not initialized properly.");
add(Msg.MANAGE_FAIL_NO_PLAYERS, red + prefix + "Database has no player data!");
add(Msg.MANAGE_FAIL_FILE_NOT_FOUND, red + prefix + "Backup file doesn't exist!");
add(Msg.MANAGE_FAIL_CONFIRM, red + prefix + "Add -a to confirm execution! REPLACE0");
add(Msg.MANAGE_NOTIFY_REWRITE, "Data in REPLACE0-database will be rewritten!");
add(Msg.MANAGE_NOTIFY_OVERWRITE, "Data in REPLACE0-database will be overwritten!");
add(Msg.MANAGE_NOTIFY_PARTIAL_OVERWRITE, "Some data in REPLACE0-database will be overwritten!");
add(Msg.MANAGE_NOTIFY_REMOVE, "Data in REPLACE0-database will be removed!");
add(Msg.CMD_FAIL_REQ_ARGS, red + prefix + "Command requires arguments. REPLACE0");
add(Msg.CMD_FAIL_REQ_ONE_ARG, red + prefix + "Command requires one argument.");
add(Msg.CMD_FAIL_NO_PERMISSION, red + prefix + "You do not have the required permission.");
add(Msg.CMD_FAIL_USERNAME_NOT_VALID, red + prefix + "This Player doesn't exist.");
add(Msg.CMD_FAIL_USERNAME_NOT_SEEN, red + prefix + "This Player has not played on this server.");
add(Msg.CMD_FAIL_USERNAME_NOT_KNOWN, red + prefix + "Player not found from the database.");
add(Msg.CMD_FAIL_TIMEOUT, red + prefix + "REPLACE0 Command timed out! Check '/plan status' & console.");
add(Msg.CMD_FAIL_NO_DATA_VIEW, yellow + "" + prefix + "No Way to view Data Available.");
add(Msg.CMD_INFO_ANALYSIS_TEMP_DISABLE, yellow + "Analysis has been temporarily disabled due to expensive task, use /plan status for info.");
add(Msg.CMD_INFO_RELOAD_COMPLETE, green + prefix + "Reload complete.");
add(Msg.CMD_INFO_FETCH_DATA, tCol + arrowsRight + mCol + " Fetching data to cache..");
add(Msg.CMD_INFO_CLICK_ME, "Click Me");
add(Msg.CMD_INFO_LINK, sCol + "" + mCol + "Link: " + tCol);
add(Msg.CMD_INFO_RESULTS, sCol + " Matching players: " + tCol);
add(Msg.CMD_INFO_NO_RESULTS, sCol + "" + mCol + "No results for " + sCol + "REPLACE0" + mCol + ".");
add(Msg.CMD_INFO_SEARCHING, cmdFooter + mCol + "Searching..");
add(Msg.CMD_USG_ANALYZE, "View the Server Analysis");
add(Msg.CMD_USG_QANALYZE, "View the Server Analysis as Text");
add(Msg.CMD_USG_HELP, "Show command list.");
add(Msg.CMD_USG_INFO, "Check the version of Plan");
add(Msg.CMD_USG_INSPECT, "Inspect Player's Data");
add(Msg.CMD_USG_QINSPECT, "Inspect Player's Data as Text");
add(Msg.CMD_USG_LIST, "List to all cached players");
add(Msg.CMD_USG_MANAGE, "Database management command");
add(Msg.CMD_USG_MANAGE_BACKUP, "Backup a database to .db file");
add(Msg.CMD_USG_MANAGE_CLEAN, "Clear old data from the database");
add(Msg.CMD_USG_MANAGE_CLEAR, "Clear ALL data from the database");
add(Msg.CMD_USG_MANAGE_DUMP, "Create a Hastebin log for Dev for easier Issue reporting.");
add(Msg.CMD_USG_MANAGE_HOTSWAP, "Hotswap to another database & restart the plugin");
add(Msg.CMD_USG_MANAGE_IMPORT, "Import Data from supported plugins to Active Database.");
add(Msg.CMD_USG_MANAGE_MOVE, "Copy data from one database to another & overwrite values");
add(Msg.CMD_USG_MANAGE_REMOVE, "Remove players's data from the Active Database.");
add(Msg.CMD_USG_MANAGE_RESTORE, "Restore a database from a backup file");
add(Msg.CMD_USG_RELOAD, "Restart the Plugin (Reloads config)");
add(Msg.CMD_USG_SEARCH, "Search for player");
add(Msg.CMD_USG_WEB, "Manage Webusers");
add(Msg.CMD_USG_WEB_CHECK, "Check a webuser and their permission level.");
add(Msg.CMD_USG_WEB_DELETE, "Delete a webuser");
add(Msg.CMD_USG_WEB_LEVEL, "Info about permission levels.");
add(Msg.CMD_USG_WEB_REGISTER, "Register a user for the webserver");
add(Msg.CMD_HELP_ANALYZE, mCol + "Analysis Command"
+ "\\" + tCol + " Used to Refresh analysis cache & Access the result page"
+ "\\" + sCol + " /plan status can be used to check status of analysis while it is running."
+ "\\" + sCol + " Aliases: analyze, analyse, analysis, a");
add(Msg.CMD_HELP_QANALYZE, mCol + "Quick Analysis command"
+ "\\" + tCol + " Used to get in game info about analysis."
+ "\\" + sCol + " Has less info than full Analysis web page."
+ "\\" + sCol + " Aliases: qanalyze, ganalyse, qanalysis, qa");
add(Msg.CMD_HELP_PLAN, mCol + "/plan - Main Command"
+ "\\" + tCol + " Used to access all SubCommands & help"
+ "\\" + sCol + " /plan - List subcommands"
+ "\\" + sCol + " /plan <subcommand> ? - in depth help");
add(Msg.CMD_HELP_INSPECT, mCol + "Inspect command"
+ "\\" + tCol + " Used to get a link to User's inspect page."
+ "\\" + sCol + " Own inspect page can be accessed with /plan inspect"
+ "\\" + sCol + " Alias: /plan <name>");
add(Msg.CMD_HELP_QINSPECT, mCol + "Quick Inspect command"
+ "\\" + tCol + " Used to get some inspect info in game."
+ "\\" + sCol + " Has less info than full Inspect web page."
+ "\\" + sCol + " Alias: /plan qi");
add(Msg.CMD_HELP_LIST, mCol + "List command"
+ "\\" + tCol + " Used to get a link to players page."
+ "\\" + sCol + " Players page contains links to all cached inspect pages."
+ "\\" + sCol + " Alias: /plan pl");
add(Msg.CMD_HELP_MANAGE, mCol + "Manage command\\"
+ tCol + " Used to Manage Database of the plugin."
+ "\\" + sCol + " Alias: /plan m"
+ "\\" + sCol + " /plan m - List subcommands"
+ "\\" + sCol + " /plan m <subcommand> ? - in depth help");
add(Msg.CMD_HELP_MANAGE_CLEAR, mCol + "Manage Clear command"
+ "\\" + tCol + " Used to delete ALL data in the active database."
+ "\\" + sCol + " Plugin should be reloaded after successful clear."
+ "\\" + sCol + " Alias: /plan pl");
add(Msg.CMD_HELP_MANAGE_DUMP, mCol + "Manage Dump command"
+ "\\" + tCol + " Used to dump important data for bug reporting to hastebin.");
add(Msg.CMD_HELP_MANAGE_HOTSWAP, mCol + "Manage Hotswap command"
+ "\\" + tCol + " Used to change database in use on the fly."
+ "\\" + sCol + " Does not change database if connection fails");
add(Msg.CMD_HELP_MANAGE_IMPORT, mCol + "Manage Import command"
+ "\\" + tCol + " Used to import data from other sources"
+ "\\" + sCol + " Analysis will be disabled during import.");
add(Msg.CMD_HELP_MANAGE_REMOVE, mCol + "Manage Remove command"
+ "\\" + tCol + " Used to Remove user's data from the active database.");
add(Msg.CMD_HELP_SEARCH, mCol + "Search command"
+ "\\" + tCol + " Used to get a list of Player names that match the given argument."
+ "\\" + sCol + " Example: /plan search 123 - Finds all users with 123 in their name.");
add(Msg.CMD_HELP_WEB, mCol + "Web User Manage command"
+ "\\" + tCol + " Used to manage web users of the plugin"
+ "\\" + sCol + " Users have a permission level:"
+ "\\" + tCol + " 0 - Access to all pages"
+ "\\" + tCol + " 1 - Access to /players & all inspect pages"
+ "\\" + tCol + " 2 - Access to own inspect page"
+ "\\" + sCol + " Alias: /plan web");
add(Msg.CMD_HELP_WEB_REGISTER, mCol + "Web Register command"
+ "\\" + tCol + " Used to register a new user for the webserver."
+ "\\" + sCol + " Registering a user for another player requires " + Permissions.MANAGE_WEB.getPerm() + " permission."
+ "\\" + sCol + " Passwords are hashed with PBKDF2 (64,000 iterations of SHA1) using a cryptographically-random salt.");
add(Msg.CMD_HEADER_ANALYZE, cmdFooter + mCol + " Player Analytics - Analysis results");
add(Msg.CMD_HEADER_INSPECT, cmdFooter + mCol + " Player Analytics - Inspect results");
add(Msg.CMD_HEADER_INFO, cmdFooter + mCol + " Player Analytics - Info");
add(Msg.CMD_HEADER_SEARCH, cmdFooter + mCol + " Player Analytics - Search results: ");
add(Msg.CMD_CONSTANT_FOOTER, tCol + arrowsRight);
add(Msg.CMD_CONSTANT_LIST_BALL, sCol + " " + "" + mCol);
add(Msg.HTML_NO_PLUGINS, "<p>No extra plugins registered.</p>");
add(Msg.HTML_BANNED, "| " + Html.SPAN.parse(Html.COLOR_4.parse() + "Banned"));
add(Msg.HTML_OP, ", Operator (Op)");
add(Msg.HTML_ONLINE, "| " + Html.SPAN.parse(Html.COLOR_2.parse() + "Online"));
add(Msg.HTML_OFFLINE, "| " + Html.SPAN.parse(Html.COLOR_4.parse() + "Offline"));
add(Msg.HTML_ACTIVE, "Player is Active");
add(Msg.HTML_INACTIVE, "Player is inactive");
add(Msg.HTML_TABLE_NO_KILLS, "No Kills");
}
private void add(Msg msg, String message) {
Verify.nullCheck(msg, message);
messages.put(msg, new Message(message));
}
private void loadFromFile(File localeFile) throws IOException {
loadFromContents(Files.lines(localeFile.toPath(), StandardCharsets.UTF_8).collect(Collectors.toList()), "Custom File");
}
private void loadFromResource(String fileName) {
try {
loadFromContents(FileUtil.lines(plugin, fileName), fileName);
} catch (FileNotFoundException e) {
Log.error("Could not find file inside the jar: " + fileName);
Log.info("Using Locale: Default (EN)");
} catch (Exception e) {
Log.toLog(this.getClass().getName(), e);
Log.info("Using Locale: Default (EN)");
}
}
private void loadFromContents(List<String> locale, String name) {
Log.info("Using Locale: " + name);
Map<String, Msg> identifiers = Msg.getIdentifiers();
locale.forEach(line -> {
String[] split = line.split(" \\|\\| ");
if (split.length == 2) {
String identifier = split[0].trim();
Msg msg = identifiers.get(identifier);
if (msg != null) {
add(msg, split[1]);
}
}
});
}
public Message getMessage(Msg msg) {
Message message = messages.get(msg);
return message != null ? message : new Message("");
}
@Override
public void close() {
messages.clear();
LocaleHolder.LOCALE = null;
}
public static void unload() {
Locale locale = LocaleHolder.getLOCALE();
if (locale != null) {
locale.close();
}
}
public static Message get(Msg msg) {
Locale locale = LocaleHolder.getLOCALE();
if (locale == null) {
throw new IllegalStateException("Locale has not been initialized.");
}
return locale.getMessage(msg);
}
private static class LocaleHolder {
private static Locale LOCALE;
public static void setLOCALE(Locale LOCALE) {
LocaleHolder.LOCALE = LOCALE;
}
public static Locale getLOCALE() {
return LOCALE;
}
}
}

View File

@ -0,0 +1,43 @@
package main.java.com.djrapitops.plan.locale;
import java.io.Serializable;
/**
* Represents a Message that can be modified.
*
* @author Rsl1122
* @since 3.6.2
*/
public class Message {
private final String message;
public Message(String message) {
this.message = message;
}
public String parse(Serializable... p) {
String returnValue = this.message;
for (int i = 0; i < p.length; i++) {
returnValue = returnValue.replace("REPLACE" + i, p[i].toString());
}
return returnValue;
}
@Override
public String toString() {
return message;
}
public String parse() {
return toString();
}
public String[] toArray() {
return message.split("\\\\");
}
public String[] toArray(Serializable... p) {
return parse().split("\\\\");
}
}

View File

@ -0,0 +1,157 @@
package main.java.com.djrapitops.plan.locale;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public enum Msg {
ENABLED("Enable"),
ENABLE_DB_INIT("Enable - Db"),
ENABLE_DB_INFO("Enable - Db Info"),
ENABLE_WEBSERVER("Enable - WebServer"),
ENABLE_WEBSERVER_INFO("Enable - WebServer Info"),
ENABLE_BOOT_ANALYSIS_INFO("Enable - Boot Analysis 30s Notify"),
ENABLE_BOOT_ANALYSIS_RUN_INFO("Enable - Boot Analysis Notify"),
//
ENABLE_NOTIFY_EMPTY_IP("Enable Notify-Empty IP"),
ENABLE_NOTIFY_NO_DATA_VIEW("Enable Notify - No data view"),
ENABLE_NOTIFY_DISABLED_CHATLISTENER("Enable Notify - ChatListener"),
ENABLE_NOTIFY_DISABLED_COMMANDLISTENER("Enable Notify - Disabled CommandListener"),
ENABLE_NOTIFY_DISABLED_DEATHLISTENER("Enable Notify - Disabled DeathListener"),
//
ENABLE_FAIL_WRONG_DB("Enable FAIL - Wrong Db Type"),
ENABLE_FAIL_DB("Enable FAIL-Db"),
ENABLE_DB_FAIL_DISABLE_INFO("Enable Db FAIL - Disable Info"),
//
RUN_WARN_QUEUE_SIZE("WARN - Too Small Queue Size"),
//
DISABLED("Disable"),
DISABLE_CACHE_SAVE("Disable - Save"),
DISABLE_WEBSERVER("Disable - WebServer"),
//
ANALYSIS_START("Analysis - Start"),
ANALYSIS_FETCH_UUID("Analysis - Fetch Phase Start"),
ANALYSIS_FETCH("Analysis - Fetch Phase"),
ANALYSIS_PHASE_START("Analysis - Begin Analysis"),
ANALYSIS_3RD_PARTY("Analysis - Third Party"),
ANALYSIS_FINISHED("Analysis - Complete"),
ANALYSIS_FAIL_NO_PLAYERS("Analysis FAIL - No Players"),
ANALYSIS_FAIL_NO_DATA("Analysis FAIL - No Data"),
ANALYSIS_FAIL_FETCH_EXCEPTION("Analysis FAIL - Fetch Exception"),
//
MANAGE_INFO_CONFIG_REMINDER("Manage - Remind Config Change"),
MANAGE_INFO_START("Manage - Start"),
MANAGE_INFO_IMPORT("Manage - Import"),
MANAGE_INFO_FAIL("Manage - Process Fail"),
MANAGE_INFO_SUCCESS("Manage - Success"),
MANAGE_INFO_COPY_SUCCESS("Manage - Copy Success"),
MANAGE_INFO_MOVE_SUCCESS("Manage - Move Success"),
MANAGE_INFO_CLEAR_SUCCESS("Manage - Clear Success"),
MANAGE_INFO_REMOVE_SUCCESS("Manage - Remove Success"),
//
MANAGE_FAIL_INCORRECT_PLUGIN("Manage FAIL - Incorrect Plugin"),
MANAGE_FAIL_PLUGIN_NOT_ENABLED("Manage FAIL - Unenabled Plugin"),
MANAGE_FAIL_SAME_DB("Manage FAIL - Same DB"),
MANAGE_FAIL_INCORRECT_DB("Manage FAIL - Incorrect DB"),
MANAGE_FAIL_FAULTY_DB("Manage FAIL - Faulty DB Connection"),
MANAGE_FAIL_NO_PLAYERS("Manage FAIL - Empty DB"),
MANAGE_FAIL_FILE_NOT_FOUND("Manage FAIL - Backup File Not Found"),
//
MANAGE_FAIL_CONFIRM("Manage FAIL - Confirm Action"),
MANAGE_NOTIFY_REWRITE("Manage NOTIFY - Rewrite"),
MANAGE_NOTIFY_OVERWRITE("Manage NOTIFY - Overwrite"),
MANAGE_NOTIFY_PARTIAL_OVERWRITE("Manage NOTIFY - Partial Overwrite"),
MANAGE_NOTIFY_REMOVE("Manage NOTIFY - Remove"),
//
CMD_FAIL_REQ_ARGS("Cmd FAIL - Requires Arguments"),
CMD_FAIL_REQ_ONE_ARG("Cmd FAIL - Require only one Argument"),
CMD_FAIL_NO_PERMISSION("Cmd FAIL - No Permission"),
CMD_FAIL_USERNAME_NOT_VALID("Cmd FAIL - Invalid Username"),
CMD_FAIL_USERNAME_NOT_SEEN("Cmd FAIL - Unseen Username"),
CMD_FAIL_USERNAME_NOT_KNOWN("Cmd FAIL - Unknown Username"),
CMD_FAIL_TIMEOUT("Cmd FAIL - Timeout"),
CMD_FAIL_NO_DATA_VIEW("Cmd FAIL - No Data View"),
//
CMD_INFO_ANALYSIS_TEMP_DISABLE("Analysis NOTIFY - Temporary Disable"),
CMD_INFO_CLICK_ME("Cmd - Click Me"),
CMD_INFO_LINK("Cmd - Link"),
CMD_INFO_RESULTS("Cmd - Results"),
CMD_INFO_NO_RESULTS("Cmd - No Results"),
CMD_INFO_RELOAD_COMPLETE("Cmd - Reload Success"),
CMD_INFO_FETCH_DATA("Cmd - Fetch Data"),
CMD_INFO_SEARCHING("Cmd - Searching"),
//
CMD_USG_ANALYZE("Cmd - Usage /plan analyze"),
CMD_USG_QANALYZE("Cmd - Usage /plan qanalyze"),
CMD_USG_HELP("Cmd - Usage /plan help"),
CMD_USG_INFO("Cmd - Usage /plan info"),
CMD_USG_INSPECT("Cmd - Usage /plan inspect"),
CMD_USG_QINSPECT("Cmd - Usage /plan qinspect"),
CMD_USG_LIST("Cmd - Usage /plan list"),
CMD_USG_MANAGE("Cmd - Usage /plan manage"),
CMD_USG_MANAGE_BACKUP("Cmd - Usage /plan manage backup"),
CMD_USG_MANAGE_CLEAN("Cmd - Usage /plan manage clean"),
CMD_USG_MANAGE_CLEAR("Cmd - Usage /plan manage clear"),
CMD_USG_MANAGE_DUMP("Cmd - Usage /plan manage dump"),
CMD_USG_MANAGE_HOTSWAP("Cmd - Usage /plan manage hotswap"),
CMD_USG_MANAGE_IMPORT("Cmd - Usage /plan manage import"),
CMD_USG_MANAGE_MOVE("Cmd - Usage /plan manage move"),
CMD_USG_MANAGE_REMOVE("Cmd - Usage /plan manage remove"),
CMD_USG_MANAGE_RESTORE("Cmd - Usage /plan manage restore"),
CMD_USG_RELOAD("Cmd - Usage /plan reload"),
CMD_USG_SEARCH("Cmd - Usage /plan search"),
CMD_USG_WEB("Cmd - Usage /plan webuser"),
CMD_USG_WEB_CHECK("Cmd - Usage /plan webuser check"),
CMD_USG_WEB_DELETE("Cmd - Usage /plan webuser delete"),
CMD_USG_WEB_LEVEL("Cmd - Usage /plan webuser level"),
CMD_USG_WEB_REGISTER("Cmd - Usage /plan webuser register"),
//
CMD_HELP_ANALYZE("In Depth Help - /plan analyze ?"),
CMD_HELP_QANALYZE("In Depth Help - /plan qanalyze ?"),
CMD_HELP_PLAN("In Depth Help - /plan ?"),
CMD_HELP_INSPECT("In Depth Help - /plan inspect ?"),
CMD_HELP_QINSPECT("In Depth Help - /plan qinspect ?"),
CMD_HELP_LIST("In Depth Help - /plan list ?"),
CMD_HELP_MANAGE("In Depth Help - /plan manage ?"),
CMD_HELP_MANAGE_CLEAR("In Depth Help - /plan manage clear ?"),
CMD_HELP_MANAGE_DUMP("In Depth Help - /plan manage dump ?"),
CMD_HELP_MANAGE_HOTSWAP("In Depth Help - /plan manage hotswap ?"),
CMD_HELP_MANAGE_IMPORT("In Depth Help - /plan manage import ?"),
CMD_HELP_MANAGE_REMOVE("In Depth Help - /plan manage remove ?"),
CMD_HELP_SEARCH("In Depth Help - /plan search ?"),
CMD_HELP_WEB("In Depth Help - /plan webuser ?"),
CMD_HELP_WEB_REGISTER("In Depth Help - /plan webuser register ?"),
//
CMD_HEADER_ANALYZE("Cmd Header - Analysis"),
CMD_HEADER_INSPECT("Cmd Header - Inspect"),
CMD_HEADER_INFO("Cmd Header - Info"),
CMD_HEADER_SEARCH("Cmd Header - Search"),
//
CMD_CONSTANT_LIST_BALL(">Constant - List Ball"),
CMD_CONSTANT_FOOTER(">Constant - CMD Footer"),
//
HTML_NO_PLUGINS("Html - No Extra Plugins"),
HTML_BANNED("Html - Banned"),
HTML_OP("Html - OP"),
HTML_ONLINE("Html - Online"),
HTML_OFFLINE("Html - Offline"),
HTML_ACTIVE("Html - Active"),
HTML_INACTIVE("Html - Inactive"),
HTML_TABLE_NO_KILLS("Html - Table No Kills"),;
private final String identifier;
Msg(String identifier) {
this.identifier = identifier;
}
public String getIdentifier() {
return identifier;
}
public static Map<String, Msg> getIdentifiers() {
return Arrays.stream(values()).collect(Collectors.toMap(Msg::getIdentifier, Function.identity()));
}
}

View File

@ -14,9 +14,6 @@ import java.util.Scanner;
*/
public enum Html {
REPLACE0("REPLACE0"),
REPLACE1("REPLACE1"),
WARN_INACCURATE("<div class=\"warn\">Data might be inaccurate, player has just registered.</div>"),
COLOR_0("<span class=\"black\">"),
COLOR_1("<span class=\"darkblue\">"),
COLOR_2("<span class=\"darkgreen\">"),
@ -35,57 +32,19 @@ public enum Html {
COLOR_F("<span class=\"white\">"),
//
FONT_AWESOME_ICON("<i class=\"fa fa-REPLACE0\" aria-hidden=\"true\"></i>"),
MINOTAR_SMALL_IMG("<img style=\"float: left; padding: 2px 2px 0px 2px\" alt=\"" + REPLACE0 + "\" src=\"https://minotar.net/avatar/" + REPLACE0 + "/19\">"),
SPAN("" + REPLACE0 + "</span>"),
BUTTON("<a class=\"button\" href=\"" + REPLACE0 + "\">" + REPLACE1 + "</a>"),
MINOTAR_SMALL_IMG("<img style=\"float: left; padding: 2px 2px 0px 2px\" alt=\"REPLACE0\" src=\"https://minotar.net/avatar/REPLACE0/19\">"),
SPAN("REPLACE0</span>"),
BUTTON("<a class=\"button\" href=\"REPLACE0\">REPLACE1</a>"),
BUTTON_CLASS("class=\"button\""),
LINK("<a class=\"link\" href=\"" + REPLACE0 + "\">" + REPLACE1 + "</a>"),
LINK_EXTERNAL("<a class=\"link\" target=\"_blank\" href=\"" + REPLACE0 + "\">" + REPLACE1 + "</a>"),
LINK("<a class=\"link\" href=\"REPLACE0\">REPLACE1</a>"),
LINK_EXTERNAL("<a class=\"link\" target=\"_blank\" href=\"REPLACE0\">REPLACE1</a>"),
LINK_CLASS("class=\"link\""),
IMG("<img src=\"" + REPLACE0 + "\">"),
COLUMNS_DIV_WRAPPER("<div class=\"columns\">" + REPLACE0 + "</div>"),
COLUMN_DIV_WRAPPER("<div class=\"about box column\">" + REPLACE0 + "</div>"),
HEADER("<div class=\"headerbox\" style=\"width: 95%;\"><div class=\"header-icon\"><div class=\"header-label\"><i class=\"fa fa-cube\" aria-hidden=\"true\"></i><span class=\"header-text\"> " + REPLACE0 + "</span></div></div></div>"),
PLUGIN_DATA_WRAPPER("<div class=\"plugin-data\">" + REPLACE0 + "</div>"),
IMG("<img src=\"REPLACE0\">"),
COLUMNS_DIV_WRAPPER("<div class=\"columns\">REPLACE0</div>"),
COLUMN_DIV_WRAPPER("<div class=\"about box column\">REPLACE0</div>"),
HEADER("<div class=\"headerbox\" style=\"width: 95%;\"><div class=\"header-icon\"><div class=\"header-label\"><i class=\"fa fa-cube\" aria-hidden=\"true\"></i><span class=\"header-text\"> REPLACE0</span></div></div></div>"),
PLUGIN_DATA_WRAPPER("<div class=\"plugin-data\">REPLACE0</div>"),
PLUGIN_CONTAINER_START("<div class=\"plugin-container\">"),
NO_PLUGINS("<p>No extra plugins registered.</p>"),
//
TOP_TOWNS("<p><b>Top 20 Towns</b></p>"),
TOP_FACTIONS("<p><b>Top 20 Factions</b></p>"),
TOTAL_BALANCE("<p>Server Total Balance: " + REPLACE0 + "</p>"),
TOTAL_VOTES("<p>Players have voted total of " + REPLACE0 + " times.</p>"),
PLOT_OPTIONS("<p>Plot options: " + REPLACE0 + "</p>"),
FRIENDS("<p>Friends with " + REPLACE0 + "</p>"),
BALANCE("<p>Balance: " + REPLACE0 + "</p>"),
FACTION_NOT_FOUND("Faction not found"),
FACTION_NO_LEADER("No leader"),
FACTION_NO_FACTIONS("No Factions"),
WARPS("<br/>Warps: " + REPLACE0),
ACHIEVEMENTS("<br/>Achievements: " + REPLACE0 + "/" + REPLACE1),
JAILED("| Jailed"),
MUTED("| Muted"),
VOTES("<br/>Has voted " + REPLACE0 + "times"),
FACTION("<br/>Faction: " + REPLACE0 + " | Power: " + REPLACE1 + "/REPLACE2"),
TOWN("<br/>Town: " + REPLACE0),
TOWN_NO_TOWNS("No Towns"),
//
BANNED("| " + SPAN.parse(COLOR_4.parse() + "Banned")),
OPERATOR(", Operator (Op)"),
ONLINE("| " + SPAN.parse(COLOR_2.parse() + "Online")),
OFFLINE("| " + SPAN.parse(COLOR_4.parse() + "Offline")),
ACTIVE("Player is Active"),
INACTIVE("Player is inactive"),
ERROR_LIST("Error Creating List</p>"),
HIDDEN("Hidden (config)"),
ERROR_NOT_SET("Error: Replace rule was not set"),
//
GRAPH_BANNED("Banned"),
GRAPH_UNKNOWN("Unknown"),
GRAPH_INACTIVE("Inactive"),
GRAPH_ACTIVE("Active"),
GRAPH_ONLINE("Players Online"),
GRAPH_PLAYERS("Players"),
GRAPH_DATE("Date"),
//
TABLE_START_2("<table class=\"sortable table\"><thead><tr><th>REPLACE0</th><th>REPLACE1</th></tr></thead><tbody>"),
TABLE_START_3("<table class=\"sortable table\"><thead><tr><th>REPLACE0</th><th>REPLACE1</th><th>REPLACE2</th></tr></thead><tbody>"),
@ -94,16 +53,15 @@ public enum Html {
TABLE_KILLS_START(TABLE_START_3.parse("Date", "Killed", "With")),
TABLE_FACTIONS_START(TABLE_START_4.parse(FONT_AWESOME_ICON.parse("flag") + " Faction", FONT_AWESOME_ICON.parse("bolt") + " Power", FONT_AWESOME_ICON.parse("map-o") + " Land", FONT_AWESOME_ICON.parse("user") + " Leader")),
TABLE_TOWNS_START(TABLE_START_4.parse(FONT_AWESOME_ICON.parse("bank") + " Town", FONT_AWESOME_ICON.parse("users") + " Residents", FONT_AWESOME_ICON.parse("map-o") + " Land", FONT_AWESOME_ICON.parse("user") + " Mayor")),
TABLELINE_2("<tr><td><b>" + REPLACE0 + "</b></td><td>" + REPLACE1 + "</td></tr>"),
TABLELINE_3("<tr><td><b>" + REPLACE0 + "</b></td><td>" + REPLACE1 + "</td><td>REPLACE2</td></tr>"),
TABLELINE_4("<tr><td><b>" + REPLACE0 + "</b></td><td>" + REPLACE1 + "</td><td>REPLACE2</td><td>REPLACE3</td></tr>"),
TABLELINE_2("<tr><td><b>REPLACE0</b></td><td>REPLACE1</td></tr>"),
TABLELINE_3("<tr><td><b>REPLACE0</b></td><td>REPLACE1</td><td>REPLACE2</td></tr>"),
TABLELINE_4("<tr><td><b>REPLACE0</b></td><td>REPLACE1</td><td>REPLACE2</td><td>REPLACE3</td></tr>"),
TABLELINE_PLAYERS("<tr><td>REPLACE0</td><td>REPLACE1</td><td sorttable_customkey=\"REPLACE2\">REPLACE3</td><td>REPLACE4</td><td sorttable_customkey=\"REPLACE5\">REPLACE6</td>" + "<td sorttable_customkey=\"REPLACE7\">REPLACE8</td><td>REPLACE9</td></tr>"),
TABLELINE_3_CUSTOMKEY("<tr><td sorttable_customkey=\"REPLACE0\">REPLACE1</td><td sorttable_customkey=\"REPLACE2\">REPLACE3</td><td sorttable_customkey=\"REPLACE4\">REPLACE5</td></tr>"),
TABLELINE_3_CUSTOMKEY_1("<tr><td sorttable_customkey=\"REPLACE0\">REPLACE1</td><td>REPLACE2</td><td>REPLACE3</td></tr>"),
ERROR_TABLE_2(TABLELINE_2.parse("No data", "No data")),
TABLE_END("</tbody></table>"),
SESSIONDATA_NONE("No Session Data available"),
KILLDATA_NONE("No Kills"),;
TABLE_END("</tbody></table>"), // KILLDATA_NONE("No Kills"),
;
private String html;

View File

@ -10,8 +10,8 @@ import java.util.stream.Collectors;
* Class for creating scatter graph data from RAM Usage snapshots with TPS task.
*
* @author Rsl1122
* @since 3.6.0
* @see main.java.com.djrapitops.plan.data.listeners.TPSCountTimer
* @since 3.6.0
*/
public class RamGraphCreator {

View File

@ -10,8 +10,8 @@ import java.util.stream.Collectors;
* Class for creating scatter graph data from Chunk & Entity load snapshots with TPS task.
*
* @author Rsl1122
* @since 3.6.0
* @see main.java.com.djrapitops.plan.data.listeners.TPSCountTimer
* @since 3.6.0
*/
public class WorldLoadGraphCreator {

View File

@ -2,7 +2,6 @@ package main.java.com.djrapitops.plan.ui.html.tables;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.comparators.MapComparator;
import java.util.Collections;
@ -26,7 +25,6 @@ public class CommandUseTableCreator {
* @return
*/
public static String createSortedCommandUseTable(Map<String, Integer> commandUse) {
Benchmark.start("Create CommandUse table");
List<String[]> sorted = MapComparator.sortByValue(commandUse);
StringBuilder html = new StringBuilder();
if (sorted.isEmpty()) {
@ -43,14 +41,12 @@ public class CommandUseTableCreator {
try {
html.append(Html.TABLELINE_2.parse(values[1], values[0]));
} catch (IllegalArgumentException e) {
Log.toLog("SortableCommandUseTableCreator", e);
Log.toLog("Cause: " + values[0] + " " + values[1], Log.getErrorsFilename());
Log.toLog("CommandUseTable - Cause: " + values[0] + " " + values[1], e);
}
i++;
}
}
Benchmark.stop("Create CommandUse table");
return html.toString();
}
}

View File

@ -3,6 +3,8 @@ package main.java.com.djrapitops.plan.ui.html.tables;
import com.djrapitops.plugin.utilities.player.Fetch;
import com.djrapitops.plugin.utilities.player.IOfflinePlayer;
import main.java.com.djrapitops.plan.data.KillData;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
@ -31,7 +33,7 @@ public class KillsTableCreator {
StringBuilder html = new StringBuilder(Html.TABLE_KILLS_START.parse());
if (killData.isEmpty()) {
html.append(Html.TABLELINE_3.parse(Html.KILLDATA_NONE.parse(), "", ""));
html.append(Html.TABLELINE_3.parse(Locale.get(Msg.HTML_TABLE_NO_KILLS).parse(), "", ""));
} else {
int i = 0;

View File

@ -3,7 +3,6 @@ package main.java.com.djrapitops.plan.ui.html.tables;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
@ -28,7 +27,6 @@ public class PlayersTableCreator {
* @return
*/
public static String createSortablePlayersTable(List<UserData> data) {
Benchmark.start("Create Players table");
StringBuilder html = new StringBuilder();
long now = MiscUtils.getTime();
@ -44,10 +42,10 @@ public class PlayersTableCreator {
boolean isUnknown = uData.getLoginTimes() == 1;
boolean isActive = AnalysisUtils.isActive(now, uData.getLastPlayed(), uData.getPlayTime(), uData.getLoginTimes());
String activityString = isBanned ? Html.GRAPH_BANNED.parse()
: isUnknown ? Html.GRAPH_UNKNOWN.parse()
: isActive ? Html.GRAPH_ACTIVE.parse()
: Html.GRAPH_INACTIVE.parse();
String activityString = isBanned ? "Banned"
: isUnknown ? "Unknown"
: isActive ? "Active"
: "Inactive";
String img = showImages ? Html.MINOTAR_SMALL_IMG.parse(uData.getName()) : "";
@ -62,11 +60,9 @@ public class PlayersTableCreator {
));
} catch (NullPointerException ignored) {
}
i++;
}
Benchmark.stop("Create Players table");
return html.toString();
}
}

View File

@ -1,6 +1,7 @@
package main.java.com.djrapitops.plan.ui.text;
import main.java.com.djrapitops.plan.Phrase;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.settings.DefaultMessages;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.AnalysisData;
import main.java.com.djrapitops.plan.data.UserData;
@ -38,15 +39,18 @@ public class TextUI {
return new String[]{"Error has occurred, please retry."};
}
UserData d = inspectCache.getFromCache(uuid);
ChatColor main = Phrase.COLOR_MAIN.color();
ChatColor sec = Phrase.COLOR_SEC.color();
ChatColor ter = Phrase.COLOR_TER.color();
ColorScheme cs = Plan.getInstance().getColorScheme();
String main = cs.getMainColor();
String sec = cs.getSecondaryColor();
String ter = cs.getTertiaryColor();
boolean active = AnalysisUtils.isActive(now, d.getLastPlayed(), d.getPlayTime(), d.getLoginTimes());
boolean banned = d.isBanned();
boolean online = d.isOnline();
String ball = sec + " " + Phrase.BALL + main;
String ball = sec + " " + DefaultMessages.BALL + main;
return new String[]{
sec + " " + Phrase.BALL + (banned ? ChatColor.DARK_RED + " Banned" : ter + (active ? " Active" : " Inactive")) + (online ? ChatColor.GREEN + " Online" : ChatColor.RED + " Offline"),
sec + " " + DefaultMessages.BALL + (banned ? ChatColor.DARK_RED + " Banned" : ter + (active ? " Active" : " Inactive")) + (online ? ChatColor.GREEN + " Online" : ChatColor.RED + " Offline"),
ball + " Registered: " + sec + FormatUtils.formatTimeStampYear(d.getRegistered()),
ball + " Last seen: " + sec + FormatUtils.formatTimeStamp(d.getLastPlayed()),
ball + " Playtime: " + sec + FormatUtils.formatTimeAmount(d.getPlayTime()),
@ -66,9 +70,12 @@ public class TextUI {
return new String[]{"Error has occurred, please retry."};
}
AnalysisData d = analysisCache.getData();
ChatColor main = Phrase.COLOR_MAIN.color();
ChatColor sec = Phrase.COLOR_SEC.color();
String ball = sec + " " + Phrase.BALL + main;
ColorScheme cs = Plan.getInstance().getColorScheme();
String main = cs.getMainColor();
String sec = cs.getSecondaryColor();
String ball = sec + " " + DefaultMessages.BALL + main;
final ActivityPart activity = d.getActivityPart();
final JoinInfoPart join = d.getJoinInfoPart();
final KillPart kills = d.getKillPart();

View File

@ -102,7 +102,8 @@ public class Request implements Closeable {
String[] reqLine = req.split(" ");
if (reqLine.length >= 2) {
request = reqLine[0];
target = reqLine[1];
target = reqLine[1].replace("%20", " ")
.replace("%2E", ".");;
} else {
request = "GET";
target = "/";

View File

@ -3,14 +3,16 @@ package main.java.com.djrapitops.plan.ui.webserver;
import com.djrapitops.plugin.utilities.Verify;
import com.sun.net.httpserver.*;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.data.cache.PageCacheHandler;
import main.java.com.djrapitops.plan.database.tables.SecurityTable;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.html.DataRequestHandler;
import main.java.com.djrapitops.plan.ui.webserver.response.*;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.PassEncryptUtil;
import main.java.com.djrapitops.plan.utilities.uuid.UUIDUtility;
@ -30,6 +32,7 @@ import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;
/**
* @author Rsl1122
@ -38,11 +41,11 @@ public class WebServer {
private final Plan plugin;
private final DataRequestHandler dataReqHandler;
private final int port;
private boolean enabled = false;
private HttpServer server;
private final int port;
private boolean usingHttps;
private boolean usingHttps = false;
/**
* Class Constructor.
@ -65,7 +68,8 @@ public class WebServer {
if (enabled) {
return;
}
Log.info(Phrase.WEBSERVER_INIT.toString());
Log.info(Locale.get(Msg.ENABLE_WEBSERVER).toString());
try {
usingHttps = startHttpsServer();
@ -82,24 +86,28 @@ public class WebServer {
try {
URI uri = exchange.getRequestURI();
String target = uri.toString();
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/html;");
WebUser user = null;
if (usingHttps) {
user = getUser(exchange.getRequestHeaders());
// Prompt authorization
if (user == null) {
responseHeaders.set("WWW-Authenticate", "Basic realm=\"/\";");
}
}
responseHeaders.set("Content-Encoding", "gzip");
Response response = getResponse(target, user);
String content = response.getContent();
exchange.sendResponseHeaders(response.getCode(), 0);
try (BufferedOutputStream out = new BufferedOutputStream(exchange.getResponseBody());
try (GZIPOutputStream out = new GZIPOutputStream(exchange.getResponseBody());
ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes())) {
byte[] buffer = new byte[2048];
int count;
@ -115,12 +123,13 @@ public class WebServer {
}
}
});
server.setExecutor(new ThreadPoolExecutor(4, 8, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100)));
server.start();
enabled = true;
Log.info(Phrase.WEBSERVER_RUNNING.parse(String.valueOf(server.getAddress().getPort())));
Log.info(Locale.get(Msg.ENABLE_WEBSERVER_INFO).parse(server.getAddress().getPort()));
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
Log.toLog(this.getClass().getName(), e);
enabled = false;
@ -128,23 +137,27 @@ public class WebServer {
}
private WebUser getUser(Headers requestHeaders) {
Benchmark.start("getUser");
try {
List<String> authorization = requestHeaders.get("Authorization");
if (Verify.isEmpty(authorization)) {
return null;
}
String auth = authorization.get(0);
if (auth.contains("Basic ")) {
auth = auth.split(" ")[1];
} else {
throw new IllegalArgumentException("Wrong format of Auth");
}
Base64.Decoder decoder = Base64.getDecoder();
byte[] decoded = decoder.decode(auth);
String[] userInfo = new String(decoded).split(":");
if (userInfo.length != 2) {
throw new IllegalArgumentException("User and Password not specified");
}
String user = userInfo[0];
String passwordRaw = userInfo[1];
@ -153,12 +166,14 @@ public class WebServer {
throw new IllegalArgumentException("User Doesn't exist");
}
WebUser webUser = securityTable.getSecurityInfo(user);
WebUser webUser = securityTable.getWebUser(user);
boolean correctPass = PassEncryptUtil.verifyPassword(passwordRaw, webUser.getSaltedPassHash());
if (!correctPass) {
throw new IllegalArgumentException("User and Password do not match");
}
Benchmark.stop("getUser: " + requestHeaders);
return webUser;
} catch (IllegalArgumentException e) {
Log.debug("WebServer: " + e.getMessage());
@ -169,11 +184,12 @@ public class WebServer {
}
}
private boolean startHttpsServer() throws IOException {
private boolean startHttpsServer() {
String keyStorePath = Settings.WEBSERVER_CERTIFICATE_PATH.toString();
if (!Paths.get(keyStorePath).isAbsolute()) {
keyStorePath = plugin.getDataFolder() + File.separator + keyStorePath;
}
char[] storepass = Settings.WEBSERVER_CERTIFICATE_STOREPASS.toString().toCharArray();
char[] keypass = Settings.WEBSERVER_CERTIFICATE_KEYPASS.toString().toCharArray();
String alias = Settings.WEBSERVER_CERTIFICATE_ALIAS.toString();
@ -231,6 +247,7 @@ public class WebServer {
if ("/favicon.ico".equals(target)) {
return PageCacheHandler.loadPage("Redirect: favicon", () -> new RedirectResponse("https://puu.sh/tK0KL/6aa2ba141b.ico"));
}
if (usingHttps) {
if (user == null) {
return PageCacheHandler.loadPage("promptAuthorization", PromptAuthorizationResponse::new);
@ -343,7 +360,7 @@ public class WebServer {
* Shuts down the server - Async thread is closed with shutdown boolean.
*/
public void stop() {
Log.info(Phrase.WEBSERVER_CLOSE.toString());
Log.info(Locale.get(Msg.DISABLE_WEBSERVER).toString());
if (server != null) {
server.stop(0);
}

View File

@ -21,22 +21,26 @@ public class PlayersPageResponse extends Response {
public static String buildContent(List<UserData> cached) {
StringBuilder html = new StringBuilder("<!DOCTYPE html><html><body><h1>Cached Players</h1><p>");
int size = cached.size();
html.append(size)
.append(" players. Use browser's Search to find players by name. (Chrome Ctrl+F)</p><table><tr>");
cached.sort(new UserDataNameComparator());
int i = 1;
for (UserData userData : cached) {
String name = userData.getName();
String link = Html.LINK.parse(HtmlUtils.getRelativeInspectUrl(name), name);
html.append("<td>").append(link).append("</td>");
if (i < size
&& i % 8 == 0) {
if (i < size && i % 8 == 0) {
html.append("</tr><tr>");
}
i++;
}
html.append("</tr></table></body></html>");
return html.toString();
}

View File

@ -27,14 +27,14 @@ public abstract class Response {
return content;
}
public void setHeader(String header) {
this.header = header;
}
public void setContent(String content) {
this.content = content;
}
public void setHeader(String header) {
this.header = header;
}
public int getCode() {
return header == null ? 500 : Integer.parseInt(header.split(" ")[1]);
}

View File

@ -20,7 +20,6 @@ public class Benchmark {
*/
public static void start(String source) {
Plan.getInstance().benchmark().start(source);
Log.debug(source);
}
/**
@ -34,4 +33,15 @@ public class Benchmark {
}
return ms;
}
/**
* Used to add Benchmark timings to larger Debug log task parts.
*
* @param task Task this benchmark is a part of.
* @param source Bench source
* @return Execution time in ms.
*/
public static long stop(String task, String source) {
return Plan.getInstance().benchmark().stop(task, source);
}
}

View File

@ -57,7 +57,6 @@ public class Check {
public static boolean ErrorIfFalse(boolean condition, String message) {
if (!condition) {
Log.error(message);
Log.toLog(message, Log.getErrorsFilename());
}
return condition;
}

View File

@ -2,15 +2,16 @@ package main.java.com.djrapitops.plan.utilities;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.ui.webserver.WebServer;
import main.java.com.djrapitops.plan.utilities.file.FileUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
/**
* @author Rsl1122
@ -30,28 +31,7 @@ public class HtmlUtils {
* @throws FileNotFoundException
*/
public static String getStringFromResource(String fileName) throws FileNotFoundException {
InputStream resourceStream = null;
Scanner scanner = null;
try {
Plan plugin = Plan.getInstance();
File localFile = new File(plugin.getDataFolder(), fileName);
if (localFile.exists()) {
scanner = new Scanner(localFile, "UTF-8");
} else {
resourceStream = plugin.getResource(fileName);
scanner = new Scanner(resourceStream);
}
StringBuilder html = new StringBuilder();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
html.append(line).append("\r\n");
}
return html.toString();
} finally {
MiscUtils.close(resourceStream, scanner);
}
return FileUtil.getStringFromResource(fileName);
}
/**
@ -59,10 +39,10 @@ public class HtmlUtils {
* @param replaceMap
* @return
*/
public static String replacePlaceholders(String html, Map<String, String> replaceMap) {
for (Map.Entry<String, String> entrySet : replaceMap.entrySet()) {
public static String replacePlaceholders(String html, Map<String, Serializable> replaceMap) {
for (Map.Entry<String, Serializable> entrySet : replaceMap.entrySet()) {
String placeholder = entrySet.getKey();
String replacer = entrySet.getValue();
String replacer = entrySet.getValue().toString();
html = html.replace(placeholder, replacer);
}
@ -120,7 +100,7 @@ public class HtmlUtils {
*/
public static String getInspectUrl(String playerName) {
String ip = getIP();
return "//" + ip + "/player/" + playerName;
return "//" + ip + "/player/" + playerName.replace(" ", "%20").replace(".", "%2E");
}
public static String getRelativeInspectUrl(String playerName) {
@ -166,7 +146,7 @@ public class HtmlUtils {
return Html.COLUMNS_DIV_WRAPPER.parse(
Html.COLUMN_DIV_WRAPPER.parse(
Html.PLUGIN_DATA_WRAPPER.parse(
Html.NO_PLUGINS.parse()
Locale.get(Msg.HTML_NO_PLUGINS).toString()
)
)
);

View File

@ -1,17 +1,20 @@
package main.java.com.djrapitops.plan.utilities;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.command.CommandUtils;
import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.utilities.player.Fetch;
import com.djrapitops.plugin.utilities.player.IOfflinePlayer;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
/**
@ -38,6 +41,10 @@ public class MiscUtils {
return System.currentTimeMillis();
}
public static int getTimeZoneOffsetHours() {
return -TimeZone.getDefault().getOffset(MiscUtils.getTime()) / (int) TimeAmount.HOUR.ms();
}
/**
* @param args
* @param sender
@ -66,7 +73,7 @@ public class MiscUtils {
} else if (args[0].equalsIgnoreCase(sender.getName())) {
playerName = sender.getName();
} else {
sender.sendMessage(Phrase.COMMAND_NO_PERMISSION.toString());
sender.sendMessage(Locale.get(Msg.CMD_FAIL_NO_PERMISSION).toString());
}
} else {
playerName = sender.getName();
@ -82,10 +89,17 @@ public class MiscUtils {
*/
public static List<String> getMatchingPlayerNames(String search) {
final String searchFor = search.toLowerCase();
List<String> matches = Fetch.getIOfflinePlayers().stream()
.map(IOfflinePlayer::getName)
.filter(name -> name.toLowerCase().contains(searchFor))
.collect(Collectors.toList());
Database db = Plan.getInstance().getDB();
List<String> matches = new ArrayList<>();
try {
List<UserData> data = db.getUserDataForUUIDS(db.getSavedUUIDs());
matches = data.stream()
.map(UserData::getName)
.filter(name -> name.toLowerCase().contains(searchFor))
.collect(Collectors.toList());
} catch (SQLException e) {
Log.toLog("MiscUtils.getMatchingPlayerNames", e);
}
Collections.sort(matches);
return matches;
}

View File

@ -17,13 +17,6 @@ import java.security.spec.InvalidKeySpecException;
*/
public class PassEncryptUtil {
/**
* Constructor used to hide the public constructor
*/
private PassEncryptUtil() {
throw new IllegalStateException("Utility class");
}
public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
// These constants may be changed without breaking existing hashes.
public static final int SALT_BYTE_SIZE = 24;
@ -36,6 +29,12 @@ public class PassEncryptUtil {
public static final int HASH_SIZE_INDEX = 2;
public static final int SALT_INDEX = 3;
public static final int PBKDF2_INDEX = 4;
/**
* Constructor used to hide the public constructor
*/
private PassEncryptUtil() {
throw new IllegalStateException("Utility class");
}
public static String createHash(String password) throws CannotPerformOperationException {
return createHash(password.toCharArray());
@ -149,7 +148,7 @@ public class PassEncryptUtil {
return skf.generateSecret(spec).getEncoded();
} catch (NoSuchAlgorithmException ex) {
throw new CannotPerformOperationException(
"Hash algorithm not supported.", ex
"Hash algorithm not supported: " + PBKDF2_ALGORITHM, ex
);
} catch (InvalidKeySpecException ex) {
throw new CannotPerformOperationException(

View File

@ -8,7 +8,8 @@ import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.analysis.GamemodePart;
import main.java.com.djrapitops.plan.data.time.WorldTimes;
import main.java.com.djrapitops.plan.database.tables.GMTimesTable;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.html.graphs.PlayerActivityGraphCreator;
import main.java.com.djrapitops.plan.ui.html.graphs.PunchCardGraphCreator;
import main.java.com.djrapitops.plan.ui.html.graphs.SessionLengthDistributionGraphCreator;
@ -17,6 +18,7 @@ import main.java.com.djrapitops.plan.ui.html.tables.KillsTableCreator;
import main.java.com.djrapitops.plan.utilities.analysis.AnalysisUtils;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import java.io.Serializable;
import java.util.*;
/**
@ -32,14 +34,13 @@ public class PlaceholderUtils {
}
/**
* Gets the HashMap that is used to replace placeholders in Analysis.
* Gets the Map that is used to replace placeholders in Analysis.
*
* @param data AnalysisData used to replace the placeholders with
* @return HashMap that contains string for each placeholder.
*/
public static Map<String, String> getAnalysisReplaceRules(AnalysisData data) {
Benchmark.start("Replace Placeholders Analysis");
HashMap<String, String> replaceMap = new HashMap<>();
public static Map<String, Serializable> getAnalysisReplaceRules(AnalysisData data) {
HashMap<String, Serializable> replaceMap = new HashMap<>();
replaceMap.putAll(data.getReplaceMap());
replaceMap.put("%plugins%", data.replacePluginsTabLayout());
@ -48,6 +49,8 @@ public class PlaceholderUtils {
replaceMap.put("%servername%", Settings.SERVER_NAME.toString());
replaceMap.put("%timezone%", MiscUtils.getTimeZoneOffsetHours());
// Html Theme colors
String[] colors = new String[]{Settings.HCOLOR_MAIN.toString(), Settings.HCOLOR_MAIN_DARK.toString(), Settings.HCOLOR_SEC.toString(), Settings.HCOLOR_TER.toString(), Settings.HCOLOR_TER_DARK.toString()};
String[] defaultCols = new String[]{"348e0f", "267F00", "5cb239", "89c471", "5da341"};
@ -56,29 +59,29 @@ public class PlaceholderUtils {
replaceMap.put("#" + defaultCols[i], "#" + colors[i]);
}
}
Benchmark.stop("Replace Placeholders Analysis");
return replaceMap;
}
/**
* Gets the HashMap that is used to replace placeholders.
* Gets the Map that is used to replace placeholders.
*
* @param data UserData used to replace the placeholders with
* @return HashMap that contains string for each placeholder.
*/
public static Map<String, String> getInspectReplaceRules(UserData data) {
Benchmark.start("Replace Placeholders Inspect");
public static Map<String, Serializable> getInspectReplaceRules(UserData data) {
HashMap<String, Serializable> replaceMap = new HashMap<>();
replaceMap.put("%timezone%", MiscUtils.getTimeZoneOffsetHours());
HashMap<String, String> replaceMap = new HashMap<>();
boolean showIPandUUID = Settings.SECURITY_IP_UUID.isTrue();
UUID uuid = data.getUuid();
replaceMap.put("%uuid%", (showIPandUUID ? String.valueOf(uuid) : Html.HIDDEN.parse()));
replaceMap.put("%uuid%", (showIPandUUID ? uuid.toString() : "Hidden (Config)"));
replaceMap.put("%lastseen%", FormatUtils.formatTimeStampYear(data.getLastPlayed()));
replaceMap.put("%logintimes%", String.valueOf(data.getLoginTimes()));
replaceMap.put("%logintimes%", data.getLoginTimes());
replaceMap.put("%geoloc%", data.getGeolocation());
long now = MiscUtils.getTime();
boolean isActive = AnalysisUtils.isActive(now, data.getLastPlayed(), data.getPlayTime(), data.getLoginTimes());
replaceMap.put("%active%", isActive ? Html.ACTIVE.parse() : Html.INACTIVE.parse());
replaceMap.put("%active%", isActive ? Locale.get(Msg.HTML_ACTIVE).parse() : Locale.get(Msg.HTML_INACTIVE).parse());
GamemodePart gmPart = new GamemodePart();
Map<String, Long> gmTimes = data.getGmTimes().getTimes();
String[] gms = GMTimesTable.getGMKeyArray();
@ -91,18 +94,18 @@ public class PlaceholderUtils {
gmPart.analyse();
replaceMap.putAll(gmPart.getReplaceMap());
replaceMap.put("%ips%", (showIPandUUID ? data.getIps().toString() : Html.HIDDEN.parse()));
replaceMap.put("%ips%", (showIPandUUID ? data.getIps().toString() : "Hidden (Config)"));
replaceMap.put("%nicknames%", HtmlUtils.removeXSS(HtmlUtils.swapColorsToSpan(data.getNicknames().toString())));
replaceMap.put("%name%", data.getName());
replaceMap.put("%registered%", FormatUtils.formatTimeStampYear(data.getRegistered()));
replaceMap.put("%timeskicked%", "" + data.getTimesKicked());
replaceMap.put("%playtime%", FormatUtils.formatTimeAmount(data.getPlayTime()));
replaceMap.put("%banned%", data.isBanned() ? Html.BANNED.parse() : "");
replaceMap.put("%op%", data.isOp() ? Html.OPERATOR.parse() : "");
replaceMap.put("%isonline%", (data.isOnline()) ? Html.ONLINE.parse() : Html.OFFLINE.parse());
replaceMap.put("%deaths%", String.valueOf(data.getDeaths()));
replaceMap.put("%playerkills%", String.valueOf(data.getPlayerKills().size()));
replaceMap.put("%mobkills%", String.valueOf(data.getMobKills()));
replaceMap.put("%banned%", data.isBanned() ? Locale.get(Msg.HTML_BANNED).parse() : "");
replaceMap.put("%op%", data.isOp() ? Locale.get(Msg.HTML_OP).parse() : "");
replaceMap.put("%isonline%", (data.isOnline()) ? Locale.get(Msg.HTML_ONLINE).parse() : Locale.get(Msg.HTML_OFFLINE).parse());
replaceMap.put("%deaths%", data.getDeaths());
replaceMap.put("%playerkills%", data.getPlayerKills().size());
replaceMap.put("%mobkills%", data.getMobKills());
replaceMap.put("%sessionaverage%", FormatUtils.formatTimeAmount(MathUtils.averageLong(AnalysisUtils.transformSessionDataToLengths(data.getSessions()))));
replaceMap.put("%killstable%", KillsTableCreator.createKillsTable(data.getPlayerKills()));
Plan plugin = Plan.getInstance();
@ -127,13 +130,12 @@ public class PlaceholderUtils {
}
long cacheTime = plugin.getInspectCache().getCacheTime(uuid);
replaceMap.put("%refresh%", FormatUtils.formatTimeAmountDifference(cacheTime, now));
replaceMap.put("%refreshlong%", String.valueOf(cacheTime));
replaceMap.put("%refreshlong%", cacheTime);
replaceMap.put("%servername%", Settings.SERVER_NAME.toString());
String pluginsTabHtml = plugin.getHookHandler().getPluginsTabLayoutForInspect();
Map<String, String> additionalReplaceRules = plugin.getHookHandler().getAdditionalInspectReplaceRules(uuid);
Map<String, Serializable> additionalReplaceRules = plugin.getHookHandler().getAdditionalInspectReplaceRules(uuid);
String replacedOnce = HtmlUtils.replacePlaceholders(pluginsTabHtml, additionalReplaceRules);
replaceMap.put("%plugins%", HtmlUtils.replacePlaceholders(replacedOnce, additionalReplaceRules));
Benchmark.stop("Replace Placeholders Inspect");
return replaceMap;
}
}

View File

@ -3,7 +3,6 @@ package main.java.com.djrapitops.plan.utilities.analysis;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.*;
@ -16,6 +15,8 @@ import main.java.com.djrapitops.plan.data.cache.DataCacheHandler;
import main.java.com.djrapitops.plan.data.cache.InspectCacheHandler;
import main.java.com.djrapitops.plan.data.cache.PageCacheHandler;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.ui.html.tables.PlayersTableCreator;
import main.java.com.djrapitops.plan.ui.webserver.response.AnalysisPageResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.PlayersPageResponse;
@ -24,6 +25,7 @@ import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.comparators.UserDataLastPlayedComparator;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
@ -60,8 +62,8 @@ public class Analysis {
return;
}
plugin.processStatus().startExecution("Analysis");
log(Phrase.ANALYSIS_START.toString());
Benchmark.start("Analysis");
log(Locale.get(Msg.ANALYSIS_START).toString());
// Async task for Analysis
plugin.getRunnableFactory().createNew(new AbsRunnable("AnalysisTask") {
@Override
@ -83,20 +85,20 @@ public class Analysis {
* @return Whether or not analysis was successful.
*/
public boolean analyze(AnalysisCacheHandler analysisCache, Database db) {
log(Phrase.ANALYSIS_FETCH_DATA.toString());
Benchmark.start("Analysis: Fetch Phase");
log(Locale.get(Msg.ANALYSIS_FETCH).toString());
Benchmark.start("Fetch Phase");
Log.debug("Database", "Analysis Fetch");
plugin.processStatus().setStatus("Analysis", "Analysis Fetch Phase");
try {
inspectCache.cacheAllUserData(db);
} catch (Exception ex) {
Log.toLog(this.getClass().getName(), ex);
Log.error(Phrase.ERROR_ANALYSIS_FETCH_FAIL.toString());
Log.error(Locale.get(Msg.ANALYSIS_FAIL_FETCH_EXCEPTION).toString());
}
List<UserData> rawData = inspectCache.getCachedUserData();
if (rawData.isEmpty()) {
Log.info(Phrase.ANALYSIS_FAIL_NO_DATA.toString());
Log.info(Locale.get(Msg.ANALYSIS_FAIL_NO_DATA).toString());
return false;
}
@ -104,7 +106,8 @@ public class Analysis {
try {
tpsData = db.getTpsTable().getTPSData();
Log.debug("TPS Data Size: " + tpsData.size());
Log.debug("Analysis", "Raw Data Size: " + rawData.size());
Log.debug("Analysis", "TPS Data Size: " + tpsData.size());
} catch (Exception ex) {
Log.toLog(this.getClass().getName(), ex);
}
@ -122,7 +125,7 @@ public class Analysis {
try {
rawData.sort(new UserDataLastPlayedComparator());
List<UUID> uuids = rawData.stream().map(UserData::getUuid).collect(Collectors.toList());
Benchmark.start("Analysis: Create Empty dataset");
Benchmark.start("Create Empty dataset");
DataCacheHandler handler = plugin.getHandler();
Map<String, Integer> commandUse = handler.getCommandUse();
@ -134,12 +137,12 @@ public class Analysis {
analysisData.getPlayerCountPart().addPlayers(uuids);
activityPart.setRecentPlayers(rawData.stream().map(UserData::getName).collect(Collectors.toList()));
Benchmark.stop("Analysis: Create Empty dataset");
long fetchPhaseLength = Benchmark.stop("Analysis: Fetch Phase");
Benchmark.stop("Analysis", "Create Empty dataset");
long fetchPhaseLength = Benchmark.stop("Analysis", "Fetch Phase");
Benchmark.start("Analysis Phase");
plugin.processStatus().setStatus("Analysis", "Analysis Phase");
log(Phrase.ANALYSIS_BEGIN_ANALYSIS.parse(String.valueOf(rawData.size()), String.valueOf(fetchPhaseLength)));
log(Locale.get(Msg.ANALYSIS_PHASE_START).parse(rawData.size(), fetchPhaseLength));
String playersTable = PlayersTableCreator.createSortablePlayersTable(rawData);
analysisData.setPlayersTable(playersTable);
@ -147,22 +150,24 @@ public class Analysis {
fillDataset(analysisData, rawData);
// Analyze
analysisData.analyseData();
Benchmark.stop("Analysis Phase");
Benchmark.stop("Analysis", "Analysis Phase");
log(Phrase.ANALYSIS_THIRD_PARTY.toString());
log(Locale.get(Msg.ANALYSIS_3RD_PARTY).toString());
plugin.processStatus().setStatus("Analysis", "Analyzing additional data sources (3rd party)");
analysisData.setAdditionalDataReplaceMap(analyzeAdditionalPluginData(uuids));
analysisCache.cache(analysisData);
long time = plugin.processStatus().finishExecution("Analysis");
long time = Benchmark.stop("Analysis", "Analysis");
Log.logDebug("Analysis", time);
if (Settings.ANALYSIS_LOG_FINISHED.isTrue()) {
Log.info(Phrase.ANALYSIS_COMPLETE.parse(String.valueOf(time), HtmlUtils.getServerAnalysisUrlWithProtocol()));
Log.info(Locale.get(Msg.ANALYSIS_FINISHED).parse(String.valueOf(time), HtmlUtils.getServerAnalysisUrlWithProtocol()));
}
ExportUtility.export(plugin, analysisData, rawData);
PageCacheHandler.cachePage("analysisPage", () -> new AnalysisPageResponse(plugin.getUiServer().getDataReqHandler()));
PageCacheHandler.cachePage("players", () -> new PlayersPageResponse(plugin));
ExportUtility.export(plugin, analysisData, rawData);
} catch (Exception e) {
Log.toLog(this.getClass().getName(), e);
plugin.processStatus().setStatus("Analysis", "Error: " + e);
@ -177,11 +182,12 @@ public class Analysis {
}
}
private Map<String, String> analyzeAdditionalPluginData(List<UUID> uuids) {
Benchmark.start("Analysis: 3rd party");
final Map<String, String> replaceMap = new HashMap<>();
private Map<String, Serializable> analyzeAdditionalPluginData(List<UUID> uuids) {
Benchmark.start("3rd party");
final Map<String, Serializable> replaceMap = new HashMap<>();
final HookHandler hookHandler = plugin.getHookHandler();
final List<PluginData> sources = hookHandler.getAdditionalDataSources().stream()
.filter(p -> !p.isBanData())
.filter(p -> !p.getAnalysisTypes().isEmpty())
.collect(Collectors.toList());
final AnalysisType[] totalTypes = new AnalysisType[]{
@ -192,7 +198,7 @@ public class Analysis {
};
final AnalysisType bool = AnalysisType.BOOLEAN_PERCENTAGE;
final AnalysisType boolTot = AnalysisType.BOOLEAN_TOTAL;
Log.debug("Analyzing additional sources: " + sources.size());
Log.debug("Analysis", "Additional Sources: " + sources.size());
sources.parallelStream().filter(Verify::notNull).forEach(source -> {
try {
Benchmark.start("Source " + source.getPlaceholder("").replace("%", ""));
@ -225,10 +231,10 @@ public class Analysis {
Log.toLog(this.getClass().getName(), e);
} finally {
Benchmark.stop("Source " + source.getPlaceholder("").replace("%", ""));
Benchmark.stop("Analysis", "Source " + source.getPlaceholder("").replace("%", ""));
}
});
Benchmark.stop("Analysis: 3rd party");
Benchmark.stop("Analysis", "3rd party");
return replaceMap;
}
@ -260,7 +266,9 @@ public class Analysis {
long now = MiscUtils.getTime();
Benchmark.start("Analysis: Fill Dataset");
Benchmark.start("Fill Dataset");
List<PluginData> banSources = plugin.getHookHandler().getAdditionalDataSources()
.stream().filter(PluginData::isBanData).collect(Collectors.toList());
rawData.forEach(uData -> {
uData.access();
Map<String, Long> gmTimes = uData.getGmTimes().getTimes();
@ -289,7 +297,20 @@ public class Analysis {
if (uData.isOp()) {
playerCount.addOP(uuid);
}
if (uData.isBanned()) {
boolean banned = uData.isBanned();
if (!banned) {
banned = banSources.stream()
.anyMatch(banData -> {
Serializable value = banData.getValue(uuid);
if (value instanceof Boolean) {
return (Boolean) value;
}
return false;
});
}
if (banned) {
activity.addBan(uuid);
} else if (uData.getLoginTimes() == 1) {
activity.addJoinedOnce(uuid);
@ -307,6 +328,6 @@ public class Analysis {
joinInfo.addSessions(uuid, sessions);
uData.stopAccessing();
});
Benchmark.stop("Analysis: Fill Dataset");
Benchmark.stop("Analysis", "Fill Dataset");
}
}

View File

@ -201,8 +201,7 @@ public class AnalysisUtils {
private static String logPluginDataCausedError(PluginData source, Throwable e) {
Log.error("A PluginData-source caused an exception: " + source.getPlaceholder("").replace("%", ""));
Log.toLog("A PluginData-source caused an exception: " + source.getPlaceholder("").replace("%", ""), Log.getErrorsFilename());
Log.toLog("com.djrapitops.plan.utilities.AnalysisUtils", e);
Log.toLog("PluginData-source caused an exception: " + source.getPlaceholder("").replace("%", ""), e);
return source.parseContainer("", "Exception during calculation.");
}

View File

@ -6,6 +6,7 @@ import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.AnalysisData;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.ui.webserver.response.PlayersPageResponse;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.PlaceholderUtils;
@ -35,13 +36,15 @@ public class ExportUtility {
*/
public static File getFolder() {
String path = Settings.ANALYSIS_EXPORT_PATH.toString();
if (Paths.get(path).isAbsolute()) {
Log.debug("Export", "Path: " + path);
boolean isAbsolute = Paths.get(path).isAbsolute();
Log.debug("Export", "Absolute: " + (isAbsolute ? "Yes" : "No"));
if (isAbsolute) {
File folder = new File(path);
if (folder.exists()
&& folder.isDirectory()) {
return folder;
if (!folder.exists() || !folder.isDirectory()) {
folder.mkdirs();
}
folder.mkdirs();
return folder;
}
File dataFolder = Plan.getInstance().getDataFolder();
@ -59,21 +62,24 @@ public class ExportUtility {
if (!Settings.ANALYSIS_EXPORT.isTrue()) {
return;
}
String processName = "Exporting Html pages";
plugin.processStatus().startExecution(processName);
Benchmark.start("Exporting Html pages");
try {
File folder = getFolder();
Log.debug("Export", "Folder: " + folder.getAbsolutePath());
writePlayersPageHtml(rawData, new File(folder, "players"));
writeAnalysisHtml(analysisData, new File(folder, "server"));
File playersFolder = getPlayersFolder(folder);
plugin.processStatus().setStatus(processName, "Player html files.");
for (UserData userData : rawData) {
writeInspectHtml(userData, playersFolder);
}
Log.debug("Export", "Player html files.");
Log.debug("Export", "Player Page Folder: " + playersFolder.getAbsolutePath());
String playerHtml = HtmlUtils.getStringFromResource("player.html");
rawData.forEach(userData -> {
writeInspectHtml(userData, playersFolder, playerHtml);
});
} catch (IOException ex) {
Log.toLog("ExportUtils.export", ex);
} finally {
plugin.processStatus().finishExecution(processName);
Benchmark.stop("Export", "Exporting Html pages");
Log.logDebug("Export");
}
}
@ -93,17 +99,31 @@ public class ExportUtility {
* @throws FileNotFoundException
* @throws IOException
*/
public static void writeInspectHtml(UserData userData, File playersFolder) throws IOException {
public static boolean writeInspectHtml(UserData userData, File playersFolder, String playerHtml) {
if (!Settings.ANALYSIS_EXPORT.isTrue()) {
return;
return false;
}
String inspectHtml = HtmlUtils.replacePlaceholders(HtmlUtils.getStringFromResource("player.html"),
PlaceholderUtils.getInspectReplaceRules(userData));
File playerFolder = new File(playersFolder, userData.getName());
playerFolder.mkdir();
File inspectHtmlFile = new File(playerFolder, "index.html");
inspectHtmlFile.delete();
Files.write(inspectHtmlFile.toPath(), Collections.singletonList(inspectHtml));
String name = userData.getName();
if (name.endsWith(".")) {
name = name.replace(".", "%2E");
}
if (name.endsWith(" ")) {
name = name.replace(" ", "%20");
}
try {
String inspectHtml = HtmlUtils.replacePlaceholders(playerHtml,
PlaceholderUtils.getInspectReplaceRules(userData));
File playerFolder = new File(playersFolder, name);
playerFolder.mkdirs();
File inspectHtmlFile = new File(playerFolder, "index.html");
inspectHtmlFile.createNewFile();
Files.write(inspectHtmlFile.toPath(), Collections.singletonList(inspectHtml));
} catch (IOException e) {
Log.toLog("Export.inspectPage: " + name, e);
return false;
}
return true;
}
/**
@ -116,12 +136,13 @@ public class ExportUtility {
if (!Settings.ANALYSIS_EXPORT.isTrue()) {
return;
}
serverFolder.mkdirs();
String analysisHtml = HtmlUtils.replacePlaceholders(HtmlUtils.getStringFromResource("analysis.html"),
PlaceholderUtils.getAnalysisReplaceRules(analysisData))
.replace(HtmlUtils.getInspectUrl(""), "../player/");
File analysisHtmlFile = new File(serverFolder, "index.html");
analysisHtmlFile.delete();
Log.debug("Export", "Analysis Page File: " + analysisHtmlFile.getAbsolutePath());
analysisHtmlFile.createNewFile();
Files.write(analysisHtmlFile.toPath(), Collections.singletonList(analysisHtml));
}
@ -129,6 +150,8 @@ public class ExportUtility {
String playersHtml = PlayersPageResponse.buildContent(rawData);
playersFolder.mkdirs();
File playersHtmlFile = new File(playersFolder, "index.html");
Log.debug("Export", "Players Page File: " + playersHtmlFile.getAbsolutePath());
playersHtmlFile.createNewFile();
Files.write(playersHtmlFile.toPath(), Collections.singletonList(playersHtml));
}

View File

@ -11,6 +11,8 @@ import java.util.stream.Stream;
*/
public class MathUtils {
private static final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
private static final DecimalFormat decimalFormat = new DecimalFormat("#.##", decimalFormatSymbols);
/**
* Constructor used to hide the public constructor
*/
@ -18,9 +20,6 @@ public class MathUtils {
throw new IllegalStateException("Utility class");
}
private static final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
private static final DecimalFormat decimalFormat = new DecimalFormat("#.##", decimalFormatSymbols);
/**
* Gets the average of a Stream of Integers.
* If there are no components in the Stream, it will return 0.

View File

@ -0,0 +1,22 @@
package main.java.com.djrapitops.plan.utilities.comparators;
import main.java.com.djrapitops.plan.locale.Message;
import main.java.com.djrapitops.plan.locale.Msg;
import org.apache.commons.lang3.StringUtils;
import java.util.Comparator;
import java.util.Map;
/**
* Compares Locale Map Entries and sorts them alphabetically according to the Enum Names.
*
* @since 3.6.2
* @author Rsl1122
*/
public class LocaleEntryComparator implements Comparator<Map.Entry<Msg, Message>> {
@Override
public int compare(Map.Entry<Msg, Message> o1, Map.Entry<Msg, Message> o2) {
return StringUtils.compare(o1.getKey().name(), o2.getKey().name());
}
}

View File

@ -0,0 +1,17 @@
package main.java.com.djrapitops.plan.utilities.comparators;
import java.util.Comparator;
/**
* Compares Strings & sorts them by length
*
* @author Rsl1122
* @since 3.6.2
*/
public class StringLengthComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return -Integer.compare(o1.length(), o2.length());
}
}

View File

@ -0,0 +1,58 @@
package main.java.com.djrapitops.plan.utilities.file;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FileUtil {
public static String getStringFromResource(String fileName) throws FileNotFoundException {
InputStream resourceStream = null;
Scanner scanner = null;
try {
Plan plugin = Plan.getInstance();
File localFile = new File(plugin.getDataFolder(), fileName);
if (localFile.exists()) {
scanner = new Scanner(localFile, "UTF-8");
} else {
resourceStream = plugin.getResource(fileName);
scanner = new Scanner(resourceStream);
}
StringBuilder html = new StringBuilder();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
html.append(line).append("\r\n");
}
return html.toString();
} finally {
MiscUtils.close(resourceStream, scanner);
}
}
public static List<String> lines(JavaPlugin plugin, String resource) throws IOException {
List<String> lines = new ArrayList<>();
Scanner scanner = null;
try (InputStream inputStream = plugin.getResource(resource)) {
scanner = new Scanner(inputStream, "UTF-8");
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());
}
} catch (NullPointerException e) {
throw new FileNotFoundException("File not found inside jar: " + resource);
} finally {
MiscUtils.close(scanner);
}
return lines;
}
}

View File

@ -0,0 +1,137 @@
package main.java.com.djrapitops.plan.utilities.file.dump;
import main.java.com.djrapitops.plan.Log;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Fuzzlemann
* @since 3.7.0
*/
public class DumpLog {
private List<CharSequence> lines = new ArrayList<>();
/**
* Writes a header
*
* @param header The name of the header
*/
void addHeader(String header) {
addLine("");
addLine("--- " + header + " ---");
}
/**
* Adds a String {@code value} to a String {@code key}
*
* @param key The key
* @param value The value
*/
void add(String key, String value) {
addLine(key + ": " + value);
}
/**
* Adds a boolean {@code value} to a String {@code key}
*
* @param key The key
* @param value The value
*/
void add(String key, boolean value) {
addLine(key + ": " + value);
}
/**
* Adds multiple {@link CharSequence CharSequences} stored in an {@link Iterable}
* to a String {@code key}
*
* @param key The key
* @param value The CharSequences stored in an Iterable
*/
void add(String key, Iterable<? extends CharSequence> value) {
addLine(key + ": " + String.join(", ", value));
}
/**
* Adds multiple lines
*
* @param lines The CharSequences stored in an Iterable
*/
void addLines(Iterable<? extends CharSequence> lines) {
lines.forEach(this::addLine);
}
/**
* Adds multiple lines
*
* @param lines The lines
*/
void addLines(CharSequence... lines) {
Arrays.stream(lines).forEach(this::addLine);
}
/**
* Adds one line
*
* @param line The content of the line
*/
private void addLine(CharSequence line) {
lines.add(line.toString());
}
/**
* Uploads the dump log to Hastebin using HTTPS and POST
*
* @return The link to the Dump Log
*/
String upload() {
String content = this.toString();
HttpsURLConnection connection = null;
try {
URL url = new URL("https://hastebin.com/documents");
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Content-length", String.valueOf(content.length()));
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("User-Agent", "Mozilla/4.0");
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(this.toString());
wr.flush();
wr.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(rd.readLine());
return "https://hastebin.com/" + json.get("key");
} catch (IOException | ParseException e) {
Log.toLog("DumpLog.upload", e);
return "Error";
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
@Override
public String toString() {
return String.join("\n", lines);
}
}

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