From a2cd3af68892bebfbe3685d81b1d60e9d7970ec9 Mon Sep 17 00:00:00 2001 From: Rsl1122 Date: Mon, 13 Feb 2017 20:21:25 +0200 Subject: [PATCH] [2.6.0-DEV] Replaced ServerData with Sessions, Added KillData - Playerkills untested - PlanLite analysis part disabled, will be replaced soon. Known bugs: - One empty nickname somehow manages to get into nicknames - SessionData cleared when DataCache clears data from cache - UnIntended. Will need a seperate save spot for current session data. --- .../commands/manage/ManageBackupCommand.java | 18 +- .../commands/manage/ManageCombineCommand.java | 8 +- .../commands/manage/ManageHotswapCommand.java | 2 +- .../commands/manage/ManageImportCommand.java | 1 + .../commands/manage/ManageMoveCommand.java | 22 +- .../commands/manage/ManageRemoveCommand.java | 1 + .../commands/manage/ManageRestoreCommand.java | 17 +- .../com/djrapitops/plan/data/KillData.java | 38 + .../djrapitops/plan/data/RawAnalysisData.java | 8 +- .../com/djrapitops/plan/data/ServerData.java | 121 --- .../com/djrapitops/plan/data/UserData.java | 32 +- .../plan/data/cache/DataCacheHandler.java | 46 +- .../plan/data/handlers/ActivityHandler.java | 4 +- .../plan/data/handlers/BasicInfoHandler.java | 10 +- .../plan/data/handlers/CommandUseHandler.java | 32 + .../plan/data/handlers/KillHandler.java | 10 +- .../plan/data/handlers/LocationHandler.java | 1 + .../plan/data/handlers/NewPlayerCreator.java | 1 - .../plan/data/handlers/ServerDataHandler.java | 52 -- .../PlanCommandPreprocessListener.java | 4 +- .../listeners/PlanDeathEventListener.java | 3 +- .../data/listeners/PlanPlayerListener.java | 5 +- .../djrapitops/plan/database/Database.java | 31 +- .../plan/database/databases/MySQLDB.java | 37 - .../plan/database/databases/SQLDB.java | 740 +++++++++--------- .../plan/database/databases/SQLiteDB.java | 5 - .../ui/graphs/PlayerActivityGraphCreator.java | 36 +- .../djrapitops/plan/utilities/Analysis.java | 78 +- .../plan/utilities/AnalysisUtils.java | 28 +- .../plan/utilities/DataCombineUtils.java | 43 - Plan/src/main/resources/config.yml | 8 - 31 files changed, 613 insertions(+), 829 deletions(-) create mode 100644 Plan/src/main/java/com/djrapitops/plan/data/KillData.java delete mode 100644 Plan/src/main/java/com/djrapitops/plan/data/ServerData.java create mode 100644 Plan/src/main/java/com/djrapitops/plan/data/handlers/CommandUseHandler.java delete mode 100644 Plan/src/main/java/com/djrapitops/plan/data/handlers/ServerDataHandler.java diff --git a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageBackupCommand.java b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageBackupCommand.java index 63c85ae83..f0b85a947 100644 --- a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageBackupCommand.java +++ b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageBackupCommand.java @@ -4,14 +4,14 @@ import com.djrapitops.plan.Phrase; import com.djrapitops.plan.Plan; import com.djrapitops.plan.command.CommandType; import com.djrapitops.plan.command.SubCommand; -import com.djrapitops.plan.data.ServerData; +import com.djrapitops.plan.data.UserData; import com.djrapitops.plan.database.Database; import com.djrapitops.plan.database.databases.SQLiteDB; +import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; +import java.util.List; import java.util.Set; import java.util.UUID; -import main.java.com.djrapitops.plan.utilities.DataCombineUtils; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -72,7 +72,7 @@ public class ManageBackupCommand extends SubCommand { plugin.logError(db + " was null!"); return true; } - final Database copyfromDB = database; + final Database copyFromDB = database; (new BukkitRunnable() { @Override public void run() { @@ -87,13 +87,13 @@ public class ManageBackupCommand extends SubCommand { } sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse()); backupDB.removeAllData(); - Set uuids = copyfromDB.getSavedUUIDs(); + Set uuids = copyFromDB.getSavedUUIDs(); + List allUserData = new ArrayList<>(); for (UUID uuid : uuids) { - backupDB.saveUserData(uuid, copyfromDB.getUserData(uuid)); + allUserData.add(copyFromDB.getUserData(uuid)); } - HashMap serverDataHashMap = copyfromDB.getServerDataHashMap(); - backupDB.saveServerDataHashMap(serverDataHashMap); - backupDB.saveCommandUse(DataCombineUtils.getCommandUse(serverDataHashMap)); + backupDB.saveMultipleUserData(allUserData); + backupDB.saveCommandUse(copyFromDB.getCommandUse()); sender.sendMessage(Phrase.MANAGE_COPY_SUCCESS.toString()); this.cancel(); } diff --git a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageCombineCommand.java b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageCombineCommand.java index 396170dca..0ef249f7f 100644 --- a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageCombineCommand.java +++ b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageCombineCommand.java @@ -4,7 +4,6 @@ import com.djrapitops.plan.Phrase; import com.djrapitops.plan.Plan; import com.djrapitops.plan.command.CommandType; import com.djrapitops.plan.command.SubCommand; -import com.djrapitops.plan.data.ServerData; import com.djrapitops.plan.data.UserData; import com.djrapitops.plan.database.Database; @@ -127,15 +126,10 @@ public class ManageCombineCommand extends SubCommand { List combinedUserData = DataCombineUtils.combineUserDatas(allFromUserData, allToUserData, uuids); - HashMap fromServerData = moveFromDB.getServerDataHashMap(); - HashMap toServerData = moveToDB.getServerDataHashMap(); - HashMap combinedServerData = DataCombineUtils.combineServerDatas(fromServerData, toServerData); - - HashMap commandUse = DataCombineUtils.combineCommandUses(DataCombineUtils.getCommandUse(fromServerData), DataCombineUtils.getCommandUse(toServerData)); + HashMap commandUse = DataCombineUtils.combineCommandUses(moveFromDB.getCommandUse(), moveToDB.getCommandUse()); moveToDB.removeAllData(); - moveToDB.saveServerDataHashMap(combinedServerData); moveToDB.saveMultipleUserData(combinedUserData); moveToDB.saveCommandUse(commandUse); diff --git a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageHotswapCommand.java b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageHotswapCommand.java index 9ff8fbddb..a2cfb3abe 100644 --- a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageHotswapCommand.java +++ b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageHotswapCommand.java @@ -57,7 +57,7 @@ public class ManageHotswapCommand extends SubCommand { if (dbToSwapTo.equalsIgnoreCase(database.getConfigName())) { db = database; db.init(); - db.getNewestServerData(); + db.getVersion(); //Test db connection } } } catch (NullPointerException e) { diff --git a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageImportCommand.java b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageImportCommand.java index 6de768ffc..965dc8d96 100644 --- a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageImportCommand.java +++ b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageImportCommand.java @@ -21,6 +21,7 @@ import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import static org.bukkit.Bukkit.getOfflinePlayer; +import static org.bukkit.Bukkit.getOfflinePlayer; /** * diff --git a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageMoveCommand.java b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageMoveCommand.java index 2fe55dde3..2623aa262 100644 --- a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageMoveCommand.java +++ b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageMoveCommand.java @@ -4,13 +4,11 @@ import com.djrapitops.plan.Phrase; import com.djrapitops.plan.Plan; import com.djrapitops.plan.command.CommandType; import com.djrapitops.plan.command.SubCommand; -import com.djrapitops.plan.data.ServerData; import com.djrapitops.plan.data.UserData; import com.djrapitops.plan.database.Database; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.UUID; @@ -33,7 +31,7 @@ public class ManageMoveCommand extends SubCommand { * @param plugin Current instance of Plan */ public ManageMoveCommand(Plan plugin) { - super("move", "plan.manage", Phrase.CMD_USG_MANAGE_MOVE+"", CommandType.CONSOLE_WITH_ARGUMENTS, Phrase.ARG_MOVE+""); + super("move", "plan.manage", Phrase.CMD_USG_MANAGE_MOVE + "", CommandType.CONSOLE_WITH_ARGUMENTS, Phrase.ARG_MOVE + ""); this.plugin = plugin; } @@ -54,7 +52,7 @@ public class ManageMoveCommand extends SubCommand { @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (args.length < 2) { - sender.sendMessage(Phrase.COMMAND_REQUIRES_ARGUMENTS.parse(Phrase.USE_MOVE+"")); + sender.sendMessage(Phrase.COMMAND_REQUIRES_ARGUMENTS.parse(Phrase.USE_MOVE + "")); return true; } String fromDB = args[0].toLowerCase(); @@ -98,7 +96,7 @@ public class ManageMoveCommand extends SubCommand { plugin.logError(toDB + " was null!"); return true; } - final Set uuids = fromDatabase.getSavedUUIDs(); + final Set uuids = fromDatabase.getSavedUUIDs(); if (uuids.isEmpty()) { sender.sendMessage(Phrase.MANAGE_ERROR_NO_PLAYERS + " (" + fromDB + ")"); return true; @@ -117,16 +115,7 @@ public class ManageMoveCommand extends SubCommand { allUserData.add(moveFromDB.getUserData(uuid)); } moveToDB.saveMultipleUserData(allUserData); - HashMap serverData = moveFromDB.getServerDataHashMap(); - moveToDB.saveServerDataHashMap(serverData); - ServerData sData = null; - for (long sDataKey : serverData.keySet()) { - sData = serverData.get(sDataKey); - break; - } - if (sData != null) { - moveToDB.saveCommandUse(sData.getCommandUsage()); - } + moveToDB.saveCommandUse(moveFromDB.getCommandUse()); sender.sendMessage(Phrase.MANAGE_MOVE_SUCCESS + ""); if (!toDB.equals(plugin.getDB().getConfigName())) { sender.sendMessage(Phrase.MANAGE_DB_CONFIG_REMINDER + ""); @@ -134,9 +123,12 @@ public class ManageMoveCommand extends SubCommand { } catch (NullPointerException e) { sender.sendMessage(Phrase.MANAGE_DATABASE_FAILURE + ""); } + this.cancel(); } + }).runTaskAsynchronously(plugin); + return true; } } diff --git a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageRemoveCommand.java b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageRemoveCommand.java index 90c1c3abe..081bb0ec9 100644 --- a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageRemoveCommand.java +++ b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageRemoveCommand.java @@ -85,6 +85,7 @@ public class ManageRemoveCommand extends SubCommand { @Override public void run() { sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse()); + plugin.getHandler().clearFromCache(uuid); plugin.getDB().removeAccount(uuid.toString()); sender.sendMessage(Phrase.MANAGE_REMOVE_SUCCESS.parse(playerName, plugin.getDB().getConfigName())); this.cancel(); diff --git a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageRestoreCommand.java b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageRestoreCommand.java index fec099450..4e057a11c 100644 --- a/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageRestoreCommand.java +++ b/Plan/src/main/java/com/djrapitops/plan/command/commands/manage/ManageRestoreCommand.java @@ -4,19 +4,20 @@ import com.djrapitops.plan.Phrase; import com.djrapitops.plan.Plan; import com.djrapitops.plan.command.CommandType; import com.djrapitops.plan.command.SubCommand; -import com.djrapitops.plan.data.ServerData; +import com.djrapitops.plan.data.UserData; import com.djrapitops.plan.database.Database; import com.djrapitops.plan.database.databases.SQLiteDB; import java.io.File; +import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; +import java.util.List; import java.util.Set; import java.util.UUID; -import main.java.com.djrapitops.plan.utilities.DataCombineUtils; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; /** * @@ -78,7 +79,7 @@ public class ManageRestoreCommand extends SubCommand { return true; } final Database copyToDB = database; - (new BukkitRunnable() { + BukkitTask asyncRestoreTask = (new BukkitRunnable() { @Override public void run() { String backupDBName = args[0]; @@ -101,12 +102,12 @@ public class ManageRestoreCommand extends SubCommand { sender.sendMessage(Phrase.MANAGE_PROCESS_START.parse()); copyToDB.removeAllData(); Set uuids = backupDB.getSavedUUIDs(); + List allUserData = new ArrayList<>(); for (UUID uuid : uuids) { - copyToDB.saveUserData(uuid, backupDB.getUserData(uuid)); + allUserData.add(backupDB.getUserData(uuid)); } - HashMap serverDataHashMap = backupDB.getServerDataHashMap(); - copyToDB.saveServerDataHashMap(serverDataHashMap); - copyToDB.saveCommandUse(DataCombineUtils.getCommandUse(serverDataHashMap)); + copyToDB.saveMultipleUserData(allUserData); + copyToDB.saveCommandUse(backupDB.getCommandUse()); sender.sendMessage(Phrase.MANAGE_COPY_SUCCESS.toString()); this.cancel(); } diff --git a/Plan/src/main/java/com/djrapitops/plan/data/KillData.java b/Plan/src/main/java/com/djrapitops/plan/data/KillData.java new file mode 100644 index 000000000..7ad3f10b2 --- /dev/null +++ b/Plan/src/main/java/com/djrapitops/plan/data/KillData.java @@ -0,0 +1,38 @@ +package main.java.com.djrapitops.plan.data; + +import java.util.UUID; + +/** + * + * @author Rsl1122 + */ +public class KillData { + + private UUID victim; + private int victimUserID; + private long date; + private String weapon; + + public KillData(UUID victim, int victimID, String weapon, long date) { + this.victim = victim; + this.weapon = weapon; + victimUserID = victimID; + this.date = date; + } + + public UUID getVictim() { + return victim; + } + + public long getDate() { + return date; + } + + public String getWeapon() { + return weapon; + } + + public int getVictimUserID() { + return victimUserID; + } +} diff --git a/Plan/src/main/java/com/djrapitops/plan/data/RawAnalysisData.java b/Plan/src/main/java/com/djrapitops/plan/data/RawAnalysisData.java index 453b25898..9751138c6 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/RawAnalysisData.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/RawAnalysisData.java @@ -29,6 +29,7 @@ public class RawAnalysisData { private HashMap playtimes; private List sessiondata; private HashMap commandUse; + private List registered; public RawAnalysisData() { gmZero = 0; @@ -47,8 +48,9 @@ public class RawAnalysisData { ages = new ArrayList<>(); latestLogins = new HashMap<>(); playtimes = new HashMap<>(); - sessiondata = new ArrayList<>(); + sessiondata = new ArrayList<>(); commandUse = new HashMap<>(); + registered = new ArrayList<>(); } public void addToGmZero(long gmZero) { @@ -186,4 +188,8 @@ public class RawAnalysisData { public HashMap getCommandUse() { return commandUse; } + + public List getRegistered() { + return registered; + } } diff --git a/Plan/src/main/java/com/djrapitops/plan/data/ServerData.java b/Plan/src/main/java/com/djrapitops/plan/data/ServerData.java deleted file mode 100644 index 34f2e8e0f..000000000 --- a/Plan/src/main/java/com/djrapitops/plan/data/ServerData.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.djrapitops.plan.data; - -import com.djrapitops.plan.Plan; -import java.util.HashMap; -import org.bukkit.Bukkit; -import static org.bukkit.plugin.java.JavaPlugin.getPlugin; -import org.bukkit.scheduler.BukkitRunnable; - -/** - * - * @author Rsl1122 - */ -public class ServerData { - - private final HashMap commandUsage; - private int playersOnline; - private int newPlayers; - - /** - * Class Constructor. - * - * Creates a new DataPoint of ServerData with the currently known player - * count. - * - * @param commandUsage HashMap of Commands used and times they have been - * used. - * @param newPlayers Amount of new players that have joined that day. - */ - public ServerData(HashMap commandUsage, int newPlayers) { - this.commandUsage = commandUsage; - this.playersOnline = Bukkit.getServer().getOnlinePlayers().size(); - this.newPlayers = newPlayers; - } - - /** - * Class Constructor with playersOnline. - * - * Creates a new DataPoint of ServerData with defined player count. - * - * @param commandUsage HashMap of Commands used and times they have been - * used. - * @param newPlayers Amount of new players that have joined that day. - * @param playersOnline Amount of players at the time of save. - */ - public ServerData(HashMap commandUsage, int newPlayers, int playersOnline) { - this.commandUsage = commandUsage; - this.playersOnline = playersOnline; - this.newPlayers = newPlayers; - } - - /** - * Updates PlayerCount if the player is new. - * - * @param newPlayer If data for player is not found in the database this is - * true. - */ - public void playerJoined(boolean newPlayer) { - updatePlayerCount(); - if (newPlayer) { - newPlayers++; - } - } - - /** - * Updates playersOnline to current playercount. - */ - public void updatePlayerCount() { - playersOnline = Bukkit.getServer().getOnlinePlayers().size(); - } - - /** - * Updates playersOnline after 5 seconds to wait for Player to leave. - */ - public void playerLeft() { - (new BukkitRunnable() { - @Override - public void run() { - updatePlayerCount(); - this.cancel(); - } - }).runTaskLater(getPlugin(Plan.class), 5 * 20); - } - - /** - * Adds command to the commandUse Map and adds 1 to the amount it has been - * used. - * - * @param command Used command (eg. /plan) - */ - public void commandRegistered(String command) { - if (!commandUsage.containsKey(command)) { - commandUsage.put(command, 0); - } - commandUsage.put(command, commandUsage.get(command) + 1); - } - - /** - * @return HashMap of used Commands and how many times they've been used. - */ - public HashMap getCommandUsage() { - return commandUsage; - } - - /** - * @return How many players were online at the time of save. - */ - public int getPlayersOnline() { - return playersOnline; - } - - /** - * @return How many players were new at the time of save. - */ - public int getNewPlayers() { - return newPlayers; - } - - public void setNewPlayers(int newPlayers) { - this.newPlayers = newPlayers; - } -} diff --git a/Plan/src/main/java/com/djrapitops/plan/data/UserData.java b/Plan/src/main/java/com/djrapitops/plan/data/UserData.java index 6f05e666f..ad92c7893 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/UserData.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/UserData.java @@ -8,6 +8,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.UUID; +import main.java.com.djrapitops.plan.data.KillData; import main.java.com.djrapitops.plan.data.PlanLitePlayerData; import main.java.com.djrapitops.plan.data.SessionData; import org.bukkit.GameMode; @@ -24,6 +25,7 @@ public class UserData { private List locations; private HashSet ips; private HashSet nicknames; + private String lastNick; private long registered; private long lastPlayed; private long playTime; @@ -37,7 +39,7 @@ public class UserData { private DemographicsData demData; private int mobKills; - private int playerKills; + private List playerKills; private int deaths; private boolean planLiteFound; @@ -72,6 +74,8 @@ public class UserData { name = player.getName(); isOnline = player.isOnline(); sessions = new ArrayList<>(); + lastNick = ""; + playerKills = new ArrayList<>(); } public UserData(OfflinePlayer player, DemographicsData demData, Database db) { @@ -95,6 +99,8 @@ public class UserData { name = player.getName(); isOnline = player.isOnline(); sessions = new ArrayList<>(); + lastNick = ""; + playerKills = new ArrayList<>(); } public void addIpAddress(InetAddress ip) { @@ -119,10 +125,14 @@ public class UserData { } } - public void addNickname(String nick) { + public boolean addNickname(String nick) { if (!nicknames.contains(nick)) { - nicknames.add(nick); + if (!nick.isEmpty()) { + nicknames.add(nick); + return true; + } } + return false; } public void addNicknames(Collection addNicks) { @@ -339,13 +349,17 @@ public class UserData { this.mobKills = mobKills; } - public int getPlayerKills() { + public List getPlayerKills() { return playerKills; } - public void setPlayerKills(int playerKills) { + public void setPlayerKills(List playerKills) { this.playerKills = playerKills; } + + public void addPlayerKill(KillData kill) { + playerKills.add(kill); + } public int getDeaths() { return deaths; @@ -358,4 +372,12 @@ public class UserData { public List getSessions() { return sessions; } + + public String getLastNick() { + return lastNick; + } + + public void setLastNick(String lastNick) { + this.lastNick = lastNick; + } } diff --git a/Plan/src/main/java/com/djrapitops/plan/data/cache/DataCacheHandler.java b/Plan/src/main/java/com/djrapitops/plan/data/cache/DataCacheHandler.java index 28af8990a..fe43713ab 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/cache/DataCacheHandler.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/cache/DataCacheHandler.java @@ -5,7 +5,6 @@ import com.djrapitops.plan.Plan; import com.djrapitops.plan.database.Database; import com.djrapitops.plan.data.*; import com.djrapitops.plan.data.handlers.*; -import com.djrapitops.plan.utilities.MiscUtils; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; @@ -34,8 +33,8 @@ public class DataCacheHandler { private final DemographicsHandler demographicsHandler; private final BasicInfoHandler basicInfoHandler; private final RuleBreakingHandler ruleBreakingHandler; - private final ServerData serverData; - private final ServerDataHandler serverDataHandler; + private final HashMap commandUse; + private final CommandUseHandler commandUseHandler; private final PlanLiteHandler planLiteHandler; private final KillHandler killHandler; private final Database db; @@ -43,7 +42,6 @@ public class DataCacheHandler { private int timesSaved; private int maxPlayers; - private Date lastServerDataSave; /** * Class Constructor. @@ -63,15 +61,14 @@ public class DataCacheHandler { demographicsHandler = new DemographicsHandler(plugin, this); basicInfoHandler = new BasicInfoHandler(plugin, this); ruleBreakingHandler = new RuleBreakingHandler(plugin, this); - serverData = db.getNewestServerData(); - serverDataHandler = new ServerDataHandler(serverData); + commandUse = db.getCommandUse(); + commandUseHandler = new CommandUseHandler(commandUse); planLiteHandler = new PlanLiteHandler(plugin); newPlayerCreator = new NewPlayerCreator(plugin, this); killHandler = new KillHandler(plugin); timesSaved = 0; maxPlayers = plugin.getServer().getMaxPlayers(); - lastServerDataSave = new Date(); int minutes = Settings.SAVE_CACHE_MIN.getNumber(); if (minutes <= 0) { @@ -97,13 +94,7 @@ public class DataCacheHandler { if (timesSaved % clearAfterXsaves == 0) { handler.clearCache(); } - Date serverDataSave = new Date(); - if (MiscUtils.isOnSameDay(serverDataSave, lastServerDataSave)) { - serverData.setNewPlayers(0); - } - serverData.updatePlayerCount(); - saveServerData(); - lastServerDataSave = serverDataSave; + saveCommandUse(); handler.clearNulls(); timesSaved++; } @@ -185,8 +176,12 @@ public class DataCacheHandler { // }); List data = new ArrayList<>(); data.addAll(dataCache.values()); + long now = new Date().toInstant().getEpochSecond() * (long) 1000; + for (UserData userData : data) { + userData.endSession(now); + } db.saveMultipleUserData(data); - db.saveServerData(serverData); + db.saveCommandUse(commandUse); db.close(); } @@ -213,11 +208,11 @@ public class DataCacheHandler { * * Data is saved on a new line with a long value matching current Date */ - public void saveServerData() { + public void saveCommandUse() { (new BukkitRunnable() { @Override public void run() { - db.saveServerData(serverData); + db.saveCommandUse(commandUse); } }).runTaskAsynchronously(plugin); } @@ -395,21 +390,15 @@ public class DataCacheHandler { return db; } - /** - * Updates the player count and returns cached ServerData. - * - * @return Cached serverData - */ - public ServerData getServerData() { - serverData.updatePlayerCount(); - return serverData; + public HashMap getCommandUse() { + return commandUse; } - + /** * @return Current instance of ServerDataHandler */ - public ServerDataHandler getServerDataHandler() { - return serverDataHandler; + public CommandUseHandler getServerDataHandler() { + return commandUseHandler; } /** @@ -424,7 +413,6 @@ public class DataCacheHandler { if (isNewPlayer) { newPlayer(player); } - serverDataHandler.handleLogin(isNewPlayer); UserData data = getCurrentData(uuid); activityHandler.handleReload(player, data); basicInfoHandler.handleReload(player, data); diff --git a/Plan/src/main/java/com/djrapitops/plan/data/handlers/ActivityHandler.java b/Plan/src/main/java/com/djrapitops/plan/data/handlers/ActivityHandler.java index fc32706da..eb4df327d 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/handlers/ActivityHandler.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/handlers/ActivityHandler.java @@ -97,8 +97,10 @@ public class ActivityHandler { * @param data UserData matching the Player */ public void handleReload(Player player, UserData data) { - long timeNow = new Date().getTime(); + Date now = new Date(); + long timeNow = now.getTime(); data.setPlayTime(data.getPlayTime() + (timeNow - data.getLastPlayed())); data.setLastPlayed(timeNow); + data.startSession(now.toInstant().getEpochSecond() * (long) 1000); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/data/handlers/BasicInfoHandler.java b/Plan/src/main/java/com/djrapitops/plan/data/handlers/BasicInfoHandler.java index 73bef64d2..827d974e7 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/handlers/BasicInfoHandler.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/handlers/BasicInfoHandler.java @@ -32,7 +32,10 @@ public class BasicInfoHandler { */ public void handleLogin(PlayerJoinEvent event, UserData data) { Player player = event.getPlayer(); - data.addNickname(player.getDisplayName()); + String nick = player.getDisplayName(); + if (data.addNickname(nick)) { + data.setLastNick(nick); + } data.addIpAddress(player.getAddress().getAddress()); } @@ -43,7 +46,10 @@ public class BasicInfoHandler { * @param data UserData matching the Player */ public void handleReload(Player player, UserData data) { - data.addNickname(player.getDisplayName()); + String nick = player.getDisplayName(); + if (data.addNickname(nick)) { + data.setLastNick(nick); + } data.addIpAddress(player.getAddress().getAddress()); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/data/handlers/CommandUseHandler.java b/Plan/src/main/java/com/djrapitops/plan/data/handlers/CommandUseHandler.java new file mode 100644 index 000000000..b9d31a45e --- /dev/null +++ b/Plan/src/main/java/com/djrapitops/plan/data/handlers/CommandUseHandler.java @@ -0,0 +1,32 @@ +package com.djrapitops.plan.data.handlers; + +import java.util.HashMap; + +/** + * + * @author Rsl1122 + */ +public class CommandUseHandler { + + private HashMap commandUse; + + /** + * Class constructor. + * + * @param serverData ServerData in the DataCacheHandler. + */ + public CommandUseHandler(HashMap serverData) { + this.commandUse = serverData; + } + + /** + * Adds command to the command usage. + * @param command Used command, first part (eg. /plan) + */ + public void handleCommand(String command) { + if (!commandUse.containsKey(command)) { + commandUse.put(command, 0); + } + commandUse.put(command, commandUse.get(command) + 1); + } +} diff --git a/Plan/src/main/java/com/djrapitops/plan/data/handlers/KillHandler.java b/Plan/src/main/java/com/djrapitops/plan/data/handlers/KillHandler.java index fd5e73d01..bd989aa51 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/handlers/KillHandler.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/handlers/KillHandler.java @@ -3,6 +3,9 @@ package com.djrapitops.plan.data.handlers; import com.djrapitops.plan.Plan; import com.djrapitops.plan.data.UserData; +import java.util.Date; +import java.util.UUID; +import main.java.com.djrapitops.plan.data.KillData; /** * @@ -15,8 +18,11 @@ public class KillHandler { this.plugin = plugin; } - public void handlePlayerKill(UserData data) { - data.setPlayerKills(data.getPlayerKills()+1); + public void handlePlayerKill(UserData killerData, UserData victim, String weapon) { + UUID victimUUID = victim.getUuid(); + long now = new Date().toInstant().getEpochSecond()*(long)1000; + int victimID = plugin.getDB().getUserId(victimUUID+""); + killerData.addPlayerKill(new KillData(victimUUID, victimID, weapon, now)); } public void handlePlayerDeath(UserData data) { diff --git a/Plan/src/main/java/com/djrapitops/plan/data/handlers/LocationHandler.java b/Plan/src/main/java/com/djrapitops/plan/data/handlers/LocationHandler.java index a8f597f9d..b47e98c27 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/handlers/LocationHandler.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/handlers/LocationHandler.java @@ -9,6 +9,7 @@ import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.event.player.PlayerQuitEvent; import static org.bukkit.Bukkit.getOfflinePlayer; +import static org.bukkit.Bukkit.getOfflinePlayer; /** * diff --git a/Plan/src/main/java/com/djrapitops/plan/data/handlers/NewPlayerCreator.java b/Plan/src/main/java/com/djrapitops/plan/data/handlers/NewPlayerCreator.java index 2fdc5a823..76882e6b8 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/handlers/NewPlayerCreator.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/handlers/NewPlayerCreator.java @@ -59,7 +59,6 @@ public class NewPlayerCreator { data.setLastGmSwapTime(zero); data.setDeaths(0); data.setMobKills(0); - data.setPlayerKills(0); db.saveUserData(player.getUniqueId(), data); } diff --git a/Plan/src/main/java/com/djrapitops/plan/data/handlers/ServerDataHandler.java b/Plan/src/main/java/com/djrapitops/plan/data/handlers/ServerDataHandler.java deleted file mode 100644 index a9a806141..000000000 --- a/Plan/src/main/java/com/djrapitops/plan/data/handlers/ServerDataHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.djrapitops.plan.data.handlers; - -import com.djrapitops.plan.data.ServerData; - -/** - * - * @author Rsl1122 - */ -public class ServerDataHandler { - - private ServerData serverData; - - /** - * Class constructor. - * - * @param serverData ServerData in the DataCacheHandler. - */ - public ServerDataHandler(ServerData serverData) { - this.serverData = serverData; - } - - /** - * Updates playercount and adds new player if player is new. - * - * @param newPlayer true if player not in database. - */ - public void handleLogin(boolean newPlayer) { - serverData.playerJoined(newPlayer); - } - - /** - * Updates playercount. - */ - public void handleLogout() { - serverData.playerLeft(); - } - - /** - * Updates playercount. - */ - public void handleKick() { - handleLogout(); - } - - /** - * Adds command to the command usage. - * @param command Used command, first part (eg. /plan) - */ - public void handleCommand(String command) { - serverData.commandRegistered(command); - } -} diff --git a/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanCommandPreprocessListener.java b/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanCommandPreprocessListener.java index d44a806a3..ada54339d 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanCommandPreprocessListener.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanCommandPreprocessListener.java @@ -2,7 +2,7 @@ package com.djrapitops.plan.data.listeners; import com.djrapitops.plan.Plan; import com.djrapitops.plan.data.cache.DataCacheHandler; -import com.djrapitops.plan.data.handlers.ServerDataHandler; +import com.djrapitops.plan.data.handlers.CommandUseHandler; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -16,7 +16,7 @@ public class PlanCommandPreprocessListener implements Listener { private final Plan plugin; private final DataCacheHandler handler; - private final ServerDataHandler serverH; + private final CommandUseHandler serverH; /** * Class Constructor. diff --git a/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanDeathEventListener.java b/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanDeathEventListener.java index 368fe5d59..372ca53cc 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanDeathEventListener.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanDeathEventListener.java @@ -45,7 +45,8 @@ public class PlanDeathEventListener implements Listener { Player killed = (Player) dead; UserData killedsData = handler.getCurrentData(killed.getUniqueId()); if (killerIsPlayer) { - kH.handlePlayerKill(killersData); + String weaponName = killer.getInventory().getItemInMainHand().getType().name(); + kH.handlePlayerKill(killersData, killedsData, weaponName); } kH.handlePlayerDeath(killedsData); } else if (killerIsPlayer) { diff --git a/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanPlayerListener.java b/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanPlayerListener.java index ea4bbaeac..4fa2202ee 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanPlayerListener.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanPlayerListener.java @@ -29,7 +29,7 @@ public class PlanPlayerListener implements Listener { private final DemographicsHandler demographicH; private final RuleBreakingHandler rulebreakH; private final PlanLiteHandler planLiteH; - private final ServerDataHandler serverHandler; + private final CommandUseHandler serverHandler; /** * Class Constructor. @@ -68,7 +68,6 @@ public class PlanPlayerListener implements Listener { if (isNewPlayer) { handler.newPlayer(player); } - serverHandler.handleLogin(isNewPlayer); UserData data = handler.getCurrentData(uuid); activityH.handleLogin(event, data); basicInfoH.handleLogin(event, data); @@ -98,7 +97,6 @@ public class PlanPlayerListener implements Listener { activityH.handleLogOut(event, data); locationH.handleLogOut(event, data); gmTimesH.handleLogOut(event, data); - serverHandler.handleLogout(); handler.saveCachedData(uuid); } @@ -117,7 +115,6 @@ public class PlanPlayerListener implements Listener { UUID uuid = event.getPlayer().getUniqueId(); UserData data = handler.getCurrentData(uuid); rulebreakH.handleKick(event, data); - serverHandler.handleKick(); handler.saveCachedData(uuid); handler.clearFromCache(uuid); } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/Database.java b/Plan/src/main/java/com/djrapitops/plan/database/Database.java index 06d6ffad6..160d37277 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/Database.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/Database.java @@ -1,7 +1,6 @@ package com.djrapitops.plan.database; import com.djrapitops.plan.data.UserData; -import com.djrapitops.plan.data.ServerData; import com.djrapitops.plan.Plan; import org.bukkit.configuration.ConfigurationSection; @@ -63,13 +62,6 @@ public abstract class Database { */ public abstract boolean wasSeenBefore(UUID uuid); - /** - * Gets the settings to the config for each database type. - * - * @param section - */ - public abstract void getConfigDefaults(ConfigurationSection section); - /** * Cleans the database. */ @@ -114,36 +106,15 @@ public abstract class Database { */ public abstract void setVersion(int version); - /** - * Saves new server data to the table - * - * @param serverData Current serverdata - */ - public abstract void saveServerData(ServerData serverData); - - /** - * Gets the newest serverdata from the database. - * - * @return ServerData with the highest save date. - */ - public abstract ServerData getNewestServerData(); - /** * Closes the database. */ public abstract void close(); - - /** - * Returns raw data for analysis, contains all of player activity history. - * - * @return HashMap with save date (long in ms) and ServerData. - */ - public abstract HashMap getServerDataHashMap(); public abstract void removeAccount(String uuid); public abstract void removeAllData(); - public abstract void saveServerDataHashMap(HashMap serverData); public abstract void saveCommandUse(HashMap data); public abstract Set getSavedUUIDs(); public abstract HashMap getCommandUse(); + public abstract int getUserId(String uuid); } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/databases/MySQLDB.java b/Plan/src/main/java/com/djrapitops/plan/database/databases/MySQLDB.java index f6348e3f8..607369d52 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/databases/MySQLDB.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/databases/MySQLDB.java @@ -33,14 +33,6 @@ public class MySQLDB extends SQLDB { protected Connection getNewConnection() { FileConfiguration config = getPlugin(Plan.class).getConfig(); - - setUserName(config.getString("mysql.tables.users")); - setLocationName(config.getString("mysql.tables.locations")); - setNicknamesName(config.getString("mysql.tables.nicknames")); - setGamemodetimesName(config.getString("mysql.tables.gamemodetimes")); - setIpsName(config.getString("mysql.tables.ips")); - setCommanduseName(config.getString("mysql.tables.commandusages")); - setServerdataName(config.getString("mysql.tables.serverdata")); try { Class.forName("com.mysql.jdbc.Driver"); @@ -53,35 +45,6 @@ public class MySQLDB extends SQLDB { } } -// private ConfigurationSection getSection(ConfigurationSection parent, String childName) { -// ConfigurationSection child = parent.getConfigurationSection(childName); -// -// if (child == null) { -// child = parent.createSection(childName); -// } -// -// return child; -// } - - @Override - public void getConfigDefaults(ConfigurationSection section) { -// section.addDefault("host", "localhost"); -// section.addDefault("port", 3306); -// section.addDefault("user", "root"); -// section.addDefault("password", "minecraft"); -// section.addDefault("database", "Plan"); -// -// ConfigurationSection tables = getSection(section, "tables"); -// -// tables.addDefault("users", "plan_users"); -// tables.addDefault("locations", "plan_locations"); -// tables.addDefault("nicknames", "plan_nicknames"); -// tables.addDefault("gamemodetimes", "plan_gamemodetimes"); -// tables.addDefault("ips", "plan_ips"); -// tables.addDefault("commandusages", "plan_commandusages"); -// tables.addDefault("serverdata", "plan_serverdata"); - } - @Override public String getName() { return "MySQL"; diff --git a/Plan/src/main/java/com/djrapitops/plan/database/databases/SQLDB.java b/Plan/src/main/java/com/djrapitops/plan/database/databases/SQLDB.java index d6eb61709..e6d9dffdb 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/databases/SQLDB.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/databases/SQLDB.java @@ -4,7 +4,6 @@ import com.djrapitops.plan.Plan; import com.djrapitops.plan.api.Gender; import com.djrapitops.plan.database.Database; import com.djrapitops.plan.data.*; -import com.djrapitops.plan.utilities.MiscUtils; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.Connection; @@ -12,14 +11,13 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; -import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; -import java.util.logging.Level; -import java.util.logging.Logger; +import main.java.com.djrapitops.plan.data.KillData; +import main.java.com.djrapitops.plan.data.SessionData; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; @@ -35,46 +33,59 @@ public abstract class SQLDB extends Database { private Connection connection; - private String userName; - private String locationName; - private String serverdataName; - private String commanduseName; - private String gamemodetimesName; - private String nicknamesName; - private String ipsName; + private final String userName; + private final String locationName; + private final String serverdataName; + private final String commanduseName; + private final String gamemodetimesName; + private final String nicknamesName; + private final String ipsName; + private final String sessionName; + private final String killsName; - private String userColumnUUID; + private final String userColumnUUID; private final String userColumnID; - private String userColumnPlayTime; - private String userColumnDemGeoLocation; - private String userColumnDemAge; - private String userColumnDemGender; - private String userColumnLastGM; - private String userColumnLastGMSwapTime; - private String userColumnLoginTimes; - private String userColumnLastPlayed; - private String userColumnMobKills; - private String userColumnPlayerKills; - private String userColumnDeaths; + private final String userColumnPlayTime; + private final String userColumnDemGeoLocation; + private final String userColumnDemAge; + private final String userColumnDemGender; + private final String userColumnLastGM; + private final String userColumnLastGMSwapTime; + private final String userColumnLoginTimes; + private final String userColumnLastPlayed; + private final String userColumnMobKills; + private final String userColumnPlayerKills; + private final String userColumnDeaths; + private final String locationColumnUserID; - private String locationColumnID; - private String locationColumnCoordinatesX; - private String locationColumnCoordinatesZ; - private String locationColumnWorld; - private String serverdataColumnDate; - private String serverdataColumnPlayersOnline; - private String serverdataColumnNewPlayers; - private String commanduseColumnCommand; - private String commanduseColumnTimesUsed; + private final String locationColumnID; + private final String locationColumnCoordinatesX; + private final String locationColumnCoordinatesZ; + private final String locationColumnWorld; + + private final String commanduseColumnCommand; + private final String commanduseColumnTimesUsed; + private final String gamemodetimesColumnUserID; - private String gamemodetimesColumnSurvivalTime; - private String gamemodetimesColumnCreativeTime; - private String gamemodetimesColumnAdventureTime; - private String gamemodetimesColumnSpectatorTime; - private String nicknamesColumnUserID; - private String nicknamesColumnNick; + private final String gamemodetimesColumnSurvivalTime; + private final String gamemodetimesColumnCreativeTime; + private final String gamemodetimesColumnAdventureTime; + private final String gamemodetimesColumnSpectatorTime; + + private final String nicknamesColumnUserID; + private final String nicknamesColumnNick; + private final String nicknamesColumnCurrent; private final String ipsColumnUserID; - private String ipsColumnIP; + private final String ipsColumnIP; + + private final String sessionColumnUserID; + private final String sessionColumnSessionStart; + private final String sessionColumnSessionEnd; + + private final String killsColumnKillerUserID; + private final String killsColumnVictimUserID; + private final String killsColumnWeapon; + private final String killsColumnDate; private String versionName; @@ -90,6 +101,8 @@ public abstract class SQLDB extends Database { gamemodetimesName = "plan_gamemodetimes"; serverdataName = "plan_serverdata"; ipsName = "plan_ips"; + sessionName = "plan_sessions"; + killsName = "plan_kills"; userColumnID = "id"; locationColumnID = "id"; @@ -98,6 +111,9 @@ public abstract class SQLDB extends Database { nicknamesColumnUserID = "user_id"; gamemodetimesColumnUserID = "user_id"; ipsColumnUserID = "user_id"; + sessionColumnUserID = "user_id"; + killsColumnKillerUserID = "killer_id"; + killsColumnVictimUserID = "victim_id"; userColumnDemAge = "age"; userColumnDemGender = "gender"; @@ -116,6 +132,7 @@ public abstract class SQLDB extends Database { locationColumnWorld = "world_name"; nicknamesColumnNick = "nickname"; + nicknamesColumnCurrent = "current_nick"; gamemodetimesColumnSurvivalTime = "survival"; gamemodetimesColumnCreativeTime = "creative"; @@ -127,9 +144,11 @@ public abstract class SQLDB extends Database { commanduseColumnCommand = "command"; commanduseColumnTimesUsed = "times_used"; - serverdataColumnDate = "date"; - serverdataColumnNewPlayers = "new_players"; - serverdataColumnPlayersOnline = "players_online"; + sessionColumnSessionStart = "session_start"; + sessionColumnSessionEnd = "session_end"; + + killsColumnWeapon = "weapon"; + killsColumnDate = "date"; versionName = "plan_version"; @@ -222,6 +241,23 @@ public abstract class SQLDB extends Database { + "FOREIGN KEY(" + nicknamesColumnUserID + ") REFERENCES " + userName + "(" + userColumnID + ")" + ")" ); + query("CREATE TABLE IF NOT EXISTS " + sessionName + " (" + + sessionColumnUserID + " integer NOT NULL, " + + sessionColumnSessionStart + " bigint NOT NULL, " + + sessionColumnSessionEnd + " bigint NOT NULL, " + + "FOREIGN KEY(" + sessionColumnUserID + ") REFERENCES " + userName + "(" + userColumnID + ")" + + ")" + ); + + query("CREATE TABLE IF NOT EXISTS " + killsName + " (" + + killsColumnKillerUserID + " integer NOT NULL, " + + killsColumnVictimUserID + " integer NOT NULL, " + + killsColumnWeapon + " varchar(30) NOT NULL, " + + killsColumnDate + " bigint NOT NULL, " + + "FOREIGN KEY(" + killsColumnKillerUserID + ") REFERENCES " + userName + "(" + userColumnID + "), " + + "FOREIGN KEY(" + killsColumnVictimUserID + ") REFERENCES " + userName + "(" + userColumnID + ")" + + ")" + ); query("CREATE TABLE IF NOT EXISTS " + commanduseName + " (" + commanduseColumnCommand + " varchar(20) NOT NULL, " @@ -229,28 +265,41 @@ public abstract class SQLDB extends Database { + ")" ); - query("CREATE TABLE IF NOT EXISTS " + serverdataName + " (" - + serverdataColumnDate + " bigint NOT NULL, " - + serverdataColumnNewPlayers + " integer NOT NULL, " - + serverdataColumnPlayersOnline + " integer NOT NULL" - + ")" - ); - query("CREATE TABLE IF NOT EXISTS " + versionName + " (" + "version integer NOT NULL" + ")" ); int version = getVersion(); - version = 0; + version = 1; if (version < 1) { - try { - query("ALTER TABLE " + userName + " ADD " + userColumnDeaths + " integer NOT NULL DEFAULT 0"); - query("ALTER TABLE " + userName + " ADD " + userColumnMobKills + " integer NOT NULL DEFAULT 0"); - query("ALTER TABLE " + userName + " ADD " + userColumnPlayerKills + " integer NOT NULL DEFAULT 0"); - } catch (Exception e) { + String[] queries = new String[]{ + "ALTER TABLE " + userName + " ADD " + userColumnDeaths + " integer NOT NULL DEFAULT 0", + "ALTER TABLE " + userName + " ADD " + userColumnMobKills + " integer NOT NULL DEFAULT 0", + "ALTER TABLE " + nicknamesName + " ADD " + nicknamesColumnCurrent + " boolean NOT NULL DEFAULT (false)", + "DROP TABLE IF EXISTS " + serverdataName + }; + for (String query : queries) { + try { + query(query); + } catch (Exception e) { + } } + setVersion(1); + } else if (version < 2) { + String[] queries = new String[]{ + "ALTER TABLE " + userName + " DROP INDEX " + userColumnPlayerKills, + "ALTER TABLE " + nicknamesName + " ADD " + nicknamesColumnCurrent + " boolean NOT NULL DEFAULT 0", + "DROP TABLE IF EXISTS " + serverdataName + }; + for (String query : queries) { + try { + query(query); + } catch (Exception e) { + } + } + setVersion(2); } - setVersion(1); + } } catch (SQLException e) { e.printStackTrace(); @@ -317,6 +366,7 @@ public abstract class SQLDB extends Database { return getUserId(uuid.toString()) != -1; } + @Override public int getUserId(String uuid) { int userId = -1; try { @@ -333,6 +383,22 @@ public abstract class SQLDB extends Database { return userId; } + private UUID getUserUUID(String userID) { + UUID uuid = null; + try { + PreparedStatement statement = connection.prepareStatement("SELECT " + userColumnUUID + " FROM " + userName + " WHERE UPPER(" + userColumnID + ") LIKE UPPER(?)"); + statement.setString(1, userID); + ResultSet set = statement.executeQuery(); + while (set.next()) { + uuid = UUID.fromString(set.getString(userColumnUUID)); + } + set.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + return uuid; + } + @Override public Set getSavedUUIDs() { Set uuids = new HashSet<>(); @@ -349,105 +415,6 @@ public abstract class SQLDB extends Database { return uuids; } - @Override - public HashMap getServerDataHashMap() { - HashMap commandUse = getCommandUse(); - HashMap rawServerData = new HashMap<>(); - try { - PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + serverdataName - + " ORDER BY " + serverdataColumnDate + " DESC"); - - ResultSet set = statement.executeQuery(); - while (set.next()) { - int newPlayers = set.getInt(serverdataColumnNewPlayers); - int playersOnline = set.getInt(serverdataColumnPlayersOnline); - rawServerData.put(new Date(set.getLong(serverdataColumnDate)).toInstant().getEpochSecond() * (long) 1000, - new ServerData(commandUse, newPlayers, playersOnline)); - } - set.close(); - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - return rawServerData; - } - - @Override - public ServerData getNewestServerData() { - HashMap commandUse = getCommandUse(); - int newPlayers = 0; - Date now = new Date(); - try { - PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + serverdataName - + " ORDER BY " + serverdataColumnDate + " DESC LIMIT 1"); - - ResultSet set = statement.executeQuery(); - while (set.next()) { - Date lastSave = new Date(set.getLong(serverdataColumnDate)); - if (MiscUtils.isOnSameDay(now, lastSave)) { - newPlayers = set.getInt(serverdataColumnNewPlayers); - } - } - set.close(); - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - return new ServerData(commandUse, newPlayers); - } - - @Override - public void saveServerDataHashMap(HashMap serverData) { - try { - connection.setAutoCommit(false); - PreparedStatement statement = connection.prepareStatement("INSERT INTO " + serverdataName + " (" - + serverdataColumnDate + ", " - + serverdataColumnNewPlayers + ", " - + serverdataColumnPlayersOnline - + ") VALUES (?, ?, ?)"); - - boolean commitRequired = false; - for (long date : serverData.keySet()) { - statement.setLong(1, date); - ServerData sData = serverData.get(date); - statement.setInt(2, sData.getNewPlayers()); - statement.setInt(3, sData.getPlayersOnline()); - statement.addBatch(); - commitRequired = true; - } - statement.executeBatch(); - if (commitRequired) { - connection.commit(); - } - statement.close(); - connection.setAutoCommit(true); - - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Override - public void saveServerData(ServerData data) { - try { - saveCommandUse(data.getCommandUsage()); - long now = new Date().toInstant().getEpochSecond() * (long) 1000; - PreparedStatement statement = connection.prepareStatement("INSERT INTO " + serverdataName + " (" - + serverdataColumnDate + ", " - + serverdataColumnNewPlayers + ", " - + serverdataColumnPlayersOnline - + ") VALUES (?, ?, ?)"); - - statement.setLong(1, now); - statement.setInt(2, data.getNewPlayers()); - statement.setInt(3, data.getPlayersOnline()); - statement.execute(); - statement.close(); - } catch (SQLException ex) { - Logger.getLogger(SQLDB.class.getName()).log(Level.SEVERE, null, ex); - } - } - @Override public void saveCommandUse(HashMap data) { try { @@ -528,6 +495,15 @@ public abstract class SQLDB extends Database { statement.setString(1, "" + userId); statement.execute(); statement.close(); + statement = connection.prepareStatement("DELETE FROM " + sessionName + " WHERE UPPER(" + sessionColumnUserID + ") LIKE UPPER(?)"); + statement.setString(1, "" + userId); + statement.execute(); + statement.close(); + statement = connection.prepareStatement("DELETE FROM " + killsName + " WHERE " + killsColumnKillerUserID + " = ? OR " + killsColumnVictimUserID + " = ?"); + statement.setString(1, "" + userId); + statement.setString(2, "" + userId); + statement.execute(); + statement.close(); statement = connection.prepareStatement("DELETE FROM " + userName + " WHERE UPPER(" + userColumnUUID + ") LIKE UPPER(?)"); statement.setString(1, uuid); statement.execute(); @@ -569,76 +545,33 @@ public abstract class SQLDB extends Database { data.setLastPlayed(set.getLong(userColumnLastPlayed)); data.setDeaths(set.getInt(userColumnDeaths)); data.setMobKills(set.getInt(userColumnMobKills)); - data.setPlayerKills(set.getInt(userColumnPlayerKills)); } set.close(); statement.close(); String userId = "" + getUserId(uuid.toString()); - statement = connection.prepareStatement("SELECT * FROM " + locationName + " WHERE UPPER(" + locationColumnUserID + ") LIKE UPPER(?)"); - statement.setString(1, userId); - set = statement.executeQuery(); - - List locations = new ArrayList<>(); - while (set.next()) { - locations.add(new Location(worlds.get(set.getString(locationColumnWorld)), set.getInt(locationColumnCoordinatesX), 0, set.getInt(locationColumnCoordinatesZ))); - } - set.close(); - statement.close(); + List locations = getLocations(userId, worlds); data.addLocations(locations); - if (locations.isEmpty()) { data.setLocation(new Location(defaultWorld, 0, 0, 0)); } else { data.setLocation(locations.get(locations.size() - 1)); } - data.setLocation(new Location(defaultWorld, 0, 0, 0)); - - statement = connection.prepareStatement("SELECT * FROM " + nicknamesName + " WHERE UPPER(" + nicknamesColumnUserID + ") LIKE UPPER(?)"); - statement.setString(1, userId); - set = statement.executeQuery(); - - List nicknames = new ArrayList<>(); - while (set.next()) { - nicknames.add(set.getString(nicknamesColumnNick)); - } - set.close(); - statement.close(); + List nicknames = getNicknames(userId); data.addNicknames(nicknames); - - statement = connection.prepareStatement("SELECT * FROM " + ipsName + " WHERE UPPER(" + ipsColumnUserID + ") LIKE UPPER(?)"); - statement.setString(1, userId); - set = statement.executeQuery(); - - List ips = new ArrayList<>(); - while (set.next()) { - try { - ips.add(InetAddress.getByName(set.getString(ipsColumnIP))); - } catch (SQLException | UnknownHostException e) { - } + if (nicknames.size() > 0) { + data.setLastNick(nicknames.get(nicknames.size() - 1)); } - set.close(); - statement.close(); + + List ips = getIPAddresses(userId); data.addIpAddresses(ips); - statement = connection.prepareStatement("SELECT * FROM " + gamemodetimesName + " WHERE UPPER(" + gamemodetimesColumnUserID + ") LIKE UPPER(?)"); - statement.setString(1, userId); - set = statement.executeQuery(); - - HashMap times = new HashMap<>(); - while (set.next()) { - times.put(GameMode.SURVIVAL, set.getLong(gamemodetimesColumnSurvivalTime)); - times.put(GameMode.CREATIVE, set.getLong(gamemodetimesColumnCreativeTime)); - times.put(GameMode.ADVENTURE, set.getLong(gamemodetimesColumnAdventureTime)); - try { - times.put(GameMode.SPECTATOR, set.getLong(gamemodetimesColumnSpectatorTime)); - } catch (NoSuchFieldError e) { - } - } - set.close(); - statement.close(); + HashMap times = getGMTimes(userId); data.setGmTimes(times); + + data.addSessions(getSessionData(userId)); + data.setPlayerKills(getPlayerKills(userId)); } catch (SQLException e) { data = null; e.printStackTrace(); @@ -646,6 +579,120 @@ public abstract class SQLDB extends Database { return data; } + private HashMap getGMTimes(String userId) throws SQLException { + PreparedStatement statement; + ResultSet set; + statement = connection.prepareStatement("SELECT * FROM " + gamemodetimesName + " WHERE UPPER(" + gamemodetimesColumnUserID + ") LIKE UPPER(?)"); + statement.setString(1, userId); + set = statement.executeQuery(); + HashMap times = new HashMap<>(); + while (set.next()) { + times.put(GameMode.SURVIVAL, set.getLong(gamemodetimesColumnSurvivalTime)); + times.put(GameMode.CREATIVE, set.getLong(gamemodetimesColumnCreativeTime)); + times.put(GameMode.ADVENTURE, set.getLong(gamemodetimesColumnAdventureTime)); + try { + times.put(GameMode.SPECTATOR, set.getLong(gamemodetimesColumnSpectatorTime)); + } catch (NoSuchFieldError e) { + } + } + set.close(); + statement.close(); + return times; + } + + private List getIPAddresses(String userId) throws SQLException { + PreparedStatement statement; + ResultSet set; + statement = connection.prepareStatement("SELECT * FROM " + ipsName + " WHERE UPPER(" + ipsColumnUserID + ") LIKE UPPER(?)"); + statement.setString(1, userId); + set = statement.executeQuery(); + List ips = new ArrayList<>(); + while (set.next()) { + try { + ips.add(InetAddress.getByName(set.getString(ipsColumnIP))); + } catch (SQLException | UnknownHostException e) { + } + } + set.close(); + statement.close(); + return ips; + } + + private List getSessionData(String userId) throws SQLException { + PreparedStatement statement; + ResultSet set; + statement = connection.prepareStatement("SELECT * FROM " + sessionName + " WHERE UPPER(" + sessionColumnUserID + ") LIKE UPPER(?)"); + statement.setString(1, userId); + set = statement.executeQuery(); + List sessions = new ArrayList<>(); + while (set.next()) { + try { + sessions.add(new SessionData(set.getLong(sessionColumnSessionStart), set.getLong(sessionColumnSessionEnd))); + } catch (SQLException e) { + } + } + set.close(); + statement.close(); + return sessions; + } + + private List getNicknames(String userId) throws SQLException { + PreparedStatement statement; + ResultSet set; + statement = connection.prepareStatement("SELECT * FROM " + nicknamesName + " WHERE UPPER(" + nicknamesColumnUserID + ") LIKE UPPER(?)"); + statement.setString(1, userId); + set = statement.executeQuery(); + List nicknames = new ArrayList<>(); + String lastNick = ""; + while (set.next()) { + String nickname = set.getString(nicknamesColumnNick); + if (nickname.isEmpty()) { + continue; + } + nicknames.add(nickname); + if (set.getBoolean(nicknamesColumnCurrent)) { + lastNick = nickname; + } + } + nicknames.remove(lastNick); + nicknames.add(lastNick); + set.close(); + statement.close(); + return nicknames; + } + + private List getLocations(String userId, HashMap worlds) throws SQLException { + PreparedStatement statement; + ResultSet set; + statement = connection.prepareStatement("SELECT * FROM " + locationName + " WHERE UPPER(" + locationColumnUserID + ") LIKE UPPER(?)"); + statement.setString(1, userId); + set = statement.executeQuery(); + List locations = new ArrayList<>(); + while (set.next()) { + locations.add(new Location(worlds.get(set.getString(locationColumnWorld)), set.getInt(locationColumnCoordinatesX), 0, set.getInt(locationColumnCoordinatesZ))); + } + set.close(); + statement.close(); + return locations; + } + + private List getPlayerKills(String userId) throws SQLException { + PreparedStatement statement; + ResultSet set; + statement = connection.prepareStatement("SELECT * FROM " + killsName + " WHERE UPPER(" + killsColumnKillerUserID + ") LIKE UPPER(?)"); + statement.setString(1, userId); + set = statement.executeQuery(); + List killData = new ArrayList<>(); + while (set.next()) { + int victimID = set.getInt(killsColumnVictimUserID); + UUID victimUUID = getUserUUID(victimID + ""); + killData.add(new KillData(victimUUID, victimID, set.getString(killsColumnWeapon), set.getLong(killsColumnDate))); + } + set.close(); + statement.close(); + return killData; + } + @Override public void saveMultipleUserData(List data) { List saveLast = new ArrayList<>(); @@ -659,8 +706,7 @@ public abstract class SQLDB extends Database { + userColumnLoginTimes + "=?, " + userColumnLastPlayed + "=?, " + userColumnDeaths + "=?, " - + userColumnMobKills + "=?, " - + userColumnPlayerKills + "=? " + + userColumnMobKills + "=? " + "WHERE UPPER(" + userColumnUUID + ") LIKE UPPER(?)"; try { connection.setAutoCommit(false); @@ -672,25 +718,28 @@ public abstract class SQLDB extends Database { saveLast.add(uData); continue; } - - uStatement.setInt(1, uData.getDemData().getAge()); - uStatement.setString(2, uData.getDemData().getGender().toString().toLowerCase()); - uStatement.setString(3, uData.getDemData().getGeoLocation()); - GameMode gm = uData.getLastGamemode(); - if (gm != null) { - uStatement.setString(4, uData.getLastGamemode().name()); - } else { - uStatement.setString(4, GameMode.SURVIVAL.name()); + try { + uStatement.setInt(1, uData.getDemData().getAge()); + uStatement.setString(2, uData.getDemData().getGender().toString().toLowerCase()); + uStatement.setString(3, uData.getDemData().getGeoLocation()); + GameMode gm = uData.getLastGamemode(); + if (gm != null) { + uStatement.setString(4, uData.getLastGamemode().name()); + } else { + uStatement.setString(4, GameMode.SURVIVAL.name()); + } + uStatement.setLong(5, uData.getLastGmSwapTime()); + uStatement.setLong(6, uData.getPlayTime()); + uStatement.setInt(7, uData.getLoginTimes()); + uStatement.setLong(8, uData.getLastPlayed()); + uStatement.setString(9, uData.getUuid().toString()); + uStatement.setInt(10, uData.getDeaths()); + uStatement.setInt(11, uData.getMobKills()); + uStatement.addBatch(); + } catch (SQLException | NullPointerException e) { + saveLast.add(uData); + continue; } - uStatement.setLong(5, uData.getLastGmSwapTime()); - uStatement.setLong(6, uData.getPlayTime()); - uStatement.setInt(7, uData.getLoginTimes()); - uStatement.setLong(8, uData.getLastPlayed()); - uStatement.setString(9, uData.getUuid().toString()); - uStatement.setInt(10, uData.getDeaths()); - uStatement.setInt(11, uData.getMobKills()); - uStatement.setInt(12, uData.getPlayerKills()); - uStatement.addBatch(); commitRequired = true; } uStatement.executeBatch(); @@ -703,8 +752,10 @@ public abstract class SQLDB extends Database { for (UserData uData : data) { int userId = getUserId(uData.getUuid().toString()); saveLocationList(userId, uData.getLocations()); - saveNickList(userId, uData.getNicknames()); + saveNickList(userId, uData.getNicknames(), uData.getLastNick()); saveIPList(userId, uData.getIps()); + saveSessionList(userId, uData.getSessions()); + savePlayerKills(userId, uData.getPlayerKills()); connection.setAutoCommit(true); saveGMTimes(userId, uData.getGmTimes()); } @@ -734,8 +785,7 @@ public abstract class SQLDB extends Database { + userColumnLoginTimes + "=?, " + userColumnLastPlayed + "=?, " + userColumnDeaths + "=?, " - + userColumnMobKills + "=?, " - + userColumnPlayerKills + "=? " + + userColumnMobKills + "=? " + "WHERE UPPER(" + userColumnUUID + ") LIKE UPPER(?)"; PreparedStatement statement = connection.prepareStatement(sql); @@ -755,7 +805,6 @@ public abstract class SQLDB extends Database { statement.setString(9, uuid.toString()); statement.setInt(10, data.getDeaths()); statement.setInt(11, data.getMobKills()); - statement.setInt(12, data.getPlayerKills()); update = statement.executeUpdate(); } if (update == 0) { @@ -770,9 +819,8 @@ public abstract class SQLDB extends Database { + userColumnLoginTimes + ", " + userColumnLastPlayed + ", " + userColumnDeaths + ", " - + userColumnMobKills + ", " - + userColumnPlayerKills - + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + + userColumnMobKills + + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); statement.setString(1, uuid.toString()); statement.setInt(2, data.getDemData().getAge()); @@ -790,15 +838,16 @@ public abstract class SQLDB extends Database { statement.setLong(9, data.getLastPlayed()); statement.setInt(10, data.getDeaths()); statement.setInt(11, data.getMobKills()); - statement.setInt(12, data.getPlayerKills()); statement.execute(); statement.close(); userId = getUserId(uuid.toString()); } saveLocationList(userId, data.getLocations()); - saveNickList(userId, data.getNicknames()); + saveNickList(userId, data.getNicknames(), data.getLastNick()); saveIPList(userId, data.getIps()); + saveSessionList(userId, data.getSessions()); + savePlayerKills(userId, data.getPlayerKills()); connection.setAutoCommit(true); saveGMTimes(userId, data.getGmTimes()); } catch (SQLException | NullPointerException e) { @@ -847,7 +896,7 @@ public abstract class SQLDB extends Database { } } - public void saveNickList(int userId, HashSet names) { + public void saveNickList(int userId, HashSet names, String lastNick) { try { PreparedStatement statement = connection.prepareStatement( "DELETE FROM " + nicknamesName + " WHERE UPPER(" + nicknamesColumnUserID + ") LIKE UPPER(?)"); @@ -857,12 +906,80 @@ public abstract class SQLDB extends Database { connection.setAutoCommit(false); statement = connection.prepareStatement("INSERT INTO " + nicknamesName + " (" + nicknamesColumnUserID + ", " + + nicknamesColumnCurrent + ", " + nicknamesColumnNick - + ") VALUES (?, ?)"); + + ") VALUES (?, ?, ?)"); boolean commitRequired = false; for (String name : names) { statement.setInt(1, userId); - statement.setString(2, name); + statement.setInt(2, (name.equals(lastNick)) ? 1 : 0); + statement.setString(3, name); + statement.addBatch(); + commitRequired = true; + } + statement.executeBatch(); + if (commitRequired) { + connection.commit(); + } + statement.close(); + + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public void saveSessionList(int userId, List sessions) { + try { + PreparedStatement statement = connection.prepareStatement( + "DELETE FROM " + sessionName + " WHERE UPPER(" + sessionColumnUserID + ") LIKE UPPER(?)"); + statement.setString(1, "" + userId); + statement.execute(); + + connection.setAutoCommit(false); + statement = connection.prepareStatement("INSERT INTO " + sessionName + " (" + + sessionColumnUserID + ", " + + sessionColumnSessionStart + ", " + + sessionColumnSessionEnd + + ") VALUES (?, ?, ?)"); + boolean commitRequired = false; + for (SessionData session : sessions) { + statement.setInt(1, userId); + statement.setLong(2, session.getSessionStart()); + statement.setLong(3, session.getSessionEnd()); + statement.addBatch(); + commitRequired = true; + } + statement.executeBatch(); + if (commitRequired) { + connection.commit(); + } + statement.close(); + + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public void savePlayerKills(int userId, List kills) { + try { + PreparedStatement statement = connection.prepareStatement( + "DELETE FROM " + killsName + " WHERE UPPER(" + killsColumnKillerUserID + ") LIKE UPPER(?)"); + statement.setString(1, "" + userId); + statement.execute(); + + connection.setAutoCommit(false); + statement = connection.prepareStatement("INSERT INTO " + killsName + " (" + + killsColumnKillerUserID + ", " + + killsColumnVictimUserID + ", " + + killsColumnWeapon + ", " + + killsColumnDate + + ") VALUES (?, ?, ?, ?)"); + boolean commitRequired = false; + for (KillData kill : kills) { + statement.setInt(1, userId); + statement.setInt(2, kill.getVictimUserID()); + statement.setString(2, kill.getWeapon()); + statement.setLong(4, kill.getDate()); statement.addBatch(); commitRequired = true; } @@ -949,7 +1066,11 @@ public abstract class SQLDB extends Database { @Override public void clean() { checkConnection(); - plugin.log("Database Cleaning has not yet been implemented."); + try { + query("DROP TABLE " + serverdataName); + } catch (Exception e) { + + } } @Override @@ -957,140 +1078,19 @@ public abstract class SQLDB extends Database { checkConnection(); try { - connection.prepareStatement("DELETE FROM " + locationName).executeUpdate(); - connection.prepareStatement("DELETE FROM " + nicknamesName).executeUpdate(); - connection.prepareStatement("DELETE FROM " + ipsName).executeUpdate(); - connection.prepareStatement("DELETE FROM " + gamemodetimesName).executeUpdate(); - connection.prepareStatement("DELETE FROM " + commanduseName).executeUpdate(); - connection.prepareStatement("DELETE FROM " + serverdataName).executeUpdate(); - connection.prepareStatement("DELETE FROM " + userName).executeUpdate(); + query("DROP TABLE " + locationName); + query("DROP TABLE " + ipsName); + query("DROP TABLE " + gamemodetimesName); + query("DROP TABLE " + nicknamesName); + query("DROP TABLE " + killsName); + query("DROP TABLE " + sessionName); + query("DROP TABLE " + commanduseName); + query("DROP TABLE " + userName); } catch (SQLException e) { e.printStackTrace(); } } - // Setters --- - public void setUserName(String userName) { - this.userName = userName; - } - - public void setLocationName(String locationName) { - this.locationName = locationName; - } - - public void setServerdataName(String serverdataName) { - this.serverdataName = serverdataName; - } - - public void setCommanduseName(String commanduseName) { - this.commanduseName = commanduseName; - } - - public void setGamemodetimesName(String gamemodetimesName) { - this.gamemodetimesName = gamemodetimesName; - } - - public void setNicknamesName(String nicknamesName) { - this.nicknamesName = nicknamesName; - } - - public void setIpsName(String ipsName) { - this.ipsName = ipsName; - } - - public void setUserColumnUUID(String userColumnUUID) { - this.userColumnUUID = userColumnUUID; - } - - public void setUserColumnPlayTime(String userColumnPlayTime) { - this.userColumnPlayTime = userColumnPlayTime; - } - - public void setUserColumnDemGeoLocation(String userColumnDemGeoLocation) { - this.userColumnDemGeoLocation = userColumnDemGeoLocation; - } - - public void setUserColumnDemAge(String userColumnDemAge) { - this.userColumnDemAge = userColumnDemAge; - } - - public void setUserColumnDemGender(String userColumnDemGender) { - this.userColumnDemGender = userColumnDemGender; - } - - public void setUserColumnLastGM(String userColumnLastGM) { - this.userColumnLastGM = userColumnLastGM; - } - - public void setUserColumnLastGMSwapTime(String userColumnLastGMSwapTime) { - this.userColumnLastGMSwapTime = userColumnLastGMSwapTime; - } - - public void setLocationColumnCoordinatesZ(String locationColumnCoordinates) { - this.locationColumnCoordinatesZ = locationColumnCoordinates; - } - - public void setLocationColumnCoordinatesX(String locationColumnCoordinates) { - this.locationColumnCoordinatesX = locationColumnCoordinates; - } - - public void setLocationColumnWorld(String locationColumnWorld) { - this.locationColumnWorld = locationColumnWorld; - } - - public void setServerdataColumnDate(String serverdataColumnDate) { - this.serverdataColumnDate = serverdataColumnDate; - } - - public void setServerdataColumnPlayersOnline(String serverdataColumnPlayersOnline) { - this.serverdataColumnPlayersOnline = serverdataColumnPlayersOnline; - } - - public void setServerdataColumnNewPlayers(String serverdataColumnNewPlayers) { - this.serverdataColumnNewPlayers = serverdataColumnNewPlayers; - } - - public void setCommanduseColumnCommand(String commanduseColumnCommand) { - this.commanduseColumnCommand = commanduseColumnCommand; - } - - public void setCommanduseColumnTimesUsed(String commanduseColumnTimesUsed) { - this.commanduseColumnTimesUsed = commanduseColumnTimesUsed; - } - - public void setUserColumnLoginTimes(String userColumnLoginTimes) { - this.userColumnLoginTimes = userColumnLoginTimes; - } - - public void setGamemodetimesColumnSurvivalTime(String gamemodetimesColumnSurvivalTime) { - this.gamemodetimesColumnSurvivalTime = gamemodetimesColumnSurvivalTime; - } - - public void setGamemodetimesColumnCreativeTime(String gamemodetimesColumnCreativeTime) { - this.gamemodetimesColumnCreativeTime = gamemodetimesColumnCreativeTime; - } - - public void setGamemodetimesColumnAdventureTime(String gamemodetimesColumnAdventureTime) { - this.gamemodetimesColumnAdventureTime = gamemodetimesColumnAdventureTime; - } - - public void setGamemodetimesColumnSpectatorTime(String gamemodetimesColumnSpectatorTime) { - this.gamemodetimesColumnSpectatorTime = gamemodetimesColumnSpectatorTime; - } - - public void setNicknamesColumnUserID(String nicknamesColumnUserID) { - this.nicknamesColumnUserID = nicknamesColumnUserID; - } - - public void setNicknamesColumnNick(String nicknamesColumnNick) { - this.nicknamesColumnNick = nicknamesColumnNick; - } - - public void setIpsColumnIP(String ipsColumnIP) { - this.ipsColumnIP = ipsColumnIP; - } - - // Getters public boolean supportsModification() { return supportsModification; } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/databases/SQLiteDB.java b/Plan/src/main/java/com/djrapitops/plan/database/databases/SQLiteDB.java index ac6a307a1..c0352fbc2 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/databases/SQLiteDB.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/databases/SQLiteDB.java @@ -53,11 +53,6 @@ public class SQLiteDB extends SQLDB { } } - @Override - public void getConfigDefaults(ConfigurationSection section) { - - } - @Override public String getName() { return "SQLite"; diff --git a/Plan/src/main/java/com/djrapitops/plan/ui/graphs/PlayerActivityGraphCreator.java b/Plan/src/main/java/com/djrapitops/plan/ui/graphs/PlayerActivityGraphCreator.java index 0281801d5..2106a7895 100644 --- a/Plan/src/main/java/com/djrapitops/plan/ui/graphs/PlayerActivityGraphCreator.java +++ b/Plan/src/main/java/com/djrapitops/plan/ui/graphs/PlayerActivityGraphCreator.java @@ -2,7 +2,6 @@ package main.java.com.djrapitops.plan.ui.graphs; import com.djrapitops.plan.Phrase; import com.djrapitops.plan.Plan; -import com.djrapitops.plan.data.ServerData; import com.djrapitops.plan.utilities.FormatUtils; import com.googlecode.charts4j.AxisLabels; import com.googlecode.charts4j.AxisLabelsFactory; @@ -14,8 +13,8 @@ import com.googlecode.charts4j.Plots; import com.googlecode.charts4j.XYLine; import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; import java.util.List; +import main.java.com.djrapitops.plan.data.SessionData; import static org.bukkit.plugin.java.JavaPlugin.getPlugin; /** @@ -27,12 +26,19 @@ public class PlayerActivityGraphCreator { /** * Creates a new url for a PlayerActivity graph. * - * @param rawServerData HashMap of all ServerData + * @param sessionData SessionData of Players in scale. * @param scale Long in ms, time the graph will be limited to. * @return Url of charts4j image link. */ - public static String createChart(HashMap rawServerData, long scale) { + public static String createChart(List sessionData, long scale) { + List sessionStarts = new ArrayList<>(); + List sessionEnds = new ArrayList<>(); + sessionData.parallelStream().forEach( + (session) -> { + sessionEnds.add(session.getSessionEnd()); + sessionStarts.add(session.getSessionStart()); + }); List xListDate = new ArrayList<>(); List pYList = new ArrayList<>(); @@ -48,14 +54,28 @@ public class PlayerActivityGraphCreator { int lastSavedPValue = -1; long lastSaveI = 0; for (long i = nowMinusScale; i <= now; i += 1000) { - if (rawServerData.containsKey(i)) { - ServerData serverData = rawServerData.get(i); - lastPValue = serverData.getPlayersOnline(); + if (sessionStarts.contains(i)) { + int amount = 0; + for (long start : sessionStarts) { + if (start == i) { + amount++; + } + } + lastPValue += amount; + } + if (sessionEnds.contains(i)) { + int amount = 0; + for (long end : sessionEnds) { + if (end == i) { + amount++; + } + } + lastPValue -= amount; } Double scaledDateValue = ((i - nowMinusScale) * 1.0 / scale) * 100; Double scaledPlayerValue = (lastPValue * 1.0 / maxPlayers) * 100; - if (lastSavedPValue != lastPValue || i - lastSaveI > (scale / (long) 50)) { + if (lastSavedPValue != lastPValue || i - lastSaveI > (scale / (long) 100)) { lastSaveI = i; xListDate.add(scaledDateValue); pYList.add((lastSavedPValue * 1.0 / maxPlayers) * 100); diff --git a/Plan/src/main/java/com/djrapitops/plan/utilities/Analysis.java b/Plan/src/main/java/com/djrapitops/plan/utilities/Analysis.java index d49a82d9b..f2c64022e 100644 --- a/Plan/src/main/java/com/djrapitops/plan/utilities/Analysis.java +++ b/Plan/src/main/java/com/djrapitops/plan/utilities/Analysis.java @@ -4,12 +4,10 @@ import com.djrapitops.plan.Phrase; import com.djrapitops.plan.Plan; import com.djrapitops.plan.PlanLiteHook; import com.djrapitops.plan.data.AnalysisData; -import com.djrapitops.plan.data.ServerData; import com.djrapitops.plan.data.UserData; import com.djrapitops.plan.data.cache.AnalysisCacheHandler; import com.djrapitops.plan.data.cache.InspectCacheHandler; import java.util.ArrayList; -import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -18,6 +16,7 @@ import java.util.UUID; import main.java.com.djrapitops.plan.Settings; import main.java.com.djrapitops.plan.data.PlanLiteAnalyzedData; import main.java.com.djrapitops.plan.data.RawAnalysisData; +import main.java.com.djrapitops.plan.data.SessionData; import main.java.com.djrapitops.plan.ui.Html; import main.java.com.djrapitops.plan.utilities.HtmlUtils; import org.bukkit.GameMode; @@ -34,7 +33,6 @@ public class Analysis { private final Plan plugin; private final InspectCacheHandler inspectCache; private final List rawData; - private HashMap rawServerData; private final List added; /** @@ -90,12 +88,9 @@ public class Analysis { // Create empty Dataset final RawAnalysisData raw = new RawAnalysisData(); raw.setCommandUse(plugin.getDB().getCommandUse()); - rawServerData = plugin.getDB().getServerDataHashMap(); log(Phrase.ANALYSIS_BEGIN_ANALYSIS + ""); AnalysisData data = new AnalysisData(); - createPlayerActivityGraphs(data); - // DEPRECATED - WILL BE REMOVED boolean planLiteEnabled = isPlanLiteEnabled(); PlanLiteAnalyzedData plData = new PlanLiteAnalyzedData(); @@ -142,16 +137,19 @@ public class Analysis { } else { raw.addInactive(1); } - raw.addTotalKills(uData.getPlayerKills()); + raw.addTotalKills(uData.getPlayerKills().size()); raw.addTotalMobKills(uData.getMobKills()); raw.addTotalDeaths(uData.getDeaths()); raw.getSessiondata().addAll(uData.getSessions()); + raw.getRegistered().add(uData.getRegistered()); } catch (NullPointerException e) { plugin.logError(Phrase.DATA_CORRUPTION_WARN.parse(uData.getUuid() + "")); } }); // Analyze & Save RawAnalysisData to AnalysisData + createPlayerActivityGraphs(data, raw.getSessiondata(), raw.getRegistered()); + data.setTop20ActivePlayers(AnalysisUtils.createActivePlayersTable(raw.getPlaytimes(), 20)); data.setRecentPlayers(AnalysisUtils.createListStringOutOfHashMapLong(raw.getLatestLogins(), 20)); @@ -254,64 +252,20 @@ public class Analysis { data.setGm3Perc((gmThree * 1.0 / gmTotal)); } - private void createPlayerActivityGraphs(AnalysisData data) { + private void createPlayerActivityGraphs(AnalysisData data, List sData, List registered) { + long now = new Date().toInstant().getEpochSecond() * (long) 1000; long scaleMonth = (long) 2592000 * (long) 1000; - String playerActivityHtmlMonth = AnalysisUtils.createPlayerActivityGraph(rawServerData, scaleMonth); - data.setPlayersChartImgHtmlMonth(playerActivityHtmlMonth); - data.setNewPlayersMonth(getHighestNPValueForScale(scaleMonth)); + String[] urlAndNumber = AnalysisUtils.analyzeSessionData(sData, registered, scaleMonth, now); + data.setPlayersChartImgHtmlMonth(urlAndNumber[0]); + data.setNewPlayersMonth(Integer.parseInt(urlAndNumber[1])); long scaleWeek = 604800 * 1000; - String playerActivityHtmlWeek = AnalysisUtils.createPlayerActivityGraph(rawServerData, scaleWeek); - data.setPlayersChartImgHtmlWeek(playerActivityHtmlWeek); - data.setNewPlayersWeek(getHighestNPValueForScale(scaleWeek)); + urlAndNumber = AnalysisUtils.analyzeSessionData(sData, registered, scaleWeek, now); + data.setPlayersChartImgHtmlWeek(urlAndNumber[0]); + data.setNewPlayersWeek(Integer.parseInt(urlAndNumber[1])); long scaleDay = 86400 * 1000; - String playerActivityHtmlDay = AnalysisUtils.createPlayerActivityGraph(rawServerData, scaleDay); - data.setPlayersChartImgHtmlDay(playerActivityHtmlDay); - data.setNewPlayersDay(getHighestNPValueForScale(scaleDay)); - } - - private int getHighestNPValueForScale(long scale) { - List> sDataForEachDay = sortServerDatasByDay(scale); - int NPTotalInsideScaleTimeFrame = 0; - NPTotalInsideScaleTimeFrame = sDataForEachDay.parallelStream() - .map((serverDataList) -> { - int highestNPValue = 0; - for (ServerData serverData : serverDataList) { - int newPlayers = serverData.getNewPlayers(); - if (newPlayers > highestNPValue) { - highestNPValue = newPlayers; - } - } - return highestNPValue; - }).map((highestNPValue) -> highestNPValue) - .reduce(NPTotalInsideScaleTimeFrame, Integer::sum); - return NPTotalInsideScaleTimeFrame; - } - - private List> sortServerDatasByDay(long scale) { - List> sDataForEachDay = new ArrayList<>(); - Date lastStartOfDay = null; - List keys = new ArrayList<>(); - keys.addAll(rawServerData.keySet()); - Collections.sort(keys); - for (long date : keys) { - Date startOfDate = MiscUtils.getStartOfDate(new Date(date)); - if (lastStartOfDay == null) { - sDataForEachDay.add(new ArrayList<>()); - lastStartOfDay = startOfDate; - } - // If data is older than one month, ignore - if (new Date().getTime() - startOfDate.getTime() > scale) { - continue; - } - if (startOfDate.getTime() != lastStartOfDay.getTime()) { - sDataForEachDay.add(new ArrayList<>()); - } - int lastIndex = sDataForEachDay.size() - 1; - ServerData serverData = rawServerData.get(date); - sDataForEachDay.get(lastIndex).add(serverData); - lastStartOfDay = startOfDate; - } - return sDataForEachDay; + urlAndNumber = AnalysisUtils.analyzeSessionData(sData, registered, scaleDay, now); + data.setPlayersChartImgHtmlDay(urlAndNumber[0]); + data.setNewPlayersDay(Integer.parseInt(urlAndNumber[1])); } }).runTaskAsynchronously(plugin); } diff --git a/Plan/src/main/java/com/djrapitops/plan/utilities/AnalysisUtils.java b/Plan/src/main/java/com/djrapitops/plan/utilities/AnalysisUtils.java index 5ae107dfa..4f05f33c3 100644 --- a/Plan/src/main/java/com/djrapitops/plan/utilities/AnalysisUtils.java +++ b/Plan/src/main/java/com/djrapitops/plan/utilities/AnalysisUtils.java @@ -1,12 +1,13 @@ package com.djrapitops.plan.utilities; -import com.djrapitops.plan.data.ServerData; import com.djrapitops.plan.ui.graphs.GMTimesPieChartCreator; +import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import main.java.com.djrapitops.plan.Settings; +import main.java.com.djrapitops.plan.data.SessionData; import main.java.com.djrapitops.plan.ui.Html; import main.java.com.djrapitops.plan.ui.graphs.ActivityPieChartCreator; import main.java.com.djrapitops.plan.ui.graphs.PlayerActivityGraphCreator; @@ -45,13 +46,11 @@ public class AnalysisUtils { return Html.IMG.parse(url); } - - static String createPlayerActivityGraph(HashMap rawServerData, long scale) { - String url = PlayerActivityGraphCreator.createChart(rawServerData, scale); + static String createPlayerActivityGraph(List sessionData, long scale) { + String url = PlayerActivityGraphCreator.createChart(sessionData, scale); return Html.IMG.parse(url); } - static boolean isActive(long lastPlayed, long playTime, int loginTimes) { int timeToActive = Settings.ANALYSIS_MINUTES_FOR_ACTIVE.getNumber(); if (timeToActive < 0) { @@ -108,4 +107,23 @@ public class AnalysisUtils { html += "

"; return html; } + + static String[] analyzeSessionData(List sessionData, List registered, long scale, long now) { + String[] returnA = new String[2]; + List inScale = new ArrayList<>(); + sessionData.stream() + .filter((s) -> (s.getSessionStart() > now - scale)) + .forEach((s) -> { + inScale.add(s); + }); + returnA[0] = createPlayerActivityGraph(inScale, scale); + + int newPlayers = 0; + // Filters out register dates before scale + newPlayers = registered.stream() + .filter((reg) -> (reg > now - scale)) + .map((_item) -> 1).reduce(newPlayers, Integer::sum); + returnA[1] = "" + newPlayers; + return returnA; + } } diff --git a/Plan/src/main/java/com/djrapitops/plan/utilities/DataCombineUtils.java b/Plan/src/main/java/com/djrapitops/plan/utilities/DataCombineUtils.java index 9eeaef575..3e545d886 100644 --- a/Plan/src/main/java/com/djrapitops/plan/utilities/DataCombineUtils.java +++ b/Plan/src/main/java/com/djrapitops/plan/utilities/DataCombineUtils.java @@ -2,7 +2,6 @@ package main.java.com.djrapitops.plan.utilities; import com.djrapitops.plan.Phrase; import com.djrapitops.plan.data.DemographicsData; -import com.djrapitops.plan.data.ServerData; import com.djrapitops.plan.data.UserData; import java.util.ArrayList; import java.util.HashMap; @@ -77,34 +76,6 @@ public class DataCombineUtils { return fData; } - /** - * Combines two conflicting ServerDatasets - * - * @param fData First Dataset - * @param tData Second Dataset - * @return Combined ServerDataset - */ - public static HashMap combineServerDatas(HashMap fData, HashMap tData) { - HashMap combinedData = new HashMap<>(); - Set allDates = new HashSet<>(); - allDates.addAll(fData.keySet()); - allDates.addAll(tData.keySet()); - allDates.parallelStream().forEach((Long date) -> { - ServerData fServerData = fData.get(date); - ServerData tServerData = tData.get(date); - if (fServerData == null) { - combinedData.put(date, tServerData); - } else if (tServerData == null) { - combinedData.put(date, fServerData); - } else if (fServerData.getPlayersOnline() > tServerData.getPlayersOnline()) { - combinedData.put(date, fServerData); - } else { - combinedData.put(date, tServerData); - } - }); - return combinedData; - } - /** * Combines Two conflicting command usage datasets. * @@ -141,18 +112,4 @@ public class DataCombineUtils { } return combinedData; } - - public static HashMap getCommandUse(HashMap fromServerData) { - ServerData sData = null; - for (long sDataKey : fromServerData.keySet()) { - sData = fromServerData.get(sDataKey); - break; - } - HashMap fromCommandUse = null; - if (sData != null) { - fromCommandUse = sData.getCommandUsage(); - } - return fromCommandUse; - } - } diff --git a/Plan/src/main/resources/config.yml b/Plan/src/main/resources/config.yml index cb8d7a1a4..b87016e2b 100644 --- a/Plan/src/main/resources/config.yml +++ b/Plan/src/main/resources/config.yml @@ -62,11 +62,3 @@ mysql: user: root password: minecraft database: Plan - tables: - users: plan_users - locations: plan_locations - nicknames: plan_nicknames - gamemodetimes: plan_gamemodetimes - ips: plan_ips - commandusages: plan_commandusages - serverdata: plan_serverdata