[3.5.5] Merge pull request #181 from Rsl1122/3.5.5

Pull Request for 3.5.5
This commit is contained in:
Rsl1122 2017-07-26 11:16:30 +03:00 committed by GitHub
commit fc814b1d1b
179 changed files with 3796 additions and 2943 deletions

View File

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="Maven: com.destroystokyo.paper:paper:1.12-R0.1-SNAPSHOT">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/destroystokyo/paper/paper/1.12-R0.1-SNAPSHOT/paper-1.12-R0.1-20170725.202533-1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/destroystokyo/paper/paper/1.12-R0.1-SNAPSHOT/paper-1.12-R0.1-20170725.202533-1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/destroystokyo/paper/paper/1.12-R0.1-SNAPSHOT/paper-1.12-R0.1-20170725.202533-1-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

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

View File

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

View File

@ -0,0 +1,8 @@
<component name="ProjectDictionaryState">
<dictionary name="Risto">
<words>
<w>ramer</w>
<w>throwables</w>
</words>
</dictionary>
</component>

View File

@ -0,0 +1,29 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="EmptyMethod" enabled="true" level="WARNING" enabled_by_default="true">
<option name="EXCLUDE_ANNOS">
<value>
<list size="15">
<item index="0" class="java.lang.String" itemvalue="org.junit.After" />
<item index="1" class="java.lang.String" itemvalue="org.junit.After" />
<item index="2" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="3" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="4" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="5" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="6" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="7" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="8" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="9" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="10" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="11" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="12" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="13" class="java.lang.String" itemvalue="org.junit.Ignore" />
<item index="14" class="java.lang.String" itemvalue="org.junit.Ignore" />
</list>
</value>
</option>
<option name="commentsAreContent" value="false" />
</inspection_tool>
</profile>
</component>

View File

@ -1,28 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.djrapitops</groupId>
<artifactId>Plan</artifactId>
<version>3.5.4</version>
<version>3.5.5</version>
<packaging>jar</packaging>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
<id>plan-repo</id>
<url>http://repo.fuzzlemann.de/artifactory/libs-release/</url>
</repository>
<repository>
<id>plan-snapshot-repo</id>
<url>http://repo.fuzzlemann.de/artifactory/libs-snapshot/</url>
</repository>
</repositories>
<dependencies>
<!-- Spigot 1.12 built with Buildtools for Database classes.-->
<!-- PaperSpigot 1.12 built with Buildtools for Database classes.-->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<groupId>com.destroystokyo.paper</groupId>
<artifactId>paper</artifactId>
<version>1.12-R0.1-20170725.202533-1</version>
<scope>provided</scope>
</dependency>
<!-- Framework for easier plugin development-->
<!-- Framework for easier plugin development-->
<dependency>
<groupId>com.djrapitops</groupId>
<artifactId>AbstractPluginFramework</artifactId>
<artifactId>abstract-plugin-framework</artifactId>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
@ -33,7 +38,7 @@
<version>3.5.0</version>
<scope>compile</scope>
</dependency>
<!-- -->
<!-- -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock</artifactId>
@ -66,7 +71,7 @@
<version>1.10.19</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
@ -88,9 +93,9 @@
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
</dependency>
</dependencies>
<build>
<defaultGoal>clean package install</defaultGoal>
<finalName>${project.name}</finalName>
@ -146,7 +151,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<version>2.6</version>
<configuration>
<excludes>
<exclude>**/test/*</exclude>
@ -154,7 +159,7 @@
<exclude>**/*/test.*</exclude>
<exclude>**/test/**/*</exclude>
</excludes>
</configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.pitest</groupId>

View File

@ -5,7 +5,7 @@ import java.util.Collection;
/**
* This class manages the messages going to the Console Logger.
*
* Methods of Abtract Plugin Framework log utility are used.
* Methods of Abstract Plugin Framework log utility are used.
*
* @author Rsl1122
* @since 3.0.0
@ -22,7 +22,7 @@ public class Log {
}
/**
* Sends a message to the console with the chatcolors.
* Sends a message to the console with the ChatColors.
*
* @param message Message to send.
*/

View File

@ -29,7 +29,7 @@ public enum Permissions {
private final String permission;
private Permissions(String permission) {
Permissions(String permission) {
this.permission = permission;
}

View File

@ -177,12 +177,12 @@ public enum Phrase {
private String text;
private ChatColor color;
private Phrase(String text) {
Phrase(String text) {
this.text = text;
this.color = null;
}
private Phrase(ChatColor color) {
Phrase(ChatColor color) {
this.color = color;
this.text = "";
}

View File

@ -25,33 +25,31 @@ import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.ITask;
import com.djrapitops.plugin.utilities.Verify;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.HashSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import main.java.com.djrapitops.plan.api.API;
import main.java.com.djrapitops.plan.command.PlanCommand;
import main.java.com.djrapitops.plan.command.commands.RegisterCommandFilter;
import main.java.com.djrapitops.plan.data.additional.HookHandler;
import main.java.com.djrapitops.plan.data.cache.*;
import main.java.com.djrapitops.plan.data.cache.AnalysisCacheHandler;
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.listeners.*;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.database.databases.*;
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.ui.webserver.WebSocketServer;
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.bukkit.Bukkit;
import java.io.*;
import java.net.URL;
import java.util.HashSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
/**
* Main class for Bukkit that manages the plugin.
*
@ -148,7 +146,7 @@ public class Plan extends BukkitPlugin<Plan> {
}
Benchmark.stop("Enable: Analysis refresh task registration");
Benchmark.start("Enable: Webserver Initialization");
Benchmark.start("Enable: WebServer Initialization");
// Data view settings
boolean webserverIsEnabled = Settings.WEBSERVER_ENABLED.isTrue();
boolean usingAlternativeIP = Settings.SHOW_ALTERNATIVE_IP.isTrue();
@ -166,7 +164,7 @@ public class Plan extends BukkitPlugin<Plan> {
if (!usingAlternativeIP && serverVariableHolder.getIp().isEmpty()) {
Log.infoColor(Phrase.NOTIFY_EMPTY_IP + "");
}
Benchmark.stop("Enable: Webserver Initialization");
Benchmark.stop("Enable: WebServer Initialization");
registerCommand(new PlanCommand(this));
@ -174,7 +172,10 @@ public class Plan extends BukkitPlugin<Plan> {
hookHandler = new HookHandler(this);
Benchmark.stop("Enable: Hook to 3rd party plugins");
Log.debug("Verboose debug messages are enabled.");
BStats bStats = new BStats(this);
bStats.registerMetrics();
Log.debug("Verbose debug messages are enabled.");
Log.info(Phrase.ENABLED + "");
processStatus().finishExecution("Enable");
}
@ -193,7 +194,7 @@ public class Plan extends BukkitPlugin<Plan> {
getServer().getScheduler().cancelTasks(this);
if (Verify.notNull(handler, db)) {
Benchmark.start("Disable: DataCache Save");
// Saves the datacache to the database without Bukkit's Schedulers.
// Saves the DataCache to the database without Bukkit's Schedulers.
Log.info(Phrase.CACHE_SAVE + "");
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.execute(() -> {
@ -335,7 +336,7 @@ public class Plan extends BukkitPlugin<Plan> {
URL localeURL = new URL("https://raw.githubusercontent.com/Rsl1122/Plan-PlayerAnalytics/master/Plan/localization/locale_" + locale + ".txt");
InputStream inputStream = localeURL.openStream();
OutputStream outputStream = new FileOutputStream(localeFile);
int read = 0;
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);

View File

@ -13,6 +13,7 @@ public class ServerVariableHolder {
private final int maxPlayers;
private final String ip;
private final boolean usingPaper;
/**
* Constructor, grabs the variables.
@ -22,6 +23,7 @@ public class ServerVariableHolder {
public ServerVariableHolder(Server server) {
maxPlayers = server.getMaxPlayers();
ip = server.getIp();
usingPaper = server.getName().equals("Paper");
}
/**
@ -41,4 +43,13 @@ public class ServerVariableHolder {
public String getIp() {
return ip;
}
/**
* Returns if the server is using PaperSpigot.
*
* @return if the server is using PaperSpigot.
*/
public boolean isUsingPaper() {
return usingPaper;
}
}

View File

@ -23,6 +23,8 @@ public enum Settings {
GATHERKILLS("Settings.Data.GatherKillData"),
GATHERGMTIMES("Settings.Data.GamemodeChangeListener"),
GATHERCOMMANDS("Settings.Data.GatherCommandUsage"),
DO_NOT_LOG_UNKNOWN_COMMANDS("Customization.Data.DoNotLogUnknownCommands"),
COMBINE_COMMAND_ALIASES_TO_MAIN_COMMAND("Customization.Data.CombineCommandAliasesToMainCommand"),
SECURITY_IP_UUID("Settings.WebServer.Security.DisplayIPsAndUUIDs"),
GRAPH_PLAYERS_USEMAXPLAYERS_SCALE("Customization.Graphs.PlayersOnlineGraph.UseMaxPlayersAsScale"),
PLAYERLIST_SHOW_IMAGES("Customization.SmallHeadImagesOnAnalysisPlayerlist"),
@ -86,7 +88,7 @@ public enum Settings {
private final String configPath;
private Boolean value;
private Settings(String path) {
Settings(String path) {
this.configPath = path;
}

View File

@ -4,13 +4,6 @@ import com.djrapitops.plugin.utilities.Verify;
import com.djrapitops.plugin.utilities.player.Fetch;
import com.djrapitops.plugin.utilities.player.IOfflinePlayer;
import com.djrapitops.plugin.utilities.player.UUIDFetcher;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.AnalysisData;
import main.java.com.djrapitops.plan.data.UserData;
@ -22,15 +15,23 @@ import main.java.com.djrapitops.plan.ui.html.DataRequestHandler;
import main.java.com.djrapitops.plan.ui.webserver.WebSocketServer;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* This class contains the API methods.
*
* Methods can be called from Asyncronous task and are thread safe unless
* Methods can be called from Asynchronous task and are thread safe unless
* otherwise stated.
*
* Use Plan.getPlanAPI() to get the API.
*
* More information about API methods can be found on Github.
* More information about API methods can be found on GitHub.
*
* @author Rsl1122
* @since 2.0.0
@ -44,7 +45,7 @@ public class API {
private final Plan plugin;
/**
* Class Construcor.
* Class Constructor.
*
* @param plugin Current instance of Plan
*/
@ -65,7 +66,7 @@ public class API {
* Add a source of plugin data to the Plugins tab on Analysis and/or Inspect
* page.
*
* Refer to documentation on github or Javadoc of PluginData to set-up a
* Refer to documentation on GitHub or Javadoc of PluginData to set-up a
* data source that extends PluginData correctly.
*
* @param dataSource an object that extends PluginData-object, thus allowing
@ -102,7 +103,7 @@ public class API {
*
* @param uuid UUID of the player.
* @param processor Object implementing DBCallableProcessor, which
* process(UserData data) method will be called.
* process (UserData data) method will be called.
*/
public void scheduleForGet(UUID uuid, DBCallableProcessor processor) {
plugin.getHandler().getUserDataForProcessing(processor, uuid, false);
@ -135,7 +136,7 @@ public class API {
/**
* Used to save the cached data to the database.
*
* Should be only called from an Asyncronous thread.
* Should be only called from an Asynchronous thread.
*/
public void saveCachedData() {
plugin.getHandler().saveCachedUserData();
@ -154,7 +155,7 @@ public class API {
/**
* Cache the UserData to InspectCache.
*
* Uses cache if data is cached or database if not. Call from an Asyncronous
* Uses cache if data is cached or database if not. Call from an Asynchronous
* thread.
*
* @param uuid UUID of the player.
@ -193,14 +194,14 @@ public class API {
* Run's the analysis with the current data in the cache and fetches rest
* from the database.
*
* Starts a new Asyncronous task to run the analysis.
* Starts a new Asynchronous task to run the analysis.
*/
public void updateAnalysisCache() {
plugin.getAnalysisCache().updateCache();
}
/**
* Used to get the full Html of the Analysis page as a string.
* Used to get the full HTML of the Analysis page as a string.
*
* Check if the data is cached to AnalysisCache before calling this.
*

View File

@ -1,10 +1,11 @@
package main.java.com.djrapitops.plan.command;
import com.djrapitops.plugin.utilities.Verify;
import java.util.UUID;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import java.util.UUID;
/**
* This class contains methods used by commands
*
@ -32,9 +33,6 @@ public class ConditionUtils {
* @return has the player played before, false if uuid is null.
*/
public static boolean playerHasPlayed(UUID uuid) {
if (!Verify.notNull(uuid)) {
return false;
}
return Plan.getInstance().fetch().hasPlayedBefore(uuid);
return Verify.notNull(uuid) && Plan.getInstance().fetch().hasPlayedBefore(uuid);
}
}

View File

@ -39,7 +39,7 @@ public class PlanCommand extends TreeCommand<Plan> {
commands.add(new InfoCommand(plugin));
commands.add(new ReloadCommand(plugin));
commands.add(new ManageCommand(plugin));
commands.add(new StatusCommand(plugin, Permissions.MANAGE.getPermission()));
commands.add(new StatusCommand<>(plugin, Permissions.MANAGE.getPermission()));
if (plugin.getUiServer().isEnabled()) {
commands.add(new ListCommand(plugin));
RegisterCommand registerCommand = new RegisterCommand(plugin);

View File

@ -45,10 +45,10 @@ public class AnalyzeCommand extends SubCommand {
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Phrase.ERROR_WEBSERVER_OFF_ANALYSIS + "", sender)) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Phrase.ERROR_WEBSERVER_OFF_ANALYSIS.toString(), sender)) {
return true;
}
if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Phrase.ERROR_ANALYSIS_DISABLED_TEMPORARILY + "", sender)) {
if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Phrase.ERROR_ANALYSIS_DISABLED_TEMPORARILY.toString(), sender)) {
if (!analysisCache.isCached()) {
return true;
}
@ -89,17 +89,17 @@ public class AnalyzeCommand extends SubCommand {
private void runMessageSenderTask(ISender sender) {
plugin.getRunnableFactory().createNew("AnalysisMessageSenderTask", new AbsRunnable() {
private int timesrun = 0;
private int timesRun = 0;
@Override
public void run() {
timesrun++;
timesRun++;
if (analysisCache.isCached() && (!analysisCache.isAnalysisBeingRun() || !analysisCache.isAnalysisEnabled())) {
sendAnalysisMessage(sender);
this.cancel();
return;
}
if (timesrun > 10) {
if (timesRun > 10) {
Log.debug("Command Timeout Message, Analysis.");
sender.sendMessage(Phrase.COMMAND_TIMEOUT.parse("Analysis"));
this.cancel();
@ -117,13 +117,13 @@ public class AnalyzeCommand extends SubCommand {
*/
private void sendAnalysisMessage(ISender sender) {
boolean textUI = Settings.USE_ALTERNATIVE_UI.isTrue();
sender.sendMessage(Phrase.CMD_ANALYZE_HEADER + "");
sender.sendMessage(Phrase.CMD_ANALYZE_HEADER.toString());
if (textUI) {
sender.sendMessage(TextUI.getAnalysisMessages());
} else {
// Link
String url = HtmlUtils.getServerAnalysisUrlWithProtocol();
String message = Phrase.CMD_LINK + "";
String message = Phrase.CMD_LINK.toString();
boolean console = !CommandUtils.isPlayer(sender);
if (console) {
sender.sendMessage(message + url);

View File

@ -25,7 +25,7 @@ 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 + "");
super("info", CommandType.CONSOLE, Permissions.INFO.getPermission(), Phrase.CMD_USG_INFO.toString());
this.plugin = plugin;
}
@ -34,11 +34,11 @@ public class InfoCommand extends SubCommand {
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
ChatColor tColor = Phrase.COLOR_SEC.color();
String[] messages = {
Phrase.CMD_INFO_HEADER + "",
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 + ""
Phrase.CMD_FOOTER.toString()
};
sender.sendMessage(messages);
return true;

View File

@ -7,13 +7,7 @@ import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import java.sql.SQLException;
import java.util.UUID;
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.Settings;
import main.java.com.djrapitops.plan.*;
import main.java.com.djrapitops.plan.command.ConditionUtils;
import main.java.com.djrapitops.plan.data.cache.InspectCacheHandler;
import main.java.com.djrapitops.plan.ui.text.TextUI;
@ -25,6 +19,9 @@ import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandException;
import java.sql.SQLException;
import java.util.UUID;
/**
* This command is used to cache UserData to InspectCache and display the link.
*
@ -42,7 +39,7 @@ 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 + "", Phrase.ARG_PLAYER + "");
super("inspect", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.INSPECT.getPermission(), Phrase.CMD_USG_INSPECT.toString(), Phrase.ARG_PLAYER.toString());
this.plugin = plugin;
inspectCache = plugin.getInspectCache();
@ -50,7 +47,7 @@ public class InspectCommand extends SubCommand {
@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(), Phrase.ERROR_WEBSERVER_OFF_INSPECT.toString(), sender)) {
return true;
}

View File

@ -66,18 +66,18 @@ public class QuickAnalyzeCommand extends SubCommand {
private void runMessageSenderTask(ISender sender) {
plugin.getRunnableFactory().createNew(new AbsRunnable("QanalysisMessageSenderTask") {
private int timesrun = 0;
private int timesRun = 0;
@Override
public void run() {
timesrun++;
timesRun++;
if (analysisCache.isCached() && (!analysisCache.isAnalysisBeingRun() || !analysisCache.isAnalysisEnabled())) {
sender.sendMessage(Phrase.CMD_ANALYZE_HEADER + "");
sender.sendMessage(TextUI.getAnalysisMessages());
sender.sendMessage(Phrase.CMD_FOOTER + "");
this.cancel();
}
if (timesrun > 10) {
if (timesRun > 10) {
Log.debug("Command Timeout Message, QuickAnalyze.");
sender.sendMessage(Phrase.COMMAND_TIMEOUT.parse("Analysis"));
this.cancel();

View File

@ -43,7 +43,7 @@ public class RegisterCommand extends SubCommand {
String permLvlErrorMsg = ChatColor.RED + "Incorrect perm level, not a number: ";
try {
if (CommandUtils.isPlayer(sender)) {
Log.info(sender.getName()+" issued WebUser register command.");
Log.info(sender.getName() + " issued WebUser register command.");
playerRegister(args, sender);
} else {
consoleRegister(args, sender, notEnoughArgsMsg);
@ -74,11 +74,6 @@ public class RegisterCommand extends SubCommand {
if (registerSenderAsUser) {
String user = sender.getName();
String pass = PassEncryptUtil.createHash(args[0]);
if (!Check.isTrue(pass != null, ChatColor.RED + "Password hash error.", sender)) {
return;
}
int permLvl = getPermissionLevel(sender);
registerUser(new WebUser(user, pass, permLvl), sender);
} else if (sender.hasPermission(Permissions.MANAGE_WEB.getPermission())) {
@ -119,7 +114,7 @@ public class RegisterCommand extends SubCommand {
}
securityTable.addNewUser(webUser);
sender.sendMessage(successMsg);
Log.info("Registered new user: "+userName+" Perm level: "+webUser.getPermLevel());
Log.info("Registered new user: " + userName + " Perm level: " + webUser.getPermLevel());
} catch (Exception e) {
Log.toLog(this.getClass().getName(), e);
} finally {

View File

@ -29,7 +29,7 @@ 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 + "", "<DB>");
super("backup", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_BACKUP.toString(), "<DB>");
this.plugin = plugin;
}
@ -37,7 +37,7 @@ 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 + ""), sender)) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS.parse(Phrase.USE_BACKUP.toString()), sender)) {
return true;
}
String dbName = args[0].toLowerCase();
@ -49,14 +49,14 @@ public class ManageBackupCommand extends SubCommand {
final Database database = ManageUtils.getDB(plugin, dbName);
// If DB is null return
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE + "", sender)) {
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
Log.error(dbName + " was null!");
return true;
}
runBackupTask(sender, args, database);
} catch (NullPointerException e) {
sender.sendMessage(Phrase.MANAGE_DATABASE_FAILURE + "");
sender.sendMessage(Phrase.MANAGE_DATABASE_FAILURE.toString());
}
return true;
}

View File

@ -29,14 +29,14 @@ 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 + "", "<DB>");
super("clean", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.MANAGE.getPermission(), Phrase.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 + "", sender)) {
if (!Check.isTrue(args.length != 0, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE.toString(), sender)) {
return true;
}
String dbName = args[0].toLowerCase();
@ -49,7 +49,7 @@ public class ManageCleanCommand extends SubCommand {
final Database database = ManageUtils.getDB(plugin, dbName);
// If DB is null return
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE + "", sender)) {
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
Log.error(dbName + " was null!");
return true;
}
@ -64,7 +64,7 @@ public class ManageCleanCommand extends SubCommand {
public void run() {
sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse());
database.clean();
sender.sendMessage(Phrase.MANAGE_SUCCESS + "");
sender.sendMessage(Phrase.MANAGE_SUCCESS.toString());
this.cancel();
}
}).runTaskAsynchronously();

View File

@ -5,7 +5,6 @@ import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import java.sql.SQLException;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
@ -72,13 +71,10 @@ public class ManageClearCommand extends SubCommand {
sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse());
if (database.removeAllData()) {
sender.sendMessage(Phrase.MANAGE_CLEAR_SUCCESS + "");
sender.sendMessage(Phrase.MANAGE_CLEAR_SUCCESS.toString());
} else {
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL + "");
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
}
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL + "");
} finally {
this.cancel();
}

View File

@ -29,14 +29,14 @@ 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 + "", "<DB>");
super("hotswap", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_HOTSWAP.toString(), "<DB>");
this.plugin = plugin;
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE + "", sender)) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE.toString(), sender)) {
return true;
}
String dbName = args[0].toLowerCase();
@ -53,7 +53,7 @@ public class ManageHotswapCommand extends SubCommand {
final Database database = ManageUtils.getDB(plugin, dbName);
// If DB is null return
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE + "", sender)) {
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
Log.error(dbName + " was null!");
return true;
}
@ -62,7 +62,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 + "");
sender.sendMessage(Phrase.MANAGE_DATABASE_FAILURE.toString());
return true;
}

View File

@ -6,10 +6,7 @@ import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.FormattingUtils;
import com.djrapitops.plugin.utilities.player.Fetch;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
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;
@ -17,6 +14,11 @@ 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.utilities.Check;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* This manage subcommand is used to import data from 3rd party plugins.
*
@ -35,7 +37,7 @@ 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 + "", Phrase.ARG_IMPORT + "");
super("import", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_IMPORT.toString(), Phrase.ARG_IMPORT.toString());
this.plugin = plugin;
}
@ -72,12 +74,12 @@ public class ManageImportCommand extends SubCommand {
@Override
public void run() {
try {
sender.sendMessage(Phrase.MANAGE_IMPORTING + "");
List<UUID> uuids = Fetch.getIOfflinePlayers().stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
sender.sendMessage(Phrase.MANAGE_IMPORTING.toString());
List<UUID> uuids = Fetch.getIOfflinePlayers().stream().map(IOfflinePlayer::getUniqueId).collect(Collectors.toList());
if (importer.importData(uuids, importArguments)) {
sender.sendMessage(Phrase.MANAGE_SUCCESS + "");
sender.sendMessage(Phrase.MANAGE_SUCCESS.toString());
} else {
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL + "");
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
}
} finally {
this.cancel();
@ -88,9 +90,7 @@ public class ManageImportCommand extends SubCommand {
private void list(Map<String, Importer> importers, ISender sender) {
sender.sendMessage(Phrase.CMD_FOOTER.parse());
importers.entrySet().stream().forEach(e -> {
sender.sendMessage(Phrase.CMD_BALL + " " + e.getKey() + ": " + e.getValue().getInfo());
});
importers.forEach((string, importer) -> sender.sendMessage(Phrase.CMD_BALL + " " + string + ": " + importer.getInfo()));
sender.sendMessage(Phrase.CMD_FOOTER.parse());
}
}

View File

@ -5,8 +5,6 @@ import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import java.util.Collection;
import java.util.UUID;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
@ -15,6 +13,9 @@ import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.ManageUtils;
import java.util.Collection;
import java.util.UUID;
/**
* This manage subcommand is used to move all data from one database to another.
*
@ -33,14 +34,14 @@ 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 + "", Phrase.ARG_MOVE + "");
super("move", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_MOVE.toString(), Phrase.ARG_MOVE.toString());
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 + ""), sender)) {
if (!Check.isTrue(args.length >= 2, Phrase.COMMAND_REQUIRES_ARGUMENTS.parse(Phrase.USE_MOVE.toString()), sender)) {
return true;
}
@ -57,7 +58,7 @@ public class ManageMoveCommand extends SubCommand {
if (!Check.isTrue(isCorrectDB, Phrase.MANAGE_ERROR_INCORRECT_DB + toDB, sender)) {
return true;
}
if (!Check.isTrue(!Verify.equalsIgnoreCase(fromDB, toDB), Phrase.MANAGE_ERROR_SAME_DB + "", sender)) {
if (!Check.isTrue(!Verify.equalsIgnoreCase(fromDB, toDB), Phrase.MANAGE_ERROR_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)) {
@ -66,14 +67,14 @@ public class ManageMoveCommand extends SubCommand {
final Database fromDatabase = ManageUtils.getDB(plugin, fromDB);
if (!Check.isTrue(Verify.notNull(fromDatabase), Phrase.MANAGE_DATABASE_FAILURE + "", sender)) {
if (!Check.isTrue(Verify.notNull(fromDatabase), Phrase.MANAGE_DATABASE_FAILURE.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 + "", sender)) {
if (!Check.isTrue(Verify.notNull(toDatabase), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
Log.error(toDB + " was null!");
return true;
}
@ -96,9 +97,9 @@ public class ManageMoveCommand extends SubCommand {
sender.sendMessage(Phrase.MANAGE_MOVE_SUCCESS + "");
boolean movedToCurrentDatabase = Verify.equalsIgnoreCase(toDatabase.getConfigName(), plugin.getDB().getConfigName());
Check.isTrue(!movedToCurrentDatabase, Phrase.MANAGE_DB_CONFIG_REMINDER + "", sender);
Check.isTrue(!movedToCurrentDatabase, Phrase.MANAGE_DB_CONFIG_REMINDER.toString(), sender);
} else {
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL + "");
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
}
} catch (Exception e) {
Log.toLog(this.getClass().getName() + " " + getTaskName(), e);

View File

@ -5,8 +5,6 @@ import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import java.sql.SQLException;
import java.util.UUID;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
@ -15,6 +13,9 @@ 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;
import java.sql.SQLException;
import java.util.UUID;
/**
* This manage subcommand is used to remove a single player's data from the
* database.
@ -31,14 +32,14 @@ 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 + "", Phrase.ARG_PLAYER + " [-a]");
super("remove", CommandType.CONSOLE_WITH_ARGUMENTS, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_REMOVE.toString(), Phrase.ARG_PLAYER + " [-a]");
this.plugin = plugin;
}
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE + "", sender)) {
if (!Check.isTrue(args.length >= 1, Phrase.COMMAND_REQUIRES_ARGUMENTS_ONE.toString(), sender)) {
return true;
}
@ -73,11 +74,11 @@ public class ManageRemoveCommand extends SubCommand {
if (plugin.getDB().removeAccount(uuid.toString())) {
sender.sendMessage(Phrase.MANAGE_REMOVE_SUCCESS.parse(playerName, plugin.getDB().getConfigName()));
} else {
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL + "");
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
}
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL + "");
sender.sendMessage(Phrase.MANAGE_PROCESS_FAIL.toString());
}
} finally {
this.cancel();

View File

@ -5,9 +5,6 @@ import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.SubCommand;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
import java.io.File;
import java.util.Collection;
import java.util.UUID;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
@ -17,6 +14,10 @@ import main.java.com.djrapitops.plan.database.databases.SQLiteDB;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.ManageUtils;
import java.io.File;
import java.util.Collection;
import java.util.UUID;
/**
* This manage subcommand is used to restore a backup.db file in the
* /plugins/Plan folder.
@ -33,14 +34,14 @@ 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 + "", Phrase.ARG_RESTORE + "");
super("restore", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_RESTORE.toString(), Phrase.ARG_RESTORE.toString());
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 + ""), sender)) {
if (!Check.isTrue(args.length >= 2, Phrase.COMMAND_REQUIRES_ARGUMENTS.parse(Phrase.USE_RESTORE.toString()), sender)) {
return true;
}
String db = args[1].toLowerCase();
@ -55,7 +56,7 @@ public class ManageRestoreCommand extends SubCommand {
final Database database = ManageUtils.getDB(plugin, db);
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE + "", sender)) {
if (!Check.isTrue(Verify.notNull(database), Phrase.MANAGE_DATABASE_FAILURE.toString(), sender)) {
Log.error(db + " was null!");
return true;
}
@ -82,7 +83,7 @@ public class ManageRestoreCommand extends SubCommand {
}
SQLiteDB backupDB = new SQLiteDB(plugin, backupDBName);
if (!backupDB.init()) {
sender.sendMessage(Phrase.MANAGE_DATABASE_FAILURE + "");
sender.sendMessage(Phrase.MANAGE_DATABASE_FAILURE.toString());
return;
}
sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse());

View File

@ -22,7 +22,7 @@ public class ManageStatusCommand extends SubCommand {
* @param plugin Current instance of Plan
*/
public ManageStatusCommand(Plan plugin) {
super("status", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_STATUS + "");
super("status", CommandType.CONSOLE, Permissions.MANAGE.getPermission(), Phrase.CMD_USG_MANAGE_STATUS.toString());
this.plugin = plugin;
}
@ -30,13 +30,13 @@ public class ManageStatusCommand extends SubCommand {
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
String[] messages = new String[]{
Phrase.CMD_MANAGE_STATUS_HEADER + "",
Phrase.CMD_MANAGE_STATUS_HEADER.toString(),
Phrase.CMD_MANAGE_STATUS_ACTIVE_DB.parse(plugin.getDB().getConfigName()),
Phrase.CMD_MANAGE_STATUS_QUEUE_PROCESS.parse("" + plugin.getHandler().getProcessTask().size()),
Phrase.CMD_MANAGE_STATUS_QUEUE_SAVE.parse("" + plugin.getHandler().getSaveTask().size()),
Phrase.CMD_MANAGE_STATUS_QUEUE_GET.parse("" + plugin.getHandler().getGetTask().size()),
Phrase.CMD_MANAGE_STATUS_QUEUE_CLEAR.parse("" + plugin.getHandler().getClearTask().size()),
Phrase.CMD_FOOTER + ""
Phrase.CMD_FOOTER.toString()
};
sender.sendMessage(messages);

View File

@ -28,7 +28,7 @@ public class WebLevelCommand extends SubCommand {
ColorScheme cs = plugin.getColorScheme();
String sCol = cs.getSecondaryColor();
String cmdBall = Phrase.CMD_BALL.parse();
String[] msgs = new String[]{
String[] messages = new String[]{
Phrase.CMD_FOOTER.parse(),
cmdBall + sCol + "0: Access all pages",
cmdBall + sCol + "1: Access '/players' and all inspect pages",
@ -36,7 +36,7 @@ public class WebLevelCommand extends SubCommand {
cmdBall + sCol + "3+: No permissions",
Phrase.CMD_FOOTER.parse()
};
sender.sendMessage(msgs);
sender.sendMessage(messages);
return true;
}

View File

@ -5,8 +5,6 @@ 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 java.util.Collections;
import java.util.List;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Phrase;
@ -14,6 +12,8 @@ import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.utilities.comparators.WebUserComparator;
import java.util.List;
/**
* Subcommand for checking WebUser list.
*
@ -39,7 +39,7 @@ public class WebListUsersCommand extends SubCommand {
String mCol = cs.getMainColor();
String sCol = cs.getSecondaryColor();
List<WebUser> users = plugin.getDB().getSecurityTable().getUsers();
Collections.sort(users, new WebUserComparator());
users.sort(new WebUserComparator());
sender.sendMessage(Phrase.CMD_FOOTER.parse() + mCol + " WebUsers (" + users.size() + ")");
for (WebUser user : users) {
sender.sendMessage(" " + user.getPermLevel() + " : " + user.getName());

View File

@ -1,24 +1,16 @@
package main.java.com.djrapitops.plan.data;
import com.djrapitops.plugin.utilities.Verify;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.analysis.ActivityPart;
import main.java.com.djrapitops.plan.data.analysis.CommandUsagePart;
import main.java.com.djrapitops.plan.data.analysis.GamemodePart;
import main.java.com.djrapitops.plan.data.analysis.GeolocationPart;
import main.java.com.djrapitops.plan.data.analysis.JoinInfoPart;
import main.java.com.djrapitops.plan.data.analysis.KillPart;
import main.java.com.djrapitops.plan.data.analysis.PlayerCountPart;
import main.java.com.djrapitops.plan.data.analysis.PlaytimePart;
import main.java.com.djrapitops.plan.data.analysis.RawData;
import main.java.com.djrapitops.plan.data.analysis.TPSPart;
import main.java.com.djrapitops.plan.data.analysis.*;
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.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Big container object for Data.
*
@ -60,7 +52,7 @@ public class AnalysisData extends RawData<AnalysisData> {
playerCountPart = new PlayerCountPart();
playtimePart = new PlaytimePart(playerCountPart);
killPart = new KillPart(playerCountPart);
gamemodePart = new GamemodePart(playerCountPart);
gamemodePart = new GamemodePart();
tpsPart = new TPSPart(tpsData);
activityPart = new ActivityPart(joinInfoPart, tpsPart);
}
@ -143,15 +135,15 @@ public class AnalysisData extends RawData<AnalysisData> {
@Override
protected void analyse() {
Verify.notNull(playersTable);
Verify.notNull(pluginsTabLayout);
Verify.notNull(planVersion);
Verify.nullCheck(playersTable);
Verify.nullCheck(pluginsTabLayout);
Verify.nullCheck(planVersion);
addValue("sortabletable", playersTable);
addValue("version", planVersion);
final List<RawData> parts = getAllParts();
parts.stream().forEach((part) -> {
parts.forEach((part) -> {
try {
Benchmark.start("Analysis Phase: " + part.getClass().getSimpleName());
part.analyseData();

View File

@ -22,7 +22,7 @@ public class KillData {
* @param victim UUID of the victim.
* @param victimID ID of the victim, get from the database.
* @param weapon Weapon used.
* @param date Epoch millisecond at which the kill occurrred.
* @param date Epoch millisecond at which the kill occurred.
*/
public KillData(UUID victim, int victimID, String weapon, long date) {
this.victim = victim;
@ -84,16 +84,9 @@ public class KillData {
return false;
}
final KillData other = (KillData) obj;
if (this.date != other.date) {
return false;
}
if (!Objects.equals(this.weapon, other.weapon)) {
return false;
}
if (!Objects.equals(this.victim, other.victim)) {
return false;
}
return true;
return this.date == other.date
&& Objects.equals(this.weapon, other.weapon)
&& Objects.equals(this.victim, other.victim);
}
@Override

View File

@ -106,13 +106,7 @@ public class SessionData {
return false;
}
final SessionData other = (SessionData) obj;
if (this.sessionStart != other.sessionStart) {
return false;
}
if (this.sessionEnd != other.sessionEnd) {
return false;
}
return true;
return this.sessionStart == other.sessionStart && this.sessionEnd == other.sessionEnd;
}
@Override

View File

@ -16,6 +16,7 @@ public class TPS {
private final long date;
private final double tps;
private final int players;
private final double cpuUsage;
/**
* Constructor.
@ -23,11 +24,13 @@ public class TPS {
* @param date time of the average calculation.
* @param tps average tps for the last minute.
* @param players average players for the last minute.
* @param cpuUsage average CPU usage for the last minute.
*/
public TPS(long date, double tps, int players) {
public TPS(long date, double tps, int players, double cpuUsage) {
this.date = date;
this.tps = tps;
this.players = players;
this.cpuUsage = cpuUsage;
}
/**
@ -57,6 +60,15 @@ public class TPS {
return players;
}
/**
* Get the average CPU Usage for the minute.
*
* @return 0-20 double
*/
public double getCPUUsage() {
return cpuUsage;
}
@Override
public int hashCode() {
int hash = 3;
@ -78,20 +90,14 @@ public class TPS {
return false;
}
final TPS other = (TPS) obj;
if (this.date != other.date) {
return false;
}
if (Double.doubleToLongBits(this.tps) != Double.doubleToLongBits(other.tps)) {
return false;
}
if (this.players != other.players) {
return false;
}
return true;
return this.date == other.date
&& Double.doubleToLongBits(this.tps) == Double.doubleToLongBits(other.tps)
&& this.players == other.players
&& this.cpuUsage == other.cpuUsage;
}
@Override
public String toString() {
return "TPS{" + date + "|" + tps + "|" + players + '}';
return "TPS{" + date + "|" + tps + "|" + players + "|" + cpuUsage + "}";
}
}

View File

@ -3,19 +3,12 @@ package main.java.com.djrapitops.plan.data;
import com.djrapitops.plugin.utilities.Verify;
import com.djrapitops.plugin.utilities.player.IOfflinePlayer;
import com.djrapitops.plugin.utilities.player.IPlayer;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import main.java.com.djrapitops.plan.Log;
import java.net.InetAddress;
import java.util.*;
import java.util.stream.Collectors;
/**
* This class is used for storing information about a player during runtime.
*
@ -50,7 +43,7 @@ public class UserData {
private boolean isOnline;
private SessionData currentSession;
private List<SessionData> sessions;
private final List<SessionData> sessions;
/**
* Creates a new UserData object with given values and default values.
@ -64,7 +57,7 @@ public class UserData {
* All Collections are left empty: locations, nicknames, ips, sessions,
* playerKills. Because nicknames is empty, lastNick is an empty string.
*
* gmTimes Hashmap will contain 4 '0L' values: SURVIVAL, CREATIVE,
* gmTimes HashMap will contain 4 '0L' values: SURVIVAL, CREATIVE,
* ADVENTURE, SPECTATOR
*
* @param uuid UUID of the player
@ -106,7 +99,7 @@ public class UserData {
* All Collections are left empty: locations, nicknames, ips, sessions,
* playerKills. Because nicknames is empty, lastNick is an empty string.
*
* gmTimes Hashmap will contain 4 '0L' values: SURVIVAL, CREATIVE,
* gmTimes HashMap will contain 4 '0L' values: SURVIVAL, CREATIVE,
* ADVENTURE, SPECTATOR
*
* @param player IPlayer object.
@ -135,7 +128,7 @@ public class UserData {
* All Collections are left empty: locations, nicknames, ips, sessions,
* playerKills. Because nicknames is empty, lastNick is an empty string.
*
* gmTimes Hashmap will contain 4 '0L' values: SURVIVAL, CREATIVE,
* gmTimes HashMap will contain 4 '0L' values: SURVIVAL, CREATIVE,
* ADVENTURE, SPECTATOR
*
* lastGM will be set as SURVIVAL
@ -216,7 +209,7 @@ public class UserData {
if (addIps.isEmpty()) {
return;
}
ips.addAll(addIps.stream().filter(ip -> Verify.notNull(ip)).collect(Collectors.toList()));
ips.addAll(addIps.stream().filter(Verify::notNull).collect(Collectors.toList()));
}
@ -306,8 +299,8 @@ public class UserData {
*/
public void addSessions(Collection<SessionData> sessions) {
Collection<SessionData> filteredSessions = sessions.stream()
.filter(session -> Verify.notNull(session))
.filter(session -> session.isValid())
.filter(Verify::notNull)
.filter(SessionData::isValid)
.collect(Collectors.toList());
this.sessions.addAll(filteredSessions);
}
@ -760,63 +753,32 @@ public class UserData {
if (getClass() != obj.getClass()) {
return false;
}
final UserData other = (UserData) obj;
if (this.registered != other.registered) {
return false;
}
// if (this.lastPlayed != other.lastPlayed) {
// return false;
// }
if (this.playTime != other.playTime) {
return false;
}
if (this.loginTimes != other.loginTimes) {
return false;
}
if (this.timesKicked != other.timesKicked) {
return false;
}
if (this.lastGmSwapTime != other.lastGmSwapTime) {
return false;
}
if (this.mobKills != other.mobKills) {
return false;
}
if (this.deaths != other.deaths) {
return false;
}
if (!Objects.equals(this.lastNick, other.lastNick)) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (!Objects.equals(this.uuid, other.uuid)) {
return false;
}
if (!Objects.equals(this.ips, other.ips)) {
return false;
}
if (!Objects.equals(this.nicknames, other.nicknames)) {
return false;
}
if (!Objects.equals(this.lastGamemode, other.lastGamemode)) {
return false;
}
if (!Objects.equals(this.gmTimes, other.gmTimes)) {
return false;
}
if (!Objects.equals(this.playerKills, other.playerKills)) {
return false;
}
if (!Objects.equals(this.sessions, other.sessions)) {
return false;
}
return true;
return this.registered == other.registered
&& this.playTime == other.playTime
&& this.loginTimes == other.loginTimes
&& this.timesKicked == other.timesKicked
&& this.lastGmSwapTime == other.lastGmSwapTime
&& this.mobKills == other.mobKills
&& this.deaths == other.deaths
&& Objects.equals(this.lastNick, other.lastNick)
&& Objects.equals(this.name, other.name)
&& Objects.equals(this.uuid, other.uuid)
&& Objects.equals(this.ips, other.ips)
&& Objects.equals(this.nicknames, other.nicknames)
&& Objects.equals(this.lastGamemode, other.lastGamemode)
&& Objects.equals(this.gmTimes, other.gmTimes)
&& Objects.equals(this.playerKills, other.playerKills)
&& Objects.equals(this.sessions, other.sessions);
}
/**
* Check wether or not the object should be cleared from cache after it has
* Check whether or not the object should be cleared from cache after it has
* been saved.
*
* @return true/false
@ -826,7 +788,7 @@ public class UserData {
}
/**
* Set wether or not the object should be cleared from cache after it has
* Set whether or not the object should be cleared from cache after it has
* been saved.
*
* @param clearAfterSave true/false

View File

@ -7,7 +7,7 @@ package main.java.com.djrapitops.plan.data.additional;
* The enum determines what should be done to the return value of
* PluginData.getValue() method when the analysis is run.
*
* Refer to the documentation on github for additional information.
* Refer to the documentation on GitHub for additional information.
*
* @author Rsl1122
* @since 3.1.0
@ -104,17 +104,17 @@ public enum AnalysisType {
private final String modifier;
private final String placeholderModifier;
private AnalysisType(String placeholderModifier, String modifier) {
AnalysisType(String placeholderModifier, String modifier) {
this.placeholderModifier = placeholderModifier;
this.modifier = modifier;
}
private AnalysisType(String placeholderModifier) {
AnalysisType(String placeholderModifier) {
this.placeholderModifier = placeholderModifier;
this.modifier = "";
}
private AnalysisType() {
AnalysisType() {
this.placeholderModifier = "";
this.modifier = "";
}

View File

@ -1,17 +1,13 @@
package main.java.com.djrapitops.plan.data.additional;
import com.djrapitops.pluginbridge.plan.Bridge;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import java.util.*;
import java.util.stream.Collectors;
/**
* Class responsible for hooking to other plugins and managing the %plugins%
* placeholder on Analysis and Inspect pages.
@ -21,7 +17,7 @@ import main.java.com.djrapitops.plan.utilities.HtmlUtils;
*/
public class HookHandler {
private List<PluginData> additionalDataSources;
private final List<PluginData> additionalDataSources;
private final PluginConfigSectionHandler configHandler;
/**
@ -46,7 +42,7 @@ public class HookHandler {
* The plugin data will appear on Analysis and/or Inspect pages depending on
* how the extending object is set up.
*
* Refer to documentation on github for more information.
* Refer to documentation on GitHub for more information.
*
* @param dataSource an object extending the PluginData class.
*/
@ -76,7 +72,7 @@ public class HookHandler {
/**
* Used to get the Layout with PluginData placeholders to replace %plugins%
* placeholder on analysis.hmtl.
* placeholder on analysis.html.
*
* @return html, getPluginsTabLayout-method
* @see HtmlUtils
@ -89,7 +85,7 @@ public class HookHandler {
/**
* Used to get the Layout with PluginData placeholders to replace %plugins%
* placeholder on player.hmtl.
* placeholder on player.html.
*
* @return html, getPluginsTabLayout-method
* @see HtmlUtils
@ -103,7 +99,7 @@ public class HookHandler {
private List<String> getPluginNamesAnalysis() {
List<String> pluginNames = additionalDataSources.stream()
.filter(source -> !source.getAnalysisTypes().isEmpty())
.map(source -> source.getSourcePlugin())
.map(PluginData::getSourcePlugin)
.distinct()
.collect(Collectors.toList());
Collections.sort(pluginNames);
@ -113,7 +109,7 @@ public class HookHandler {
private List<String> getPluginNamesInspect() {
List<String> pluginNames = additionalDataSources.stream()
.filter(source -> !source.analysisOnly())
.map(source -> source.getSourcePlugin())
.map(PluginData::getSourcePlugin)
.distinct()
.collect(Collectors.toList());
Collections.sort(pluginNames);

View File

@ -31,8 +31,7 @@ public class PluginConfigSectionHandler {
private ConfigurationSection getPluginsSection() {
FileConfiguration config = plan.getConfig();
ConfigurationSection section = config.getConfigurationSection("Customization.Plugins");
return section;
return config.getConfigurationSection("Customization.Plugins");
}
public void createSection(PluginData dataSource) {

View File

@ -1,13 +1,10 @@
package main.java.com.djrapitops.plan.data.additional;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import main.java.com.djrapitops.plan.ui.html.Html;
import java.io.Serializable;
import java.util.*;
/**
* This is an abstract class that can be used to add data from a plugin to the
* "Plugins"-tab of Analysis and Inspect pages.
@ -34,7 +31,7 @@ public abstract class PluginData {
/**
* Name of the plugin the data is coming from.
*
* All datasources with the same sourcePlugin will be placed in the same
* All sources of data with the same sourcePlugin will be placed in the same
* "box" in the "Plugins" tab.
*
* A box has a max height of 600px, and higher than that will add a
@ -72,7 +69,7 @@ public abstract class PluginData {
* A list containing the AnalysisType enums that determine what should be
* done with the data on the analysis page.
*/
protected List<AnalysisType> analysisTypes;
protected final List<AnalysisType> analysisTypes;
/**
* Main constructor.
@ -280,7 +277,7 @@ public abstract class PluginData {
/**
* If a PluginData object has same placeholder, sourcePlugin and
* analysisTypes, it is considired equal.
* analysisTypes, it is considered equal.
*
* @param obj Another Object.
* @return Is current object equal to given object.
@ -297,19 +294,10 @@ public abstract class PluginData {
return false;
}
final PluginData other = (PluginData) obj;
if (this.analysisOnly != other.analysisOnly) {
return false;
}
if (!Objects.equals(this.placeholder, other.placeholder)) {
return false;
}
if (!Objects.equals(this.sourcePlugin, other.sourcePlugin)) {
return false;
}
if (!Objects.equals(this.analysisTypes, other.analysisTypes)) {
return false;
}
return true;
return this.analysisOnly == other.analysisOnly
&& Objects.equals(this.placeholder, other.placeholder)
&& Objects.equals(this.sourcePlugin, other.sourcePlugin)
&& Objects.equals(this.analysisTypes, other.analysisTypes);
}
@Override

View File

@ -1,11 +1,12 @@
package main.java.com.djrapitops.plan.data.analysis;
import com.djrapitops.plugin.utilities.Verify;
import java.util.Arrays;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import java.util.Arrays;
/**
* Part responsible for all Gamemode usage related analysis.
*
@ -21,14 +22,12 @@ import main.java.com.djrapitops.plan.utilities.HtmlUtils;
*/
public class GamemodePart extends RawData<GamemodePart> {
private final PlayerCountPart playerCount;
private long survivalTime;
private long creativeTime;
private long adventureTime;
private long spectatorTime;
public GamemodePart(PlayerCountPart playerCount) {
this.playerCount = playerCount;
public GamemodePart() {
survivalTime = 0;
creativeTime = 0;
adventureTime = 0;

View File

@ -73,10 +73,7 @@ public class GeolocationPart extends RawData<GeolocationPart> {
}
public void addGeoloc(String country) {
if (geolocations.get(country) == null) {
return;
}
geolocations.replace(country, geolocations.get(country) + 1);
geolocations.computeIfPresent(country, (computedCountry, amount) -> amount + 1);
}
}

View File

@ -2,15 +2,13 @@ package main.java.com.djrapitops.plan.data.analysis;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.utilities.Verify;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import main.java.com.djrapitops.plan.data.SessionData;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.AnalysisUtils;
import java.util.*;
import java.util.stream.Collectors;
/**
* Part responsible for all Player login related analysis.
*
@ -109,6 +107,6 @@ public class JoinInfoPart extends RawData<JoinInfoPart> {
public void addSessions(UUID uuid, List<SessionData> sessions) {
Verify.nullCheck(uuid);
Verify.nullCheck(sessions);
this.sessions.put(uuid, sessions);
this.sessions.put(uuid, sessions.stream().distinct().collect(Collectors.toList()));
}
}

View File

@ -1,12 +1,13 @@
package main.java.com.djrapitops.plan.data.analysis;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.data.KillData;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import main.java.com.djrapitops.plan.data.KillData;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
/**
* Part responsible for all Death related analysis.
@ -22,7 +23,7 @@ import main.java.com.djrapitops.plan.utilities.MiscUtils;
*/
public class KillPart extends RawData<KillPart> {
private final PlayerCountPart playerCount;
private final PlayerCountPart playerCount; // TODO Averages
private final Map<UUID, List<KillData>> playerKills;
private long mobKills;
private long deaths;

View File

@ -1,13 +1,15 @@
package main.java.com.djrapitops.plan.data.analysis;
import com.djrapitops.plugin.api.TimeAmount;
import java.util.List;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.ui.html.graphs.CPUGraphCreator;
import main.java.com.djrapitops.plan.ui.html.graphs.TPSGraphCreator;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import java.util.List;
/**
* Part responsible for all TPS related analysis.
*
@ -15,7 +17,7 @@ import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
*
* Placeholder values can be retrieved using the get method.
*
* Contains following place-holders: tpsscatterday, tpsscatterweek, averagetps,
* Contains following place-holders: tpsscatterday, tpsscatterweek, cpuscatterday, cpuscatterweek, averagetps,
* averagetpsday
*
* @author Rsl1122
@ -37,12 +39,17 @@ public class TPSPart extends RawData<TPSPart> {
String tpsScatterDay = TPSGraphCreator.buildScatterDataStringTPS(day, TimeAmount.DAY.ms());
String tpsScatterWeek = TPSGraphCreator.buildScatterDataStringTPS(week, TimeAmount.WEEK.ms());
String cpuScatterDay = CPUGraphCreator.buildScatterDataString(day, TimeAmount.DAY.ms());
String cpuScatterWeek = CPUGraphCreator.buildScatterDataString(week, TimeAmount.WEEK.ms());
addValue("tpsscatterday", tpsScatterDay);
addValue("tpsscatterweek", tpsScatterWeek);
double averageTPSweek = MathUtils.averageDouble(week.stream().map(t -> t.getTps()));
double averageTPSday = MathUtils.averageDouble(day.stream().map(t -> t.getTps()));
addValue("cpuscatterday", cpuScatterDay);
addValue("cpuscatterweek", cpuScatterWeek);
double averageTPSweek = MathUtils.averageDouble(week.stream().map(TPS::getTps));
double averageTPSday = MathUtils.averageDouble(day.stream().map(TPS::getTps));
addValue("averagetps", FormatUtils.cutDecimals(averageTPSweek));
addValue("averagetpsday", FormatUtils.cutDecimals(averageTPSday));

View File

@ -13,7 +13,6 @@ import main.java.com.djrapitops.plan.utilities.analysis.Analysis;
*/
public class AnalysisCacheHandler {
private final Plan plugin;
private AnalysisData cache;
private final Analysis analysis;
private boolean analysisEnabled;
@ -26,7 +25,6 @@ public class AnalysisCacheHandler {
* @param plugin Current instance of Plan
*/
public AnalysisCacheHandler(Plan plugin) {
this.plugin = plugin;
analysis = new Analysis(plugin);
analysisEnabled = true;
}

View File

@ -1,21 +1,17 @@
package main.java.com.djrapitops.plan.data.cache;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.ITask;
import com.djrapitops.plugin.utilities.player.IPlayer;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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.*;
import main.java.com.djrapitops.plan.data.cache.queue.*;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.cache.queue.DataCacheClearQueue;
import main.java.com.djrapitops.plan.data.cache.queue.DataCacheGetQueue;
import main.java.com.djrapitops.plan.data.cache.queue.DataCacheProcessQueue;
import main.java.com.djrapitops.plan.data.cache.queue.DataCacheSaveQueue;
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;
@ -26,16 +22,19 @@ import main.java.com.djrapitops.plan.utilities.NewPlayerCreator;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import main.java.com.djrapitops.plan.utilities.comparators.HandlingInfoTimeComparator;
import java.sql.SQLException;
import java.util.*;
/**
* This Class contains the Cache.
*
* This class is the main processing class that initialises Save, Clear, Process
* and Get queue and Starts the asyncronous save task.
* and Get queue and Starts the asynchronous save task.
*
* It is used to store command use, locations, active sessions and UserData
* objects in memory.
*
* It's methods can be used to access all the data it stores and to clear them.
* Its methods can be used to access all the data it stores and to clear them.
*
* @author Rsl1122
* @since 2.0.0
@ -64,7 +63,7 @@ public class DataCacheHandler extends SessionCache {
* Class Constructor.
*
* Gets the Database from the plugin. Starts the queues. Registers
* Asyncronous Periodic Save Task
* Asynchronous Periodic Save Task
*
* @param plugin Current instance of Plan
*/
@ -113,7 +112,7 @@ public class DataCacheHandler extends SessionCache {
}
/**
* Used to start the Asyncronous Save Task.
* Used to start the Asynchronous Save Task.
*
* @throws IllegalArgumentException BukkitRunnable was given wrong
* parameters.
@ -132,7 +131,7 @@ public class DataCacheHandler extends SessionCache {
clearAfterXsaves = configValue;
}
DataCacheHandler handler = this;
ITask asyncPeriodicCacheSaveTask = plugin.getRunnableFactory().createNew(new AbsRunnable("PeriodicCacheSaveTask") {
plugin.getRunnableFactory().createNew(new AbsRunnable("PeriodicCacheSaveTask") {
private int timesSaved = 0;
@Override
@ -224,7 +223,7 @@ public class DataCacheHandler extends SessionCache {
* Should only be called from Async thread
*/
public void saveCachedUserData() {
List<UserData> data = new ArrayList<>();
Set<UserData> data = new HashSet<>();
data.addAll(dataCache.values());
try {
db.saveMultipleUserData(data);
@ -272,7 +271,7 @@ public class DataCacheHandler extends SessionCache {
toProcess.add(new LogoutInfo(uuid, time, p.isBanned(), p.getGamemode(), getSession(uuid)));
}
Log.debug("ToProcess size_AFTER: " + toProcess.size() + " DataCache size: " + dataCache.keySet().size());
Collections.sort(toProcess, new HandlingInfoTimeComparator());
toProcess.sort(new HandlingInfoTimeComparator());
processUnprocessedHandlingInfo(toProcess);
Benchmark.stop("Cache: ProcessOnlineHandlingInfo");
List<UserData> data = new ArrayList<>();
@ -336,7 +335,7 @@ public class DataCacheHandler extends SessionCache {
/**
* Saves the cached CommandUse.
*
* Should be only called from an Asyncronous Thread.
* Should be only called from an Asynchronous Thread.
*/
public void saveCommandUse() {
try {
@ -363,12 +362,15 @@ public class DataCacheHandler extends SessionCache {
if (unsavedTPSHistory.isEmpty()) {
return new ArrayList<>();
}
List<List<TPS>> copy = new ArrayList<>(unsavedTPSHistory);;
List<List<TPS>> copy = new ArrayList<>(unsavedTPSHistory);
for (List<TPS> history : copy) {
final long lastdate = history.get(history.size() - 1).getDate();
final double averageTPS = MathUtils.averageDouble(history.stream().map(t -> t.getTps()));
final int averagePlayersOnline = (int) MathUtils.averageInt(history.stream().map(t -> t.getPlayers()));
averages.add(new TPS(lastdate, averageTPS, averagePlayersOnline));
final long lastDate = history.get(history.size() - 1).getDate();
final double averageTPS = MathUtils.averageDouble(history.stream().map(TPS::getTps));
final int averagePlayersOnline = (int) MathUtils.averageInt(history.stream().map(TPS::getPlayers));
final double averageCPUUsage = MathUtils.averageDouble(history.stream().map(TPS::getCPUUsage));
averages.add(new TPS(lastDate, averageTPS, averagePlayersOnline, averageCPUUsage));
}
unsavedTPSHistory.removeAll(copy);
return averages;
@ -379,9 +381,7 @@ public class DataCacheHandler extends SessionCache {
*/
public void saveHandlerDataToCache() {
final List<IPlayer> onlinePlayers = plugin.fetch().getOnlinePlayers();
onlinePlayers.stream().forEach((p) -> {
saveHandlerDataToCache(p, false);
});
onlinePlayers.forEach((p) -> saveHandlerDataToCache(p, false));
}
private void saveHandlerDataToCache(IPlayer player, boolean pool) {
@ -429,7 +429,7 @@ public class DataCacheHandler extends SessionCache {
*
* @param uuid Player's UUID.
*/
public void scheludeForClear(UUID uuid) {
public void scheduldeForClear(UUID uuid) {
clearTask.scheduleForClear(uuid);
}
@ -495,7 +495,7 @@ public class DataCacheHandler extends SessionCache {
* Calls all the methods that are ran when PlayerJoinEvent is fired
*/
public void handleReload() {
ITask asyncReloadCacheUpdateTask = plugin.getRunnableFactory().createNew(new AbsRunnable("ReloadCacheUpdateTask") {
plugin.getRunnableFactory().createNew(new AbsRunnable("ReloadCacheUpdateTask") {
@Override
public void run() {
final List<IPlayer> onlinePlayers = plugin.fetch().getOnlinePlayers();
@ -519,10 +519,9 @@ public class DataCacheHandler extends SessionCache {
* @param command "/command"
*/
public void handleCommand(String command) {
if (!commandUse.containsKey(command)) {
commandUse.put(command, 0);
}
commandUse.put(command, commandUse.get(command) + 1);
int amount = commandUse.getOrDefault(command, 0);
commandUse.put(command, amount + 1);
}
/**

View File

@ -0,0 +1,93 @@
package main.java.com.djrapitops.plan.data.cache;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
/**
* This class contains the geolocation cache.
* <p>
* It caches all IPs with their matching country.
* <p>
* This cache uses the Google Guava {@link Cache} and has a capacity of 10.000 entries.
*
* @author Fuzzlemann
* @since 3.5.5
*/
public class GeolocationCacheHandler {
private static final Cache<String, String> geolocationCache = CacheBuilder.newBuilder()
.maximumSize(10000)
.build();
/**
* Retrieves the country in full length (e.g. United States) from the IP Address.
* <p>
* This method uses the {@code geolocationCache}, every first access is getting cached and then retrieved later.
*
* @param ipAddress The IP Address from which the country is retrieved
* @return The name of the country in full length.
* <p>
* An exception from that rule is when the country is unknown or the retrieval of the country failed in any way,
* if that happens, "Not Known" will be returned.
* @see #getUncachedCountry(String)
*/
public static String getCountry(String ipAddress) {
Log.debug("Started country retrieval from IP Address " + ipAddress);
Map<String, String> geolocationMap = geolocationCache.asMap();
String country = geolocationMap.get(ipAddress);
Log.debug("Got country from " + ipAddress + " out of cache: " + country + " (if null, country wasn't cached)");
if (country != null) {
return country;
} else {
country = getUncachedCountry(ipAddress);
geolocationCache.put(ipAddress, country);
Log.debug("Got uncached country from IP Address " + ipAddress + ": " + country);
return country;
}
}
/**
* Retrieves the country in full length (e.g. United States) from the IP Address.
* <p>
* This method uses the free service of freegeoip.net. The maximum amount of requests is 15.000 per hour.
*
* @param ipAddress The IP Address from which the country is retrieved
* @return The name of the country in full length.
* <p>
* An exception from that rule is when the country is unknown or the retrieval of the country failed in any way,
* if that happens, "Not Known" will be returned.
* @see <a href="http://freegeoip.net">http://freegeoip.net</a>
* @see #getCountry(String)
*/
private static String getUncachedCountry(String ipAddress) {
Benchmark.start("getUncachedCountry");
try {
URL url = new URL("http://freegeoip.net/csv/" + ipAddress);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String resultLine = in.readLine();
Log.debug(resultLine);
in.close();
String[] results = resultLine.split(",");
String result = results[2];
return result.isEmpty() ? "Not Known" : result;
} catch (Exception exc) {
return "Not Known";
} finally {
Benchmark.stop("getUncachedCountry");
}
}
}

View File

@ -1,14 +1,5 @@
package main.java.com.djrapitops.plan.data.cache;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
@ -16,6 +7,10 @@ import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.ExportUtility;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
/**
* This class stores UserData objects used for displaying the Html pages.
*
@ -24,10 +19,9 @@ import main.java.com.djrapitops.plan.utilities.analysis.ExportUtility;
*/
public class InspectCacheHandler {
private DataCacheHandler handler;
private Plan plugin;
private Map<UUID, UserData> cache;
private Map<UUID, Long> cacheTimes;
private final DataCacheHandler handler;
private final Map<UUID, UserData> cache;
private final Map<UUID, Long> cacheTimes;
/**
* Class constructor.
@ -36,7 +30,6 @@ public class InspectCacheHandler {
*/
public InspectCacheHandler(Plan plugin) {
this.handler = plugin.getHandler();
this.plugin = plugin;
this.cache = new HashMap<>();
cacheTimes = new HashMap<>();
}
@ -62,6 +55,7 @@ public class InspectCacheHandler {
}
}
};
handler.getUserDataForProcessing(cacher, uuid, false);
}
@ -110,10 +104,7 @@ public class InspectCacheHandler {
* @return -1 when not cached or Epoch millisecond.
*/
public long getCacheTime(UUID uuid) {
if (cacheTimes.containsKey(uuid)) {
return cacheTimes.get(uuid);
}
return -1;
return cacheTimes.getOrDefault(uuid, -1L);
}
/**

View File

@ -1,17 +1,19 @@
package main.java.com.djrapitops.plan.data.cache.queue;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.stream.Collectors;
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 java.util.Collection;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.stream.Collectors;
/**
* This Class strats the Clear Queue Thread, that clears data from DataCache.
* This Class contains the Clear Queue Thread, which is clearing data from the DataCache.
*
* @author Rsl1122
* @since 3.0.0
@ -21,7 +23,7 @@ public class DataCacheClearQueue extends Queue<UUID> {
/**
* Class constructor, starts the new Thread for clearing.
*
* @param handler current instance of DataCachehandler.
* @param handler current instance of DataCacheHandler.
*/
public DataCacheClearQueue(DataCacheHandler handler) {
super(new ArrayBlockingQueue(Settings.PROCESS_CLEAR_LIMIT.getNumber()));
@ -48,7 +50,7 @@ public class DataCacheClearQueue extends Queue<UUID> {
if (uuids.isEmpty()) {
return;
}
uuids = uuids.stream().filter(u -> u != null).collect(Collectors.toList());
uuids = uuids.stream().filter(Objects::nonNull).collect(Collectors.toList());
Log.debug("Scheduling for clear: " + uuids);
try {
queue.addAll(uuids);

View File

@ -1,14 +1,5 @@
package main.java.com.djrapitops.plan.data.cache.queue;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
@ -16,6 +7,11 @@ 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 java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
* This Class is starts the Get Queue Thread, that fetches data from DataCache.
*
@ -36,7 +32,7 @@ public class DataCacheGetQueue extends Queue<Map<UUID, List<DBCallableProcessor>
}
/**
* Schedules UserData objects to be get for the given proecssors.
* Schedules UserData objects to be get for the given processors.
*
* @param uuid UUID of the player whose UserData object is fetched.
* @param processors Processors which process-method will be called after
@ -54,10 +50,7 @@ public class DataCacheGetQueue extends Queue<Map<UUID, List<DBCallableProcessor>
}
public boolean containsUUIDtoBeCached(UUID uuid) {
if (uuid == null) {
return false;
}
return new ArrayList<>(queue).stream().anyMatch((map) -> (map.get(uuid) != null && map.get(uuid).size() >= 2)); // Map has 2 processors if being cached
return uuid != null && new ArrayList<>(queue).stream().anyMatch((map) -> (map.get(uuid) != null && map.get(uuid).size() >= 2));
}
}

View File

@ -1,15 +1,16 @@
package main.java.com.djrapitops.plan.data.cache.queue;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.cache.DBCallableProcessor;
import main.java.com.djrapitops.plan.data.cache.DataCacheHandler;
import main.java.com.djrapitops.plan.data.handling.info.HandlingInfo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.cache.DBCallableProcessor;
import main.java.com.djrapitops.plan.data.cache.DataCacheHandler;
import main.java.com.djrapitops.plan.data.handling.info.HandlingInfo;
/**
* This Class is starts the Process Queue Thread, that processes HandlingInfo
@ -23,7 +24,7 @@ public class DataCacheProcessQueue extends Queue<HandlingInfo> {
/**
* Class constructor, starts the new Thread for processing.
*
* @param handler current instance of DataCachehandler.
* @param handler current instance of DataCacheHandler.
*/
public DataCacheProcessQueue(DataCacheHandler handler) {
super(new ArrayBlockingQueue(20000));
@ -65,10 +66,7 @@ public class DataCacheProcessQueue extends Queue<HandlingInfo> {
* @return true/false
*/
public boolean containsUUID(UUID uuid) {
if (uuid == null) {
return false;
}
return new ArrayList<>(queue).stream().anyMatch(info -> info.getUuid().equals(uuid));
return uuid != null && new ArrayList<>(queue).stream().anyMatch(info -> info.getUuid().equals(uuid));
}
}

View File

@ -1,12 +1,5 @@
package main.java.com.djrapitops.plan.data.cache.queue;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.stream.Collectors;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
@ -15,8 +8,16 @@ 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 java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.stream.Collectors;
/**
* This Class is starts the Save Queue Thread, that saves data to the Databse.
* This Class is starts the Save Queue Thread, that saves data to the Database.
*
* @author Rsl1122
* @since 3.0.0
@ -55,7 +56,7 @@ public class DataCacheSaveQueue extends Queue<UserData> {
* @param data Collection of UserData objects.
*/
public void scheduleForSave(Collection<UserData> data) {
Log.debug("Scheduling for save: " + data.stream().map(u -> u.getUuid()).collect(Collectors.toList()));
Log.debug("Scheduling for save: " + data.stream().map(UserData::getUuid).collect(Collectors.toList()));
try {
queue.addAll(data);
} catch (IllegalStateException e) {
@ -84,10 +85,7 @@ public class DataCacheSaveQueue extends Queue<UserData> {
* @return true/false
*/
public boolean containsUUID(UUID uuid) {
if (uuid == null) {
return false;
}
return new ArrayList<>(queue).stream().anyMatch(d -> d.getUuid().equals(uuid));
return uuid != null && new ArrayList<>(queue).stream().anyMatch(d -> d.getUuid().equals(uuid));
}
}

View File

@ -16,7 +16,7 @@ public abstract class Queue<T> {
Setup<T> setup;
/**
* Consturctor, defines queue.
* Constructor, defines queue.
*
* @param queue BlockingQueue to use for this queue.
*/

View File

@ -17,6 +17,7 @@ public abstract class Setup<T> {
*
* @param consumers Consumers for the new threads.
*/
@SafeVarargs
public Setup(Consumer<T>... consumers) {
this.consumers = consumers;
}

View File

@ -1,9 +1,10 @@
package main.java.com.djrapitops.plan.data.handling;
import com.djrapitops.plugin.utilities.player.Gamemode;
import java.util.Map;
import main.java.com.djrapitops.plan.data.UserData;
import java.util.Map;
/**
* Class containing static methods for processing information contained in a
* GamemodeChangeEvent.
@ -33,10 +34,7 @@ public class GamemodeHandling {
}
lastGamemode = data.getLastGamemode();
Map<String, Long> times = data.getGmTimes();
Long currentGMTime = times.get(lastGamemode);
if (currentGMTime == null) {
currentGMTime = 0L;
}
long currentGMTime = times.getOrDefault(lastGamemode, 0L);
data.setPlayTime(data.getPlayTime() + (time - data.getLastPlayed()));
data.setLastPlayed(time);
long lastSwap = data.getLastGmSwapTime();

View File

@ -1,11 +1,9 @@
package main.java.com.djrapitops.plan.data.handling;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.cache.GeolocationCacheHandler;
import java.net.InetAddress;
/**
* Class containing static methods for processing information contained in a
@ -39,29 +37,15 @@ public class LoginHandling {
/**
* Updates the geolocation of the player.
*
* Uses free service of freegeoip.net. 10000 requests can be sent per hour.
* Uses free service of freegeoip.net. 15000 requests can be sent per hour.
*
* @param ip InetAddress used for location.
* @param data UserData of the player.
* @see GeolocationCacheHandler
*/
public static void updateGeolocation(InetAddress ip, UserData data) {
try {
String result = "";
URL url = new URL("http://freegeoip.net/csv/" + ip.getHostAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String geoLocation = GeolocationCacheHandler.getCountry(ip.getHostAddress());
String resultline;
while ((resultline = in.readLine()) != null) {
result += resultline + ",";
}
in.close();
String[] results = result.split(",");
if (!results[2].isEmpty()) {
data.setGeolocation(results[2]);
}
} catch (Exception e) {
data.setGeolocation(Phrase.DEM_UNKNOWN + "");
}
data.setGeolocation(geoLocation);
}
}

View File

@ -21,10 +21,7 @@ public class ImportUtils {
* @return true/false
*/
public static boolean isPluginEnabled(String pluginName) {
if ("offline".equals(pluginName)) {
return true;
}
return getPluginManager().isPluginEnabled(pluginName);
return "offline".equals(pluginName) || getPluginManager().isPluginEnabled(pluginName);
}
/**

View File

@ -80,8 +80,7 @@ public abstract class Importer {
plan.processStatus().setStatus(processName, createUserObjects);
Map<UUID, IOfflinePlayer> offlinePlayers = Fetch.getIOfflinePlayers().stream().collect(Collectors.toMap(IOfflinePlayer::getUuid, Function.identity()));
Benchmark.start(createUserObjects);
List<IOfflinePlayer> offlineP = unSaved.stream().map(uuid
-> offlinePlayers.get(uuid)).collect(Collectors.toList());
List<IOfflinePlayer> offlineP = unSaved.stream().map(offlinePlayers::get).collect(Collectors.toList());
List<UserData> newUsers = new ArrayList<>();
for (IOfflinePlayer p : offlineP) {
UserData newPlayer = NewPlayerCreator.createNewOfflinePlayer(p);

View File

@ -1,9 +1,10 @@
package main.java.com.djrapitops.plan.data.handling.info;
import java.util.UUID;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.handling.ChatHandling;
import java.util.UUID;
/**
* HandlingInfo Class for ChatEvent information.
*
@ -12,8 +13,8 @@ import main.java.com.djrapitops.plan.data.handling.ChatHandling;
*/
public class ChatInfo extends HandlingInfo {
private String nickname;
private String message;
private final String nickname;
private final String message;
/**
* Constructor.

View File

@ -1,8 +1,9 @@
package main.java.com.djrapitops.plan.data.handling.info;
import java.util.UUID;
import main.java.com.djrapitops.plan.data.UserData;
import java.util.UUID;
/**
* An abstract class for processing information about events and modifying
* UserData objects associated with the events.
@ -12,9 +13,9 @@ import main.java.com.djrapitops.plan.data.UserData;
*/
public abstract class HandlingInfo {
UUID uuid;
InfoType type;
long time;
final UUID uuid;
final InfoType type;
final long time;
/**
* Super Constructor.

View File

@ -49,5 +49,5 @@ public enum InfoType {
*
* @since 3.1.1
*/
OTHER;
OTHER
}

View File

@ -1,10 +1,11 @@
package main.java.com.djrapitops.plan.data.handling.info;
import java.util.UUID;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.handling.KillHandling;
import org.bukkit.entity.LivingEntity;
import java.util.UUID;
/**
* HandlingInfo Class for DeathEvent information when the dead entity is a
* player.
@ -14,8 +15,8 @@ import org.bukkit.entity.LivingEntity;
*/
public class KillInfo extends HandlingInfo {
private LivingEntity dead;
private String weaponName;
private final LivingEntity dead;
private final String weaponName;
/**
* Constructor.

View File

@ -1,11 +1,12 @@
package main.java.com.djrapitops.plan.data.handling.info;
import com.djrapitops.plugin.utilities.player.Gamemode;
import java.net.InetAddress;
import java.util.UUID;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.handling.LoginHandling;
import java.net.InetAddress;
import java.util.UUID;
/**
* HandlingInfo Class for JoinEvent information.
*
@ -14,11 +15,11 @@ import main.java.com.djrapitops.plan.data.handling.LoginHandling;
*/
public class LoginInfo extends HandlingInfo {
private InetAddress ip;
private boolean banned;
private String nickname;
private GamemodeInfo gmInfo;
private int loginTimes;
private final InetAddress ip;
private final boolean banned;
private final String nickname;
private final GamemodeInfo gmInfo;
private final int loginTimes;
/**
* Constructor.

View File

@ -1,11 +1,12 @@
package main.java.com.djrapitops.plan.data.handling.info;
import com.djrapitops.plugin.utilities.player.Gamemode;
import java.util.UUID;
import main.java.com.djrapitops.plan.data.SessionData;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.handling.LogoutHandling;
import java.util.UUID;
/**
* HandlingInfo Class for QuitEvent information.
*
@ -14,9 +15,9 @@ import main.java.com.djrapitops.plan.data.handling.LogoutHandling;
*/
public class LogoutInfo extends HandlingInfo {
private boolean banned;
private SessionData sData;
private GamemodeInfo gmInfo;
private final boolean banned;
private final SessionData sData;
private final GamemodeInfo gmInfo;
/**
* Constructor.

View File

@ -1,11 +1,12 @@
package main.java.com.djrapitops.plan.data.handling.info;
import com.djrapitops.plugin.utilities.player.Gamemode;
import java.net.InetAddress;
import java.util.UUID;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.handling.LoginHandling;
import java.net.InetAddress;
import java.util.UUID;
/**
* HandlingInfo Class for refreshing data in the cache for online players.
*
@ -14,10 +15,10 @@ import main.java.com.djrapitops.plan.data.handling.LoginHandling;
*/
public class ReloadInfo extends HandlingInfo {
private InetAddress ip;
private boolean banned;
private String nickname;
private GamemodeInfo gmInfo;
private final InetAddress ip;
private final boolean banned;
private final String nickname;
private final GamemodeInfo gmInfo;
/**
* Constructor.

View File

@ -16,7 +16,6 @@ import org.bukkit.event.player.AsyncPlayerChatEvent;
*/
public class PlanChatListener implements Listener {
private final Plan plugin;
private final DataCacheHandler handler;
/**
@ -25,7 +24,6 @@ public class PlanChatListener implements Listener {
* @param plugin Current instance of Plan
*/
public PlanChatListener(Plan plugin) {
this.plugin = plugin;
handler = plugin.getHandler();
}

View File

@ -3,7 +3,9 @@ package main.java.com.djrapitops.plan.data.listeners;
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.data.cache.DataCacheHandler;
import org.bukkit.command.Command;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@ -40,12 +42,30 @@ public class PlanCommandPreprocessListener implements Listener {
if (event.isCancelled()) {
return;
}
String commandName = event.getMessage().split(" ")[0].toLowerCase();
boolean doNotLogUnknownCommands = Settings.DO_NOT_LOG_UNKNOWN_COMMANDS.isTrue();
boolean combineCommandAliasesToMainCommand = Settings.COMBINE_COMMAND_ALIASES_TO_MAIN_COMMAND.isTrue();
if (doNotLogUnknownCommands || combineCommandAliasesToMainCommand) {
Command command = plugin.getServer().getPluginCommand(commandName);
if (command == null) {
if (doNotLogUnknownCommands) {
Log.debug("Ignored command, command is unknown");
return;
}
} else if (combineCommandAliasesToMainCommand) {
commandName = command.getName();
}
}
Player player = event.getPlayer();
if (player.hasPermission(Permissions.IGNORE_COMMANDUSE.getPermission())) {
Log.debug("Ignored command, player had ignore permission.");
return;
}
handler.handleCommand(event.getMessage().split(" ")[0].toLowerCase());
handler.handleCommand(commandName);
}
}

View File

@ -20,7 +20,6 @@ import org.bukkit.event.entity.EntityDeathEvent;
*/
public class PlanDeathEventListener implements Listener {
private final Plan plugin;
private final DataCacheHandler handler;
/**
@ -29,7 +28,6 @@ public class PlanDeathEventListener implements Listener {
* @param plugin Current instance of Plan
*/
public PlanDeathEventListener(Plan plugin) {
this.plugin = plugin;
this.handler = plugin.getHandler();
}
@ -38,6 +36,7 @@ public class PlanDeathEventListener implements Listener {
*
* @param event Fired event.
*/
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.MONITOR)
public void onDeath(EntityDeathEvent event) {
long time = MiscUtils.getTime();
@ -50,7 +49,7 @@ public class PlanDeathEventListener implements Listener {
itemInHand = killer.getInventory().getItemInMainHand().getType();
} catch (Throwable e) {
try {
itemInHand = killer.getInventory().getItemInHand().getType();
itemInHand = killer.getInventory().getItemInHand().getType(); // Support for non dual wielding versions.
} catch (Throwable e2) {
itemInHand = Material.AIR;
}
@ -58,7 +57,7 @@ public class PlanDeathEventListener implements Listener {
handler.addToPool(new KillInfo(killer.getUniqueId(), time, dead, itemInHand.name()));
}
if (dead instanceof Player) {
handler.addToPool(new DeathInfo(((Player) dead).getUniqueId()));
handler.addToPool(new DeathInfo(dead.getUniqueId()));
}
}
}

View File

@ -18,7 +18,6 @@ import org.bukkit.event.player.PlayerGameModeChangeEvent;
*/
public class PlanGamemodeChangeListener implements Listener {
private final Plan plugin;
private final DataCacheHandler handler;
/**
@ -27,7 +26,6 @@ public class PlanGamemodeChangeListener implements Listener {
* @param plugin Current instance of Plan
*/
public PlanGamemodeChangeListener(Plan plugin) {
this.plugin = plugin;
handler = plugin.getHandler();
}

View File

@ -1,10 +1,8 @@
package main.java.com.djrapitops.plan.data.listeners;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.task.ITask;
import com.djrapitops.plugin.utilities.player.Gamemode;
import com.djrapitops.plugin.utilities.player.bukkit.BukkitPlayer;
import java.util.UUID;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
@ -22,6 +20,8 @@ import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.UUID;
/**
* Event Listener for PlayerJoin, PlayerQuit and PlayerKickEvents.
*
@ -59,7 +59,7 @@ public class PlanPlayerListener implements Listener {
UUID uuid = player.getUniqueId();
handler.startSession(uuid);
Log.debug(uuid + ": PlayerJoinEvent");
ITask asyncNewPlayerCheckTask = plugin.getRunnableFactory().createNew(new AbsRunnable("NewPlayerCheckTask") {
plugin.getRunnableFactory().createNew(new AbsRunnable("NewPlayerCheckTask") {
@Override
public void run() {
LoginInfo loginInfo = new LoginInfo(uuid, MiscUtils.getTime(), player.getAddress().getAddress(), player.isBanned(), player.getDisplayName(), Gamemode.wrap(player.getGameMode()), 1);
@ -112,8 +112,10 @@ public class PlanPlayerListener implements Listener {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
handler.endSession(uuid);
Log.debug(uuid + ": PlayerKickEvent");
handler.addToPool(new LogoutInfo(uuid, MiscUtils.getTime(), player.isBanned(), Gamemode.wrap(player.getGameMode()), handler.getSession(uuid)));
handler.addToPool(new KickInfo(uuid));
handler.saveCachedData(uuid);
Log.debug(uuid + ": PlayerKickEvent_END");
}
}

View File

@ -2,13 +2,17 @@ package main.java.com.djrapitops.plan.data.listeners;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.task.AbsRunnable;
import java.util.ArrayList;
import java.util.List;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.data.cache.DataCacheHandler;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.util.ArrayList;
import java.util.List;
/**
* Class responsible for calculating TPS every second.
@ -32,36 +36,93 @@ public class TPSCountTimer extends AbsRunnable {
@Override
public void run() {
long nanotime = System.nanoTime();
long nanoTime = System.nanoTime();
long now = MiscUtils.getTime();
long diff = nanotime - lastCheckNano;
lastCheckNano = nanotime;
if (diff > nanotime) { // First run's diff = nanotime + 1, no calc possible.
long diff = nanoTime - lastCheckNano;
lastCheckNano = nanoTime;
if (diff > nanoTime) { // First run's diff = nanoTime + 1, no calc possible.
Log.debug("First run of TPSCountTimer Task.");
return;
}
diff -= TimeAmount.MILLISECOND.ns() * 40L; // 40ms Removed because the run appears to take 40-50ms, scewing the tps.
TPS tps = calculateTPS(diff, now);
history.add(tps);
if (history.size() >= 60) {
handler.addTPSLastMinute(history);
history.clear();
}
}
public TPS calculateTPS(long diff, long now) {
/**
* Calculates the TPS
*
* @param diff The time difference between the last run and the new run
* @param now The time right now
* @return the TPS
*/
private TPS calculateTPS(long diff, long now) {
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
int availableProcessors = operatingSystemMXBean.getAvailableProcessors();
double averageCPUUsage = MathUtils.round(operatingSystemMXBean.getSystemLoadAverage() / availableProcessors * 100.0);
if (averageCPUUsage < 0) { // If Unavailable, getSystemLoadAverage() returns -1
averageCPUUsage = -1;
}
int playersOnline = plugin.getServer().getOnlinePlayers().size();
if (plugin.getVariable().isUsingPaper()) {
return getTPSPaper(now, averageCPUUsage, playersOnline);
} else {
diff -= TimeAmount.MILLISECOND.ns() * 40L; // 40ms removed because the run appears to take 40-50ms, screwing the tps.
return getTPS(diff, now, averageCPUUsage, playersOnline);
}
}
/**
* Gets the TPS for Paper
*
* @param now The time right now
* @param cpuUsage The usage of the CPU
* @param playersOnline The amount of players that are online
* @return the TPS
*/
private TPS getTPSPaper(long now, double cpuUsage, int playersOnline) {
double tps = plugin.getServer().getTPS()[0];
if (tps > 20) {
tps = 20;
}
tps = MathUtils.round(tps);
return new TPS(now, tps, playersOnline, cpuUsage);
}
/**
* Gets the TPS for a Spigot / Bukkit
*
* @param diff The difference between the last run and this run
* @param now The time right now
* @param cpuUsage The usage of the CPU
* @param playersOnline The amount of players that are online
* @return the TPS
*/
private TPS getTPS(long diff, long now, double cpuUsage, int playersOnline) {
if (diff < TimeAmount.SECOND.ns()) { // No tick count above 20
diff = TimeAmount.SECOND.ns();
}
int playersOnline = plugin.getServer().getOnlinePlayers().size();
long twentySeconds = 20L * TimeAmount.SECOND.ns();
while (diff > twentySeconds) {
history.add(new TPS(now, 0, playersOnline));
history.add(new TPS(now, 0, playersOnline, cpuUsage));
diff -= twentySeconds;
}
double tpsN = twentySeconds / diff;
TPS tps = new TPS(now, tpsN, playersOnline);
return tps;
return new TPS(now, tpsN, playersOnline, cpuUsage);
}
}

View File

@ -1,26 +1,17 @@
package main.java.com.djrapitops.plan.database;
import java.sql.SQLException;
import java.util.*;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.cache.DBCallableProcessor;
import main.java.com.djrapitops.plan.database.tables.CommandUseTable;
import main.java.com.djrapitops.plan.database.tables.GMTimesTable;
import main.java.com.djrapitops.plan.database.tables.IPsTable;
import main.java.com.djrapitops.plan.database.tables.KillsTable;
import main.java.com.djrapitops.plan.database.tables.LocationsTable;
import main.java.com.djrapitops.plan.database.tables.NicknamesTable;
import main.java.com.djrapitops.plan.database.tables.SecurityTable;
import main.java.com.djrapitops.plan.database.tables.SessionsTable;
import main.java.com.djrapitops.plan.database.tables.TPSTable;
import main.java.com.djrapitops.plan.database.tables.UsersTable;
import main.java.com.djrapitops.plan.database.tables.VersionTable;
import main.java.com.djrapitops.plan.database.tables.*;
import java.sql.SQLException;
import java.util.*;
/**
* Abstract class representing a Database.
*
* All methods should be only called from an asyncronous thread, unless stated
* All methods should be only called from an asynchronous thread, unless stated
* otherwise.
*
* @author Rsl1122
@ -235,9 +226,8 @@ public abstract class Database {
* Uses DELETE * FROM table.
*
* @return Success of removal.
* @throws SQLException If a database error occurs.
*/
public abstract boolean removeAllData() throws SQLException;
public abstract boolean removeAllData();
/**
* Used to save CommandUse map.

View File

@ -36,9 +36,8 @@ public class MySQLDB extends SQLDB {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://" + config.getString("mysql.host") + ":" + config.getString("mysql.port") + "/" + config.getString("mysql.database");
Connection connection = DriverManager.getConnection(url, config.getString("mysql.user"), config.getString("mysql.password"));
return connection;
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()));
return null;

View File

@ -1,28 +1,24 @@
package main.java.com.djrapitops.plan.database.databases;
import com.djrapitops.plugin.task.AbsRunnable;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.*;
import main.java.com.djrapitops.plan.data.KillData;
import main.java.com.djrapitops.plan.data.SessionData;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.cache.DBCallableProcessor;
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 java.net.InetAddress;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
*
* @author Rsl1122
@ -59,8 +55,6 @@ public abstract class SQLDB extends Database {
}
/**
*
* @param plugin
* @throws IllegalArgumentException
* @throws IllegalStateException
*/
@ -128,7 +122,7 @@ public abstract class SQLDB extends Database {
}
if (newDatabase) {
Log.info("New Database created.");
setVersion(5);
setVersion(6);
}
Benchmark.start("Database: Create tables");
for (Table table : getAllTables()) {
@ -142,8 +136,8 @@ public abstract class SQLDB extends Database {
return false;
}
Benchmark.stop("Database: Create tables");
if (!newDatabase && getVersion() < 5) {
setVersion(5);
if (!newDatabase && getVersion() < 6) {
setVersion(6);
}
}
return true;
@ -279,16 +273,7 @@ public abstract class SQLDB extends Database {
return false;
}
int userId = usersTable.getUserId(uuid);
if (userId == -1) {
return false;
}
return locationsTable.removeUserLocations(userId)
&& ipsTable.removeUserIps(userId)
&& nicknamesTable.removeUserNicknames(userId)
&& gmTimesTable.removeUserGMTimes(userId)
&& sessionsTable.removeUserSessions(userId)
&& killsTable.removeUserKillsAndVictims(userId)
&& usersTable.removeUser(uuid);
return userId != -1 && locationsTable.removeUserLocations(userId) && ipsTable.removeUserIps(userId) && nicknamesTable.removeUserNicknames(userId) && gmTimesTable.removeUserGMTimes(userId) && sessionsTable.removeUserSessions(userId) && killsTable.removeUserKillsAndVictims(userId) && usersTable.removeUser(uuid);
} finally {
Benchmark.stop("Database: Remove Account");
setAvailable();
@ -334,9 +319,7 @@ public abstract class SQLDB extends Database {
List<SessionData> sessions = sessionsTable.getSessionData(userId);
data.addSessions(sessions);
data.setPlayerKills(killsTable.getPlayerKills(userId));
processors.stream().forEach((processor) -> {
processor.process(data);
});
processors.forEach((processor) -> processor.process(data));
Benchmark.stop("Database: Give userdata to processors");
setAvailable();
}
@ -368,7 +351,7 @@ public abstract class SQLDB extends Database {
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(e -> e.getValue()).collect(Collectors.toList());
List<Integer> ids = userIds.entrySet().stream().filter(e -> uuids.contains(e.getKey())).map(Map.Entry::getValue).collect(Collectors.toList());
Log.debug("Ids: " + ids.size());
Map<Integer, List<String>> nicknames = nicknamesTable.getNicknames(ids);
Map<Integer, Set<InetAddress>> ipList = ipsTable.getIPList(ids);
@ -439,11 +422,9 @@ public abstract class SQLDB extends Database {
sessionsTable.saveSessionData(sessions);
gmTimesTable.saveGMTimes(gmTimes);
userDatas.values().stream()
.filter(u -> u != null)
.filter(uData -> uData.isAccessed())
.forEach(uData -> {
uData.stopAccessing();
});
.filter(Objects::nonNull)
.filter(UserData::isAccessed)
.forEach(UserData::stopAccessing);
Benchmark.stop("Database: Save multiple Userdata");
setAvailable();
}

View File

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

View File

@ -1,16 +1,13 @@
package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import java.util.*;
/**
*
@ -151,7 +148,7 @@ public class GMTimesTable extends Table {
}
PreparedStatement statement = null;
String[] gms = getGMKeyArray();
int update = 0;
int update;
try {
statement = prepareStatement(
"UPDATE " + tableName + " SET "

View File

@ -240,7 +240,7 @@ public class KillsTable extends Table {
if (victimUserID == -1) {
List<Integer> matchingIds = uuids.entrySet()
.stream().filter(e -> e.getValue().equals(kill.getVictim()))
.map(e -> e.getKey())
.map(Map.Entry::getKey)
.collect(Collectors.toList());
if (matchingIds.isEmpty()) {
continue;

View File

@ -5,14 +5,15 @@
*/
package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
/**
*
@ -93,11 +94,10 @@ public class SecurityTable extends Table {
statement = prepareStatement("SELECT * FROM " + tableName + " WHERE (" + columnUser + "=?)");
statement.setString(1, user);
set = statement.executeQuery();
while (set.next()) {
if (set.next()) {
String saltedPassHash = set.getString(columnSaltedHash);
int permissionLevel = set.getInt(columnPermLevel);
WebUser info = new WebUser(user, saltedPassHash, permissionLevel);
return info;
return new WebUser(user, saltedPassHash, permissionLevel);
}
return null;
} finally {

View File

@ -1,15 +1,5 @@
package main.java.com.djrapitops.plan.database.tables;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.SessionData;
import main.java.com.djrapitops.plan.database.Container;
@ -18,6 +8,11 @@ import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.ManageUtils;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
*
* @author Rsl1122
@ -267,7 +262,7 @@ public class SessionsTable extends Table {
Map<Integer, Integer> loginTimes = db.getUsersTable().getLoginTimes();
Map<Integer, List<SessionData>> allSessions = getSessionData(loginTimes.keySet());
Benchmark.start("Database: Combine Sessions");
int before = MathUtils.sumInt(allSessions.values().stream().map(l -> l.size()));
int before = MathUtils.sumInt(allSessions.values().stream().map(List::size));
Log.debug("Sessions before: " + before);
Map<Integer, Integer> beforeM = new HashMap<>();
Map<Integer, Integer> afterM = new HashMap<>();
@ -287,13 +282,11 @@ public class SessionsTable extends Table {
afterM.put(id, combined.size());
allSessions.put(id, combined);
}
int after = MathUtils.sumInt(allSessions.values().stream().map(l -> l.size()));
int after = MathUtils.sumInt(allSessions.values().stream().map(List::size));
Log.debug("Sessions after: " + after);
if (before - after > 50) {
Benchmark.start("Database: Save combined sessions");
Iterator<Integer> iterator = new HashSet<>(allSessions.keySet()).iterator();
while (iterator.hasNext()) {
int id = iterator.next();
for (Integer id : new HashSet<>(allSessions.keySet())) {
if (afterM.get(id) < beforeM.get(id)) {
removeUserSessions(id);
} else {

View File

@ -1,11 +1,6 @@
package main.java.com.djrapitops.plan.database.tables;
import com.djrapitops.plugin.api.TimeAmount;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.database.DBUtils;
@ -13,6 +8,12 @@ import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Class representing database table plan_tps
*
@ -24,9 +25,9 @@ public class TPSTable extends Table {
private final String columnDate;
private final String columnTPS;
private final String columnPlayers;
private final String columnCPUUsage;
/**
*
* @param db
* @param usingMySQL
*/
@ -35,6 +36,7 @@ public class TPSTable extends Table {
columnDate = "date";
columnTPS = "tps";
columnPlayers = "players_online";
columnCPUUsage = "cpu_usage";
}
@Override
@ -43,9 +45,14 @@ public class TPSTable extends Table {
execute("CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ columnDate + " bigint NOT NULL, "
+ columnTPS + " double NOT NULL, "
+ columnPlayers + " integer NOT NULL"
+ columnPlayers + " integer NOT NULL, "
+ columnCPUUsage + " double NOT NULL"
+ ")"
);
int version = getVersion();
if (version < 6) {
alterTablesV6();
}
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
@ -53,8 +60,19 @@ public class TPSTable extends Table {
}
}
private void alterTablesV6() {
try {
if (usingMySQL) {
execute("ALTER TABLE " + tableName + " ADD " + columnCPUUsage + " double NOT NULL DEFAULT 0");
} else {
execute("ALTER TABLE " + tableName + " ADD COLUMN " + columnCPUUsage + " double NOT NULL DEFAULT 0");
}
} catch (SQLException e) {
}
}
/**
*
* @return @throws SQLException
*/
public List<TPS> getTPSData() throws SQLException {
@ -69,7 +87,8 @@ public class TPSTable extends Table {
long date = set.getLong(columnDate);
double tps = set.getDouble(columnTPS);
int players = set.getInt(columnPlayers);
data.add(new TPS(date, tps, players));
double cpuUsage = set.getDouble(columnCPUUsage);
data.add(new TPS(date, tps, players, cpuUsage));
}
return data;
} finally {
@ -80,7 +99,6 @@ public class TPSTable extends Table {
}
/**
*
* @param data
* @throws SQLException
*/
@ -97,8 +115,9 @@ public class TPSTable extends Table {
statement = prepareStatement("INSERT INTO " + tableName + " ("
+ columnDate + ", "
+ columnTPS + ", "
+ columnPlayers
+ ") VALUES (?, ?, ?)");
+ columnPlayers + ", "
+ columnCPUUsage
+ ") VALUES (?, ?, ?, ?)");
boolean commitRequired = false;
int i = 0;
@ -106,6 +125,7 @@ public class TPSTable extends Table {
statement.setLong(1, tps.getDate());
statement.setDouble(2, tps.getTps());
statement.setInt(3, tps.getPlayers());
statement.setDouble(4, tps.getCPUUsage());
statement.addBatch();
commitRequired = true;
i++;
@ -120,7 +140,6 @@ public class TPSTable extends Table {
}
/**
*
* @throws SQLException
*/
public void clean() throws SQLException {

View File

@ -1,15 +1,16 @@
package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.database.Container;
import main.java.com.djrapitops.plan.database.DBUtils;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.database.Container;
import main.java.com.djrapitops.plan.database.DBUtils;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
/**
*
@ -20,17 +21,17 @@ public abstract class Table {
/**
*
*/
protected String tableName;
protected final String tableName;
/**
*
*/
protected SQLDB db;
protected final SQLDB db;
/**
*
*/
protected boolean usingMySQL;
protected final boolean usingMySQL;
/**
*
@ -78,8 +79,7 @@ public abstract class Table {
*/
protected boolean execute(String sql) throws SQLException {
Connection connection = getConnection();
boolean success = connection.createStatement().execute(sql);
return success;
return connection.createStatement().execute(sql);
}
/**

View File

@ -1,19 +1,6 @@
package main.java.com.djrapitops.plan.database.tables;
import com.djrapitops.plugin.utilities.player.Fetch;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.database.DBUtils;
@ -22,6 +9,13 @@ import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.uuid.UUIDUtility;
import org.bukkit.GameMode;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
*
* @author Rsl1122
@ -252,9 +246,6 @@ public class UsersTable extends Table {
set = statement.executeQuery();
while (set.next()) {
UUID uuid = UUID.fromString(set.getString(columnUUID));
if (uuid == null) {
continue;
}
uuids.add(uuid);
}
return uuids;
@ -400,8 +391,7 @@ public class UsersTable extends Table {
statement = prepareStatement("SELECT * FROM " + tableName + " WHERE (" + columnUUID + "=?)");
statement.setString(1, uuid.toString());
set = statement.executeQuery();
while (set.next()) {
if (set.next()) {
String gm = set.getString(columnLastGM);
boolean op = set.getBoolean(columnOP);
boolean banned = set.getBoolean(columnBanned);
@ -647,7 +637,7 @@ public class UsersTable extends Table {
private String getUpdateStatement() {
final boolean hasV4Columns = tableHasV4Columns();
String v4rows = hasV4Columns ? columnDemAge + "=-1, " + columnDemGender + "='Deprecated', " : "";
String sql = "UPDATE " + tableName + " SET "
return "UPDATE " + tableName + " SET "
+ v4rows
+ columnGeolocation + "=?, "
+ columnLastGM + "=?, "
@ -663,7 +653,6 @@ public class UsersTable extends Table {
+ columnName + "=?, "
+ columnRegistered + "=? "
+ "WHERE " + columnUUID + "=?";
return sql;
}
/**
@ -892,10 +881,9 @@ public class UsersTable extends Table {
statement = prepareStatement("SELECT " + columnUUID + " FROM " + tableName + " WHERE (UPPER(" + columnName + ")=UPPER(?))");
statement.setString(1, playername);
set = statement.executeQuery();
while (set.next()) {
if (set.next()) {
String uuidS = set.getString(columnUUID);
UUID uuid = UUID.fromString(uuidS);
return uuid;
return UUID.fromString(uuidS);
}
return null;
} finally {

View File

@ -1,7 +1,5 @@
package main.java.com.djrapitops.plan.ui.html;
import java.io.FileNotFoundException;
import java.util.UUID;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.cache.AnalysisCacheHandler;
@ -9,13 +7,15 @@ import main.java.com.djrapitops.plan.data.cache.InspectCacheHandler;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.PlaceholderUtils;
import java.io.FileNotFoundException;
import java.util.UUID;
/**
*
* @author Rsl1122
*/
public class DataRequestHandler {
private final Plan plugin;
private final InspectCacheHandler inspectCache;
private final AnalysisCacheHandler analysisCache;
@ -25,7 +25,6 @@ public class DataRequestHandler {
* @param plugin Current instance of Plan
*/
public DataRequestHandler(Plan plugin) {
this.plugin = plugin;
this.inspectCache = plugin.getInspectCache();
this.analysisCache = plugin.getAnalysisCache();
}

View File

@ -107,7 +107,7 @@ public enum Html {
private String html;
private Html(String html) {
Html(String html) {
this.html = html;
}

View File

@ -1,8 +1,9 @@
package main.java.com.djrapitops.plan.ui.html;
import java.util.List;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import java.util.List;
/**
*
* @author Rsl1122
@ -12,9 +13,9 @@ public class RecentPlayersButtonsCreator {
/**
* Creates recent players buttons inside a p-tag.
*
* @param names Playernames sorted by last playtime.
* @param limit How many playes will be shown
* @return html p-tag list of recent logins.
* @param names The name of players sorted by last playtime.
* @param limit How many players will be shown
* @return html p-tag list of recent log-ins.
*/
public static String createRecentLoginsButtons(List<String> names, int limit) {
StringBuilder html = new StringBuilder();
@ -22,7 +23,7 @@ public class RecentPlayersButtonsCreator {
for (int i = 0; i < names.size(); i++) {
if (i < limit) {
String name = names.get(i);
html.append(Html.BUTTON.parse(HtmlUtils.getInspectUrl(name), name));
html.append(Html.BUTTON.parse(HtmlUtils.getRelativeInspectUrl(name), name));
html.append(" ");
}
}

View File

@ -0,0 +1,20 @@
package main.java.com.djrapitops.plan.ui.html.graphs;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.Point;
import java.util.List;
import java.util.stream.Collectors;
public class CPUGraphCreator {
public static String buildScatterDataString(List<TPS> tpsData, long scale) {
long now = MiscUtils.getTime();
List<Point> points = tpsData.stream()
.filter(tps -> tps.getDate() >= now - scale)
.map(tps -> new Point(tps.getDate(), Double.parseDouble(FormatUtils.cutDecimals(tps.getCPUUsage()).replace(",", "."))))
.collect(Collectors.toList());
return ScatterGraphCreator.scatterGraph(points, true);
}
}

View File

@ -1,180 +1,49 @@
package main.java.com.djrapitops.plan.ui.html.graphs;
import com.djrapitops.plugin.api.TimeAmount;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.SessionData;
import main.java.com.djrapitops.plan.data.TPS;
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 main.java.com.djrapitops.plan.utilities.analysis.DouglasPeckerAlgorithm;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import main.java.com.djrapitops.plan.utilities.analysis.Point;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* @author Rsl1122
*/
public class PlayerActivityGraphCreator {
@Deprecated
public static String[] generateArray(List<TPS> tpsData, long scale) {
long now = MiscUtils.getTime();
List<TPS> filtered = tpsData.stream().filter(tps -> tps.getDate() >= now - scale).collect(Collectors.toList());
String players = filtered.stream().map(tps -> tps.getPlayers()).collect(Collectors.toList()).toString();
String dates = filtered.stream().map(tps -> tps.getDate()).collect(Collectors.toList()).toString();
return new String[]{players, dates};
}
public static String buildScatterDataString(List<TPS> tpsData, long scale) {
long now = MiscUtils.getTime();
List<Point> points = tpsData.stream().filter(tps -> tps.getDate() >= now - scale).map(tps -> new Point(tps.getDate(), tps.getPlayers())).collect(Collectors.toList());
List<Point> points = tpsData.stream()
.filter(tps -> tps.getDate() >= now - scale)
.map(tps -> new Point(tps.getDate(), tps.getPlayers()))
.collect(Collectors.toList());
return ScatterGraphCreator.scatterGraph(points, true);
}
/**
*
* @param sessionData
* @param scale
* @return
*/
public static String[] generateDataArray(List<SessionData> sessionData, long scale) {
public static String buildScatterDataStringSessions(List<SessionData> sessionData, long scale) {
long now = MiscUtils.getTime();
long nowMinusScale = now - scale;
List<List<Long>> s = filterAndTransformSessions(sessionData, nowMinusScale);
List<Long> sessionStarts = s.get(0);
List<Long> sessionEnds = s.get(1);
List<SessionData> filtered = filterSessions(sessionData, nowMinusScale);
int amount = (int) sessionStarts.stream().filter(start -> start < nowMinusScale).count();
for (int i = amount; i > 0; i--) {
sessionStarts.add(nowMinusScale);
}
Map<Long, Integer> change = transformIntoChangeMap(sessionStarts, sessionEnds);
long lastPValue = 0;
long lastSavedPValue = -1;
long lastSaveIndex = 0;
List<Long> playersOnline = new ArrayList<>();
List<String> labels = new ArrayList<>();
for (long i = nowMinusScale / 1000; i <= now / 1000; i += 1) {
long index = i * 1000;
boolean contains = change.containsKey(index);
boolean isBelowMinimumScaleThreshold = index - lastSaveIndex > (scale / (long) 75);
if (!(contains || isBelowMinimumScaleThreshold)) {
continue;
}
if (contains) {
lastPValue += change.get(index);
}
if (isBelowMinimumScaleThreshold || lastSavedPValue != lastPValue) {
lastSaveIndex = index;
labels.add("\"" + FormatUtils.formatTimeStamp(index) + "\"");
lastSavedPValue = lastPValue;
playersOnline.add(lastPValue);
}
}
if (Settings.ANALYSIS_REMOVE_OUTLIERS.isTrue()) {
long average = MathUtils.averageLong(playersOnline.stream());
double standardDiviation = getStandardDiviation(playersOnline, average);
if (standardDiviation > 3.5) {
for (int i = 0; i < playersOnline.size(); i++) {
long value = playersOnline.get(i);
if (value - average > 3 * standardDiviation) {
playersOnline.set(i, (long) Plan.getInstance().getVariable().getMaxPlayers() + 10);
}
}
}
}
return new String[]{playersOnline.toString(), labels.toString()};
}
private static double getStandardDiviation(List<Long> players, long avg) {
List<Double> valueMinusAvg = players.stream()
.map(p -> Math.pow(Math.abs(p - avg), 2))
List<Point> points = filtered.stream()
.map(session -> new Point[]{new Point(session.getSessionStart(), 1), new Point(session.getSessionEnd(), 0)})
.flatMap(Arrays::stream)
.collect(Collectors.toList());
int size = valueMinusAvg.size();
double sum = MathUtils.sumDouble(valueMinusAvg.stream().map(p -> (Serializable) p));
return Math.sqrt(sum / size);
Log.debug(points.stream().map(Point::getY).collect(Collectors.toList()).toString());
return ScatterGraphCreator.scatterGraph(points, true, false);
}
private static Map<Long, Integer> transformIntoChangeMap(List<Long> sessionStarts, List<Long> sessionEnds) {
Map<Long, Integer> starts = sessionStarts.stream().distinct().collect(Collectors.toMap(Function.identity(), start -> Collections.frequency(sessionStarts, start)));
Map<Long, Integer> ends = sessionEnds.stream().distinct().collect(Collectors.toMap(Function.identity(), end -> Collections.frequency(sessionEnds, end)));
Set<Long> keys = new HashSet<>(starts.keySet());
keys.addAll(ends.keySet());
Map<Long, Integer> change = new HashMap<>();
keys.stream().forEach((key) -> {
int value = 0;
if (starts.containsKey(key)) {
value += starts.get(key);
}
if (ends.containsKey(key)) {
value -= ends.get(key);
}
change.put(key, value);
});
return change;
}
/**
*
* @param values
* @param lookFor
* @return
*/
public static long getCount(List<Long> values, long lookFor) {
return Collections.frequency(values, lookFor);
// values.stream()
// .filter((start) -> (start == lookFor))
// .count();
}
/**
*
* @param sessionData
* @param nowMinusScale
* @return
*/
public static List<List<Long>> filterAndTransformSessions(List<SessionData> sessionData, long nowMinusScale) {
List<Long[]> values = sessionData.parallelStream()
private static List<SessionData> filterSessions(List<SessionData> sessions, long nowMinusScale) {
return sessions.parallelStream()
.filter(session -> (session != null))
.filter(session -> session.isValid() || session.getSessionEnd() == -1)
.filter((session) -> (session.getSessionStart() >= nowMinusScale || session.getSessionEnd() >= nowMinusScale))
.map(session -> new Long[]{session.getSessionStart(), session.getSessionEnd()})
.distinct()
.collect(Collectors.toList());
List<Long> sessionStarts = new ArrayList<>();
List<Long> sessionEnds = new ArrayList<>();
for (Long[] startAndEnd : values) {
sessionStarts.add(getSecond(startAndEnd[0]));
Long end = startAndEnd[1];
if (end != -1) {
sessionEnds.add(getSecond(end));
}
}
List<List<Long>> r = new ArrayList<>();
r.add(sessionStarts);
r.add(sessionEnds);
return r;
}
/**
*
* @param ms
* @return
*/
public static long getSecond(long ms) {
return ms - (ms % 1000);
}
}

View File

@ -5,16 +5,17 @@
*/
package main.java.com.djrapitops.plan.ui.html.graphs;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.SessionData;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.AnalysisUtils;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
*
* @author Rsl1122
@ -27,7 +28,6 @@ public class PunchCardGraphCreator {
* @return
*/
public static String generateDataArray(Collection<SessionData> data) {
// Initialize dataset
List<Long> sessionStarts = getSessionStarts(data);
List<int[]> daysAndHours = AnalysisUtils.getDaysAndHours(sessionStarts);
int[][] dataArray = createDataArray(daysAndHours);
@ -47,7 +47,7 @@ public class PunchCardGraphCreator {
continue;
}
arrayBuilder.append("{").append("x:").append(j).append(", y:").append(i).append(", r:").append(value).append("}");
if (!(i == 6 && j == 23)) {
if (i != 6 || j != 23) {
arrayBuilder.append(",");
}
}
@ -65,14 +65,13 @@ public class PunchCardGraphCreator {
}
if (Settings.ANALYSIS_REMOVE_OUTLIERS.isTrue()) {
int avg = findAverage(dataArray);
double standardDiviation = getStandardDiviation(dataArray, avg);
Log.debug("Diviation: " + standardDiviation);
if (standardDiviation > 3.5) {
double standardDeviation = getStandardDeviation(dataArray, avg);
if (standardDeviation > 3.5) {
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 24; j++) {
int value = dataArray[i][j];
if (value - avg > 3 * standardDiviation) {
dataArray[i][j] = (int) (avg);
if (value - avg > 3 * standardDeviation) {
dataArray[i][j] = avg;
}
}
}
@ -81,7 +80,7 @@ public class PunchCardGraphCreator {
return dataArray;
}
private static double getStandardDiviation(int[][] array, int avg) {
private static double getStandardDeviation(int[][] array, int avg) {
int[][] valueMinusAvg = new int[7][24];
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 24; j++) {
@ -111,14 +110,13 @@ public class PunchCardGraphCreator {
private static List<Long> getSessionStarts(Collection<SessionData> data) {
long now = MiscUtils.getTime();
List<Long> sessionStarts = data.stream()
.filter(s -> s != null)
.filter(s -> s.isValid())
.map(s -> s.getSessionStart())
return data.stream()
.filter(Objects::nonNull)
.filter(SessionData::isValid)
.map(SessionData::getSessionStart)
.filter(start -> now - start < (long) 2592000 * (long) 1000)
.sorted()
.collect(Collectors.toList());
return sessionStarts;
}
private static int[][] createEmptyArray() {
@ -156,7 +154,6 @@ public class PunchCardGraphCreator {
scaled[i][j] = value;
}
}
Log.debug("Punchcard Biggest value: " + big);
return scaled;
}
}

View File

@ -7,16 +7,14 @@ package main.java.com.djrapitops.plan.ui.html.graphs;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.utilities.Verify;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.DouglasPeckerAlgorithm;
import main.java.com.djrapitops.plan.utilities.analysis.Point;
import main.java.com.djrapitops.plan.utilities.comparators.PointComparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Abstract scatter graph creator used by other graph creators.
*
@ -26,18 +24,22 @@ import main.java.com.djrapitops.plan.utilities.comparators.PointComparator;
public class ScatterGraphCreator {
public static String scatterGraph(List<Point> points, boolean reduceGapTriangles) {
return scatterGraph(points, reduceGapTriangles, true);
}
public static String scatterGraph(List<Point> points, boolean reduceGapTriangles, boolean reducePoints) {
StringBuilder arrayBuilder = new StringBuilder();
arrayBuilder.append("[");
points = DouglasPeckerAlgorithm.reducePoints(points, 0);
if (reducePoints) {
points = DouglasPeckerAlgorithm.reducePoints(points, 0);
}
if (reduceGapTriangles) {
Point lastPoint = null;
Set<Point> toAdd = new HashSet<>();
Iterator<Point> iterator = points.iterator();
while (iterator.hasNext()) {
Point point = iterator.next();
for (Point point : points) {
if (Verify.notNull(point, lastPoint)) {
long date = (long) point.getX();
long lastDate = (long) lastPoint.getX();
@ -53,7 +55,7 @@ public class ScatterGraphCreator {
lastPoint = point;
}
points.addAll(toAdd);
Collections.sort(points, new PointComparator());
points.sort(new PointComparator());
}
int size = points.size();

View File

@ -1,14 +1,13 @@
package main.java.com.djrapitops.plan.ui.html.graphs;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.TPS;
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 main.java.com.djrapitops.plan.utilities.analysis.Point;
import main.java.com.djrapitops.plan.utilities.comparators.TPSComparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
*
@ -17,28 +16,18 @@ import main.java.com.djrapitops.plan.utilities.comparators.TPSComparator;
*/
public class TPSGraphCreator {
public static String[] generateDataArray(List<TPS> tpsData, long scale) {
Benchmark.start("TPSGraph: generate array");
long now = MiscUtils.getTime();
List<TPS> filtered = filterTPS(tpsData, now - scale);
Log.debug("TPSGraph, filtered: " + filtered.size());
Collections.sort(filtered, new TPSComparator());
List<Long> dates = filtered.stream().map(t -> t.getDate()).collect(Collectors.toList());
List<Double> tps = filtered.stream().map(t -> t.getTps()).collect(Collectors.toList());
List<Integer> players = filtered.stream().map(t -> t.getPlayers()).collect(Collectors.toList());
Benchmark.stop("TPSGraph: generate array");
return new String[]{dates.toString(), tps.toString(), players.toString()};
}
public static String buildScatterDataStringTPS(List<TPS> tpsData, long scale) {
long now = MiscUtils.getTime();
List<Point> points = tpsData.stream().filter(tps -> tps.getDate() >= now - scale).map(tps -> new Point(tps.getDate(), tps.getTps())).collect(Collectors.toList());
List<Point> points = tpsData.stream()
.filter(tps -> tps.getDate() >= now - scale)
.map(tps -> new Point(tps.getDate(), Double.parseDouble(FormatUtils.cutDecimals(tps.getTps()).replace(",", "."))))
.collect(Collectors.toList());
return ScatterGraphCreator.scatterGraph(points, true);
}
public static List<TPS> filterTPS(List<TPS> tpsData, long nowMinusScale) {
return tpsData.stream()
.filter(t -> t != null)
.filter(Objects::nonNull)
.filter(t -> t.getDate() >= nowMinusScale)
.collect(Collectors.toList());
}

View File

@ -1,13 +1,14 @@
package main.java.com.djrapitops.plan.ui.html.tables;
import java.util.Collections;
import java.util.List;
import java.util.Map;
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;
import java.util.List;
import java.util.Map;
/**
*
* @author Rsl1122
@ -20,7 +21,7 @@ public class CommandUseTableCreator {
* @return
*/
public static String createSortedCommandUseTable(Map<String, Integer> commandUse) {
Benchmark.start("Create commanduse table");
Benchmark.start("Create CommandUse table");
List<String[]> sorted = MapComparator.sortByValue(commandUse);
StringBuilder html = new StringBuilder();
if (sorted.isEmpty()) {
@ -38,9 +39,10 @@ public class CommandUseTableCreator {
Log.toLog("SortableCommandUseTableCreator", e);
Log.toLog("Cause: " + values[0] + " " + values[1], Log.getErrorsFilename());
}
i++;
}
}
Benchmark.stop("Create commanduse table");
Benchmark.stop("Create CommandUse table");
return html.toString();
}
}

View File

@ -2,12 +2,13 @@ package main.java.com.djrapitops.plan.ui.html.tables;
import com.djrapitops.plugin.utilities.player.Fetch;
import com.djrapitops.plugin.utilities.player.IOfflinePlayer;
import java.util.List;
import main.java.com.djrapitops.plan.data.KillData;
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;
import java.util.List;
/**
*
* @author Rsl1122
@ -19,28 +20,28 @@ public class KillsTableCreator {
* @param killData
* @return
*/
public static String createSortedSessionDataTable10(List<KillData> killData) {
String html = Html.TABLE_KILLS_START.parse();
public static String createKillsTable(List<KillData> killData) {
StringBuilder html = new StringBuilder(Html.TABLE_KILLS_START.parse());
if (killData.isEmpty()) {
html += Html.TABLELINE_3.parse(Html.KILLDATA_NONE.parse(), "", "");
html.append(Html.TABLELINE_3.parse(Html.KILLDATA_NONE.parse(), "", ""));
} else {
int i = 0;
for (KillData kill : killData) {
if (i >= 10) {
if (i >= 20) {
break;
}
long date = kill.getDate();
IOfflinePlayer victim = Fetch.getIOfflinePlayer(kill.getVictim());
String name = victim.getName();
html += Html.TABLELINE_3_CUSTOMKEY_1.parse(
html.append(Html.TABLELINE_3_CUSTOMKEY_1.parse(
date + "", FormatUtils.formatTimeStamp(date),
Html.LINK.parse(HtmlUtils.getInspectUrl(name), name),
kill.getWeapon()
);
));
i++;
}
}
html += Html.TABLE_END.parse();
return html;
html.append(Html.TABLE_END.parse());
return html.toString();
}
}

View File

@ -1,6 +1,5 @@
package main.java.com.djrapitops.plan.ui.html.tables;
import java.util.List;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.ui.html.Html;
@ -10,14 +9,14 @@ import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.AnalysisUtils;
import java.util.List;
/**
*
* @author Rsl1122
*/
public class PlayersTableCreator {
/**
*
* @param data
* @return
*/
@ -33,14 +32,20 @@ public class PlayersTableCreator {
break;
}
try {
String banOunknownOactiveOinactive = uData.isBanned() ? Html.GRAPH_BANNED.parse()
: uData.getLoginTimes() == 1 ? Html.GRAPH_UNKNOWN.parse()
: AnalysisUtils.isActive(now, uData.getLastPlayed(), uData.getPlayTime(), uData.getLoginTimes()) ? Html.GRAPH_ACTIVE.parse()
: Html.GRAPH_INACTIVE.parse();
boolean isBanned = uData.isBanned();
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 img = showImages ? Html.MINOTAR_SMALL_IMG.parse(uData.getName()) : "";
html.append(Html.TABLELINE_PLAYERS.parse(
img + Html.LINK.parse(HtmlUtils.getInspectUrl(uData.getName()), uData.getName()),
banOunknownOactiveOinactive,
activityString,
uData.getPlayTime() + "", FormatUtils.formatTimeAmount(uData.getPlayTime()),
uData.getLoginTimes() + "",
uData.getRegistered() + "", FormatUtils.formatTimeStampYear(uData.getRegistered()),

View File

@ -1,50 +0,0 @@
package main.java.com.djrapitops.plan.ui.html.tables;
import java.util.Collections;
import java.util.List;
import main.java.com.djrapitops.plan.data.SessionData;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
import main.java.com.djrapitops.plan.utilities.comparators.SessionDataComparator;
/**
*
* @author Rsl1122
*/
public class SessionTableCreator {
/**
*
* @param sessionData
* @return
*/
public static String createSortedSessionDataTable10(List<SessionData> sessionData) {
String html = Html.TABLE_SESSIONS_START.parse();
if (sessionData.isEmpty()) {
html += Html.TABLELINE_3.parse(Html.SESSIONDATA_NONE.parse(), "", "");
} else {
Collections.sort(sessionData, new SessionDataComparator());
Collections.reverse(sessionData);
int i = 0;
for (SessionData session : sessionData) {
if (i >= 10) {
break;
}
long start = session.getSessionStart();
long end = session.getSessionEnd();
long length = end - start;
if (length < 0) {
continue;
}
html += Html.TABLELINE_3_CUSTOMKEY.parse(
start + "", FormatUtils.formatTimeStamp(start),
end + "", FormatUtils.formatTimeStamp(end),
length + "", FormatUtils.formatTimeAmount(length)
);
i++;
}
}
html += Html.TABLE_END.parse();
return html;
}
}

View File

@ -1,16 +1,10 @@
package main.java.com.djrapitops.plan.ui.text;
import java.util.UUID;
import main.java.com.djrapitops.plan.Phrase;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.AnalysisData;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.analysis.ActivityPart;
import main.java.com.djrapitops.plan.data.analysis.JoinInfoPart;
import main.java.com.djrapitops.plan.data.analysis.KillPart;
import main.java.com.djrapitops.plan.data.analysis.PlayerCountPart;
import main.java.com.djrapitops.plan.data.analysis.PlaytimePart;
import main.java.com.djrapitops.plan.data.analysis.TPSPart;
import main.java.com.djrapitops.plan.data.analysis.*;
import main.java.com.djrapitops.plan.data.cache.AnalysisCacheHandler;
import main.java.com.djrapitops.plan.data.cache.InspectCacheHandler;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
@ -19,6 +13,8 @@ import main.java.com.djrapitops.plan.utilities.analysis.AnalysisUtils;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import org.bukkit.ChatColor;
import java.util.UUID;
/**
*
* @author Rsl1122
@ -68,7 +64,6 @@ public class TextUI {
AnalysisData d = analysisCache.getData();
ChatColor main = Phrase.COLOR_MAIN.color();
ChatColor sec = Phrase.COLOR_SEC.color();
ChatColor ter = Phrase.COLOR_TER.color();
String ball = sec + " " + Phrase.BALL + main;
final ActivityPart activity = d.getActivityPart();
final JoinInfoPart join = d.getJoinInfoPart();

View File

@ -1,22 +1,19 @@
package main.java.com.djrapitops.plan.ui.webserver;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import main.java.com.djrapitops.plan.Log;
import java.io.*;
import java.util.Arrays;
import java.util.Optional;
import main.java.com.djrapitops.plan.Log;
/**
* Represents a HTTP Request.
*
* <p>
* Request is read from the given InputStream.
*
* <p>
* Closing the Request closes the InputStream. (Closing Socket InputStream
* closes the socket.)
*
* <p>
* Request Strings should not be logged because they may contain base64 encoded
* user:password Authorization combinations.
*
@ -43,11 +40,11 @@ public class Request implements Closeable {
/**
* Reads the information in the Request and parses required information.
*
* <p>
* Parses Request (GET, POST etc.)
*
* <p>
* Parses Target (/home/etc)
*
* <p>
* Parses Authorization (Authorization header).
*
* @throws java.io.IOException if InputStream can not be read.
@ -56,8 +53,11 @@ public class Request implements Closeable {
StringBuilder headerB = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
close = in;
String line;
while (!(line = in.readLine()).isEmpty()) {
while (true) {
String line = in.readLine();
if (line == null || line.isEmpty()) {
break;
}
headerB.append(line);
headerB.append(":::");
}
@ -129,8 +129,8 @@ public class Request implements Closeable {
/**
* Closes the Request.
*
* Closes the inputstream.
* <p>
* Closes the InputStream.
*
* @throws IOException if the stream can not be closed.
*/

View File

@ -2,6 +2,20 @@ package main.java.com.djrapitops.plan.ui.webserver;
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.WebUser;
import main.java.com.djrapitops.plan.database.tables.SecurityTable;
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.MiscUtils;
import main.java.com.djrapitops.plan.utilities.PassEncryptUtil;
import main.java.com.djrapitops.plan.utilities.uuid.UUIDUtility;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@ -11,29 +25,6 @@ import java.net.Socket;
import java.sql.SQLException;
import java.util.Base64;
import java.util.UUID;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
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.database.tables.SecurityTable;
import main.java.com.djrapitops.plan.ui.html.DataRequestHandler;
import main.java.com.djrapitops.plan.ui.webserver.response.AnalysisPageResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.ForbiddenResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.InspectPageResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.InternalErrorResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.NotFoundResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.PlayersPageResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.PromptAuthorizationResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.RedirectResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.Response;
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 main.java.com.djrapitops.plan.utilities.PassEncryptUtil;
import main.java.com.djrapitops.plan.utilities.uuid.UUIDUtility;
/**
*
@ -66,14 +57,14 @@ public class WebSocketServer {
}
/**
* Starts up the Webserver in a Asyncronous thread.
* Starts up the Webserver in a Asynchronous thread.
*/
public void initServer() {
//Server is already enabled stop code
if (enabled) {
return;
}
Log.info(Phrase.WEBSERVER_INIT + "");
Log.info(Phrase.WEBSERVER_INIT.toString());
try {
InetAddress ip = InetAddress.getByName(Settings.WEBSERVER_IP.toString());
// SSLServerSocketFactory ssl = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
@ -101,8 +92,8 @@ public class WebSocketServer {
response.sendStaticResource();
} catch (IOException | IllegalArgumentException e) {
} finally {
Benchmark.stop("Webserver Response");
MiscUtils.close(input, request, output, socket);
Benchmark.stop("Webserver Response");
}
}
this.cancel();
@ -214,7 +205,7 @@ public class WebSocketServer {
* Shuts down the server - Async thread is closed with shutdown boolean.
*/
public void stop() {
Log.info(Phrase.WEBSERVER_CLOSE + "");
Log.info(Phrase.WEBSERVER_CLOSE.toString());
shutdown = true;
try {
if (server != null) {

View File

@ -1,14 +1,14 @@
package main.java.com.djrapitops.plan.ui.webserver.response;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.comparators.UserDataNameComparator;
import java.io.OutputStream;
import java.util.List;
/**
*
* @author Rsl1122
@ -22,13 +22,13 @@ public class PlayersPageResponse extends Response {
super.setContent(buildContent(plugin.getInspectCache().getCachedUserData()));
}
public static final String buildContent(List<UserData> cached) {
public static String buildContent(List<UserData> cached) {
StringBuilder html = new StringBuilder();
int size = cached.size();
html.append("<h1>Cached Players</h1><p>")
.append(size)
.append(" players. Use browser's Search to find players by name. (Chrome Ctrl+F)</p><table><tr>");
Collections.sort(cached, new UserDataNameComparator());
cached.sort(new UserDataNameComparator());
int i = 1;
for (UserData userData : cached) {
String name = userData.getName();

View File

@ -18,14 +18,14 @@ public abstract class Response {
/**
* Class Constructor.
*
* @param output Website outputstream to write the response to.
* @param output Website OutputStream to write the response to.
*/
public Response(OutputStream output) {
this.output = output;
}
/**
* Wrties the HTML to the Outputstream according to the requested page.
* Writes the HTML to the OutputStream according to the requested page.
*
* @throws IOException
*/
@ -37,6 +37,7 @@ public abstract class Response {
+ content;
// Log.debug("Response: " + response); // Responses should not be logged, html content large.
output.write(response.getBytes());
output.flush();
}
public void setHeader(String header) {

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