From cc524365d6624ec71d2a638f240260ebe5513877 Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Mon, 21 Aug 2017 14:08:04 +0200 Subject: [PATCH 01/16] Add check for the server key --- .gitignore | 6 ++++- .../main/java/com/djrapitops/plan/Plan.java | 12 +++++++++- .../plan/data/handling/PlaytimeHandling.java | 6 +---- .../plan/ui/webserver/WebServer.java | 24 +++++++++++++++++-- .../webserver/api/bukkit/InspectWebAPI.java | 2 +- .../com/djrapitops/plan/PermissionsTest.java | 1 - 6 files changed, 40 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index b4d1bc86c..f66ece913 100644 --- a/.gitignore +++ b/.gitignore @@ -12,4 +12,8 @@ /Filetool/nbproject/private/ /Filetool/build/ /PlanPluginBridge/target/ -/MakroS/nbproject/private/ \ No newline at end of file +/MakroS/nbproject/private/ +*.xml +Plan/Plan.iml +Plan/.sonar/.sonar_lock +Plan/.sonar/report-task.txt diff --git a/Plan/src/main/java/com/djrapitops/plan/Plan.java b/Plan/src/main/java/com/djrapitops/plan/Plan.java index de81fb1bf..bf14e9d5b 100644 --- a/Plan/src/main/java/com/djrapitops/plan/Plan.java +++ b/Plan/src/main/java/com/djrapitops/plan/Plan.java @@ -189,7 +189,7 @@ public class Plan extends BukkitPlugin { } Benchmark.start("ServerInfo Registration"); - serverInfoManager = new ServerInfoManager(this); + serverInfoManager = new ServerInfoManager(this); Benchmark.stop("Enable", "ServerInfo Registration"); setupFilter(); // TODO Move to RegisterCommand Constructor @@ -455,4 +455,14 @@ public class Plan extends BukkitPlugin { public ServerVariableHolder getVariable() { return serverVariableHolder; } + + /** + * Used to get the object storing server info + * + * @return ServerInfoManager + * @see ServerInfoManager + */ + public ServerInfoManager getServerInfoManager() { + return serverInfoManager; + } } diff --git a/Plan/src/main/java/com/djrapitops/plan/data/handling/PlaytimeHandling.java b/Plan/src/main/java/com/djrapitops/plan/data/handling/PlaytimeHandling.java index aa94f9ca0..9aa962be3 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/handling/PlaytimeHandling.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/handling/PlaytimeHandling.java @@ -20,11 +20,7 @@ public class PlaytimeHandling { data.setLastPlayed(time); GMTimes gmTimes = data.getGmTimes(); - if (gamemode != null) { - gmTimes.changeState(gamemode, playTime); - } else { - gmTimes.changeState(gmTimes.getState(), playTime); - } + gmTimes.changeState(gamemode != null ? gamemode : gmTimes.getState(), playTime); WorldTimes worldTimes = data.getWorldTimes(); worldTimes.changeState(worldName, playTime); diff --git a/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java b/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java index 60fb49a9e..74a509cb8 100644 --- a/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java +++ b/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java @@ -308,11 +308,19 @@ public class WebServer { } Map variables = readVariables(response); - - //TODO ADD CHECK IF SERVER KEY VALID + String key = variables.get("key"); Plan plan = Plan.getInstance(); + if (!checkKey(plan, key)) { + String error = "Server Key not given or invalid"; + return PageCacheHandler.loadPage(error, () -> { + ForbiddenResponse forbidden = new ForbiddenResponse(); + forbidden.setContent(error); + return forbidden; + }); + } + WebAPI api = WebAPIManager.getAPI(method); if (api == null) { @@ -328,6 +336,18 @@ public class WebServer { } } + private boolean checkKey(Plan plan, String key) { + UUID uuid = plan.getServerInfoManager().getServerUUID(); + UUID keyUUID; + try { + keyUUID = UUID.fromString(key); + } catch (IllegalArgumentException e) { + return false; + } + + return uuid.equals(keyUUID); + } + private Map readVariables(String response) { String[] variables = response.split("&"); diff --git a/Plan/src/main/java/com/djrapitops/plan/ui/webserver/api/bukkit/InspectWebAPI.java b/Plan/src/main/java/com/djrapitops/plan/ui/webserver/api/bukkit/InspectWebAPI.java index 0b4d759b8..c64e10694 100644 --- a/Plan/src/main/java/com/djrapitops/plan/ui/webserver/api/bukkit/InspectWebAPI.java +++ b/Plan/src/main/java/com/djrapitops/plan/ui/webserver/api/bukkit/InspectWebAPI.java @@ -35,7 +35,7 @@ public class InspectWebAPI implements WebAPI { return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error)); } - Plan.getInstance().getInspectCache().cache(uuid); + plan.getInspectCache().cache(uuid); return PageCacheHandler.loadPage("success", SuccessResponse::new); } diff --git a/Plan/test/test/java/main/java/com/djrapitops/plan/PermissionsTest.java b/Plan/test/test/java/main/java/com/djrapitops/plan/PermissionsTest.java index 0d2c79a46..15d338f71 100644 --- a/Plan/test/test/java/main/java/com/djrapitops/plan/PermissionsTest.java +++ b/Plan/test/test/java/main/java/com/djrapitops/plan/PermissionsTest.java @@ -28,5 +28,4 @@ public class PermissionsTest { public void testGetPermission() { assertEquals("plan.inspect.other", Permissions.INSPECT_OTHER.getPerm()); } - } \ No newline at end of file From 76a79c8c57a7997369ba083fe777c9a1035be400 Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Mon, 21 Aug 2017 16:53:09 +0200 Subject: [PATCH 02/16] Fix Kill Detection when the player is killed by an Arrow --- .../data/listeners/PlanDeathEventListener.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) 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 2444694ad..d447edd0a 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 @@ -14,6 +14,7 @@ import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.projectiles.ProjectileSource; /** * Event Listener for EntityDeathEvents. @@ -88,6 +89,20 @@ public class PlanDeathEventListener implements Listener { handler.addToPool(new KillInfo(owner.getUniqueId(), time, dead, "Wolf")); } + + if (killerEntity instanceof Arrow) { + Arrow arrow = (Arrow) killerEntity; + + ProjectileSource source = arrow.getShooter(); + + if (!(source instanceof Player)) { + return; + } + + Player player = (Player) source; + + handler.addToPool(new KillInfo(player.getUniqueId(), time, dead, "Bow")); + } } } From b0a4d6778295f26b0e50a02374b816154790626b Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Mon, 21 Aug 2017 18:33:54 +0200 Subject: [PATCH 03/16] Change some WorldTimes methods --- .../com/djrapitops/plan/data/time/WorldTimes.java | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/Plan/src/main/java/com/djrapitops/plan/data/time/WorldTimes.java b/Plan/src/main/java/com/djrapitops/plan/data/time/WorldTimes.java index 5c2482e32..35040db40 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/time/WorldTimes.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/time/WorldTimes.java @@ -61,9 +61,11 @@ public class WorldTimes { } currentGMTimes.changeState(currentGamemode, changeTime); } + for (GMTimes gmTimes : worldTimes.values()) { gmTimes.setLastStateChange(changeTime); } + currentWorld = worldName; currentGamemode = gameMode; } @@ -76,10 +78,7 @@ public class WorldTimes { */ public long getWorldPlaytime(String world) { GMTimes gmTimes = worldTimes.get(world); - if (gmTimes != null) { - return gmTimes.getTotal(); - } - return 0; + return gmTimes != null ? gmTimes.getTotal() : 0; } public long getTotal() { @@ -99,11 +98,7 @@ public class WorldTimes { * @return GMTimes object with play times of each GameMode. */ public GMTimes getGMTimes(String world) { - GMTimes gmTimes = worldTimes.get(world); - if (gmTimes != null) { - return gmTimes; - } - return new GMTimes(); + return worldTimes.getOrDefault(world, new GMTimes()); } @Override From 67ef64ec0d62d92b2d046bf1e35adcdd20f771aa Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Mon, 21 Aug 2017 19:13:39 +0200 Subject: [PATCH 04/16] Fixes #260 Fixes JavaDoc at MathUtils --- .../com/djrapitops/plan/command/commands/InspectCommand.java | 2 +- .../djrapitops/plan/command/commands/QuickInspectCommand.java | 4 ++-- .../com/djrapitops/plan/utilities/analysis/MathUtils.java | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Plan/src/main/java/com/djrapitops/plan/command/commands/InspectCommand.java b/Plan/src/main/java/com/djrapitops/plan/command/commands/InspectCommand.java index 1fd75f173..e0eb76cd5 100644 --- a/Plan/src/main/java/com/djrapitops/plan/command/commands/InspectCommand.java +++ b/Plan/src/main/java/com/djrapitops/plan/command/commands/InspectCommand.java @@ -124,7 +124,7 @@ public class InspectCommand extends SubCommand { } private void sendInspectMsg(ISender sender, String playerName, UUID uuid) { - sender.sendMessage(Locale.get(Msg.CMD_HEADER_INSPECT) + playerName); + sender.sendMessage(Locale.get(Msg.CMD_HEADER_INSPECT) + " " + playerName); // Link String url = HtmlUtils.getInspectUrlWithProtocol(playerName); String message = Locale.get(Msg.CMD_INFO_LINK).toString(); diff --git a/Plan/src/main/java/com/djrapitops/plan/command/commands/QuickInspectCommand.java b/Plan/src/main/java/com/djrapitops/plan/command/commands/QuickInspectCommand.java index de8302ade..db2e36113 100644 --- a/Plan/src/main/java/com/djrapitops/plan/command/commands/QuickInspectCommand.java +++ b/Plan/src/main/java/com/djrapitops/plan/command/commands/QuickInspectCommand.java @@ -90,9 +90,9 @@ public class QuickInspectCommand extends SubCommand { public void run() { timesrun++; if (inspectCache.isCached(uuid)) { - sender.sendMessage(Locale.get(Msg.CMD_HEADER_INSPECT) + playerName); + sender.sendMessage(Locale.get(Msg.CMD_HEADER_INSPECT) + " " + playerName); sender.sendMessage(TextUI.getInspectMessages(uuid)); - sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER) + ""); + sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString()); this.cancel(); } if (timesrun > 10) { diff --git a/Plan/src/main/java/com/djrapitops/plan/utilities/analysis/MathUtils.java b/Plan/src/main/java/com/djrapitops/plan/utilities/analysis/MathUtils.java index 1f9ce278a..cfc76848e 100644 --- a/Plan/src/main/java/com/djrapitops/plan/utilities/analysis/MathUtils.java +++ b/Plan/src/main/java/com/djrapitops/plan/utilities/analysis/MathUtils.java @@ -152,7 +152,7 @@ public class MathUtils { /** * Gets the biggest Integer in a Collection with Integer as Entry - * If the Collection is empty, it will return 0. + * If the Collection is empty, it will return 1. * * @param values The Collection with Integer as the Entry * @return The biggest Integer @@ -166,7 +166,7 @@ public class MathUtils { /** * Gets the biggest Long in a Collection with Long as Entry - * If the Collection is empty, it will return 0. + * If the Collection is empty, it will return 1. * * @param values The Collection with Long as the Entry * @return The biggest Integer From 256b365980e6c6b101e8f0b0cf2b64b8e32785d0 Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Mon, 21 Aug 2017 19:49:26 +0200 Subject: [PATCH 05/16] Fix Error --- Plan/src/main/java/com/djrapitops/plan/Plan.java | 4 ++-- .../plan/data/listeners/PlanDeathEventListener.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Plan/src/main/java/com/djrapitops/plan/Plan.java b/Plan/src/main/java/com/djrapitops/plan/Plan.java index a7e1774a3..d604a30e5 100644 --- a/Plan/src/main/java/com/djrapitops/plan/Plan.java +++ b/Plan/src/main/java/com/djrapitops/plan/Plan.java @@ -191,7 +191,7 @@ public class Plan extends BukkitPlugin { } Benchmark.start("ServerInfo Registration"); - serverInfoManager = new ServerInfoManager(this); + serverInfoManager = new ServerInfoManager(this); Benchmark.stop("Enable", "ServerInfo Registration"); setupFilter(); // TODO Move to RegisterCommand Constructor @@ -229,7 +229,7 @@ public class Plan extends BukkitPlugin { } } - private final void initColorScheme() { + private void initColorScheme() { try { ChatColor mainColor = ChatColor.getByChar(Settings.COLOR_MAIN.toString().charAt(1)); ChatColor secColor = ChatColor.getByChar(Settings.COLOR_SEC.toString().charAt(1)); 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 b99af1386..c39d443de 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 @@ -100,7 +100,7 @@ public class PlanDeathEventListener implements Listener { Player player = (Player) source; - handler.addToPool(new KillInfo(player.getUniqueId(), time, dead, "Bow")); + plugin.addToProcessQueue(new KillInfo(player.getUniqueId(), time, dead, "Bow")); } } } From 424ee0dffc3cf89e5baa50e9ab5be99cd6dfd84f Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Mon, 21 Aug 2017 19:56:07 +0200 Subject: [PATCH 06/16] Fix Error --- Plan/src/main/java/com/djrapitops/plan/Plan.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Plan/src/main/java/com/djrapitops/plan/Plan.java b/Plan/src/main/java/com/djrapitops/plan/Plan.java index d604a30e5..dabcfdff0 100644 --- a/Plan/src/main/java/com/djrapitops/plan/Plan.java +++ b/Plan/src/main/java/com/djrapitops/plan/Plan.java @@ -458,6 +458,16 @@ public class Plan extends BukkitPlugin { return serverVariableHolder; } + /** + * Used to get the object storing server info + * + * @return ServerInfoManager + * @see ServerInfoManager + */ + public ServerInfoManager getServerInfoManager() { + return serverInfoManager; + } + public ProcessingQueue getProcessingQueue() { return processingQueue; } From 685bac0c57bcb23f9577d10f33bcbc5ef8df2acd Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Mon, 21 Aug 2017 21:39:46 +0200 Subject: [PATCH 07/16] Update toString() --- Plan/src/main/java/com/djrapitops/plan/data/TPS.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Plan/src/main/java/com/djrapitops/plan/data/TPS.java b/Plan/src/main/java/com/djrapitops/plan/data/TPS.java index 88c2839c3..c1f11824a 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/TPS.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/TPS.java @@ -137,6 +137,14 @@ public class TPS { @Override public String toString() { - return "TPS{" + date + "|" + ticksPerSecond + "|" + players + "|" + cpuUsage + "}"; + return "TPS{" + + "date=" + date + + ", ticksPerSecond=" + ticksPerSecond + + ", players=" + players + + ", cpuUsage=" + cpuUsage + + ", usedMemory=" + usedMemory + + ", entityCount=" + entityCount + + ", chunksLoaded=" + chunksLoaded + + '}'; } } From dee25eff4c225068ade0d88b19d672d8ba0afd1e Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Mon, 21 Aug 2017 21:41:44 +0200 Subject: [PATCH 08/16] Update hashCode() and equals() --- .../java/com/djrapitops/plan/data/TPS.java | 39 +++++++------------ 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/Plan/src/main/java/com/djrapitops/plan/data/TPS.java b/Plan/src/main/java/com/djrapitops/plan/data/TPS.java index c1f11824a..f19de2090 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/TPS.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/TPS.java @@ -5,6 +5,8 @@ */ package main.java.com.djrapitops.plan.data; +import com.google.common.base.Objects; + /** * Class containing single datapoint of TPS / Players online / CPU Usage / Used Memory / Entity Count / Chunks loaded. * @@ -106,33 +108,22 @@ public class TPS { } @Override - public int hashCode() { - int hash = 3; - hash = 97 * hash + (int) (this.date ^ (this.date >>> 32)); - hash = 97 * hash + (int) (Double.doubleToLongBits(this.ticksPerSecond) ^ (Double.doubleToLongBits(this.ticksPerSecond) >>> 32)); - hash = 97 * hash + this.players; - return hash; + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + TPS tps = (TPS) o; + return date == tps.date && + Double.compare(tps.ticksPerSecond, ticksPerSecond) == 0 && + players == tps.players && + Double.compare(tps.cpuUsage, cpuUsage) == 0 && + usedMemory == tps.usedMemory && + entityCount == tps.entityCount && + chunksLoaded == tps.chunksLoaded; } @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (obj == null) { - return false; - } - - if (getClass() != obj.getClass()) { - return false; - } - - final TPS other = (TPS) obj; - return date == other.date - && Double.compare(this.ticksPerSecond, other.ticksPerSecond) == 0 - && this.players == other.players - && Double.compare(cpuUsage, other.cpuUsage) == 0; + public int hashCode() { + return Objects.hashCode(date, ticksPerSecond, players, cpuUsage, usedMemory, entityCount, chunksLoaded); } @Override From 82da226edbccef7e480be83a04f8adcb907dbff0 Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Tue, 22 Aug 2017 18:26:59 +0200 Subject: [PATCH 09/16] First try on Connection Pool --- Plan/pom.xml | 16 ++ .../plan/data/handling/DBCommitProcessor.java | 9 +- .../listeners/PlanDeathEventListener.java | 24 ++- .../djrapitops/plan/database/Database.java | 10 +- .../plan/database/databases/MySQLDB.java | 34 ++-- .../plan/database/databases/SQLDB.java | 164 +++++++----------- .../plan/database/databases/SQLiteDB.java | 39 ++--- .../plan/database/tables/ActionsTable.java | 2 + .../plan/database/tables/CommandUseTable.java | 26 ++- .../plan/database/tables/IPsTable.java | 4 + .../plan/database/tables/KillsTable.java | 24 ++- .../plan/database/tables/NicknamesTable.java | 10 +- .../plan/database/tables/SecurityTable.java | 17 +- .../plan/database/tables/ServerTable.java | 7 + .../plan/database/tables/SessionsTable.java | 2 + .../plan/database/tables/TPSTable.java | 8 +- .../plan/database/tables/Table.java | 30 ++-- .../plan/database/tables/UserIDTable.java | 5 + .../plan/database/tables/UsersTable.java | 34 ++-- .../plan/database/tables/VersionTable.java | 6 +- .../plan/database/tables/WorldTable.java | 9 +- .../plan/database/tables/WorldTimesTable.java | 36 ++-- .../plan/data/cache/queue/QueueTest.java | 6 +- .../plan/database/DatabaseCommitTest.java | 22 +-- .../plan/database/DatabaseTest.java | 43 ++--- Plan/test/test/java/utils/TestInit.java | 7 +- 26 files changed, 289 insertions(+), 305 deletions(-) diff --git a/Plan/pom.xml b/Plan/pom.xml index 01beedcec..2a4e02cc3 100644 --- a/Plan/pom.xml +++ b/Plan/pom.xml @@ -31,6 +31,22 @@ 2.0.4 compile + + + org.apache.commons + commons-dbcp2 + 2.1.1 + + + org.apache.commons + commons-pool2 + 2.4.2 + + + commons-logging + commons-logging + 1.2 + com.djrapitops diff --git a/Plan/src/main/java/com/djrapitops/plan/data/handling/DBCommitProcessor.java b/Plan/src/main/java/com/djrapitops/plan/data/handling/DBCommitProcessor.java index 55a294f25..7cd0e6aa1 100644 --- a/Plan/src/main/java/com/djrapitops/plan/data/handling/DBCommitProcessor.java +++ b/Plan/src/main/java/com/djrapitops/plan/data/handling/DBCommitProcessor.java @@ -4,12 +4,9 @@ */ package main.java.com.djrapitops.plan.data.handling; -import main.java.com.djrapitops.plan.Log; import main.java.com.djrapitops.plan.database.Database; import main.java.com.djrapitops.plan.queue.processing.Processor; -import java.sql.SQLException; - /** * Processor for queueing a Database Commit after changes. * @@ -23,10 +20,10 @@ public class DBCommitProcessor extends Processor { @Override public void process() { // TODO Prevent Commit during batch operations. - try { - object.commit(); + /*try { + TODO FIX object.commit(); } catch (SQLException e) { Log.toLog(this.getClass().getName(), e); - } + }*/ } } \ No newline at end of file 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 c39d443de..679d6658a 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 @@ -1,10 +1,10 @@ package main.java.com.djrapitops.plan.data.listeners; import main.java.com.djrapitops.plan.Plan; -import main.java.com.djrapitops.plan.data.handling.KillHandling; -import main.java.com.djrapitops.plan.data.handling.info.DeathInfo; -import main.java.com.djrapitops.plan.data.handling.info.KillInfo; +import main.java.com.djrapitops.plan.data.handling.player.DeathProcessor; +import main.java.com.djrapitops.plan.data.handling.player.KillProcessor; import main.java.com.djrapitops.plan.utilities.MiscUtils; +import org.apache.commons.lang3.text.WordUtils; import org.bukkit.Material; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; @@ -45,7 +45,7 @@ public class PlanDeathEventListener implements Listener { LivingEntity dead = event.getEntity(); if (dead instanceof Player) { - plugin.addToProcessQueue(new DeathInfo(dead.getUniqueId())); + plugin.addToProcessQueue(new DeathProcessor(dead.getUniqueId())); } EntityDamageEvent entityDamageEvent = dead.getLastDamageCause(); @@ -69,7 +69,7 @@ public class PlanDeathEventListener implements Listener { } } - plugin.addToProcessQueue(new KillInfo(killer.getUniqueId(), time, dead, KillHandling.normalizeMaterialName(itemInHand))); + plugin.addToProcessQueue(new KillProcessor(killer.getUniqueId(), time, dead, normalizeMaterialName(itemInHand))); return; } @@ -86,7 +86,7 @@ public class PlanDeathEventListener implements Listener { return; } - plugin.addToProcessQueue(new KillInfo(owner.getUniqueId(), time, dead, "Wolf")); + plugin.addToProcessQueue(new KillProcessor(owner.getUniqueId(), time, dead, "Wolf")); } if (killerEntity instanceof Arrow) { @@ -100,8 +100,18 @@ public class PlanDeathEventListener implements Listener { Player player = (Player) source; - plugin.addToProcessQueue(new KillInfo(player.getUniqueId(), time, dead, "Bow")); + plugin.addToProcessQueue(new KillProcessor(player.getUniqueId(), time, dead, "Bow")); } } + + /** + * Normalizes a material name + * + * @param material The material + * @return The normalized material name + */ + private String normalizeMaterialName(Material material) { + return WordUtils.capitalizeFully(material.name(), '_').replace('_', ' '); + } } 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 1ef398c23..5b10dd9c3 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/Database.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/Database.java @@ -3,7 +3,9 @@ package main.java.com.djrapitops.plan.database; import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.data.UserData; import main.java.com.djrapitops.plan.database.tables.*; +import org.apache.commons.dbcp2.BasicDataSource; +import java.sql.Connection; import java.sql.SQLException; import java.util.*; @@ -90,6 +92,8 @@ public abstract class Database { */ protected ServerTable serverTable; + protected BasicDataSource dataSource; + /** * Super constructor. * @@ -322,5 +326,9 @@ public abstract class Database { return serverTable; } - public abstract void commit() throws SQLException; + public BasicDataSource getDataSource() { + return dataSource; + } + + public abstract void commit(Connection connection) throws SQLException; } 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 a5c36c687..d942b1e7e 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 @@ -1,15 +1,9 @@ package main.java.com.djrapitops.plan.database.databases; -import main.java.com.djrapitops.plan.Log; import main.java.com.djrapitops.plan.Plan; -import main.java.com.djrapitops.plan.locale.Locale; -import main.java.com.djrapitops.plan.locale.Msg; +import org.apache.commons.dbcp2.BasicDataSource; import org.bukkit.configuration.file.FileConfiguration; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - /** * @author Rsl1122 */ @@ -25,30 +19,26 @@ public class MySQLDB extends SQLDB { } /** - * Creates a new connection to the database. - * - * @return the new Connection. + * Setups the {@link BasicDataSource} */ @Override - public Connection getNewConnection() { + public void setupDataSource() { FileConfiguration config = plugin.getConfig(); - try { - Class.forName("com.mysql.jdbc.Driver"); + dataSource = new BasicDataSource(); + dataSource.setDriverClassName("com.mysql.jdbc.Driver"); - String url = "jdbc:mysql://" + config.getString("mysql.host") + ":" + config.getString("mysql.port") + "/" - + config.getString("mysql.database") - + "?rewriteBatchedStatements=true"; + dataSource.setUrl("jdbc:mysql://" + config.getString("Database.MySQL.Host") + ":" + config.getString("Database.MySQL.Port") + "/" + + config.getString("Database.MySQL.Database") + + "?rewriteBatchedStatements=true"); - return DriverManager.getConnection(url, config.getString("mysql.user"), config.getString("mysql.password")); - } catch (ClassNotFoundException | SQLException e) { - Log.error(Locale.get(Msg.ENABLE_FAIL_DB).parse(getConfigName(), e.getMessage())); - return null; - } + dataSource.setUsername(config.getString("Database.MySQL.User")); + dataSource.setPassword(config.getString("Database.MySQL.Password")); + dataSource.setMaxTotal(-1); } /** - * @return + * @return the name of the Database */ @Override public String getName() { 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 d28ef4dbb..6d8228d8e 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 @@ -1,13 +1,12 @@ package main.java.com.djrapitops.plan.database.databases; -import com.djrapitops.plugin.task.AbsRunnable; import main.java.com.djrapitops.plan.Log; import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.data.UserData; import main.java.com.djrapitops.plan.database.Database; import main.java.com.djrapitops.plan.database.tables.*; import main.java.com.djrapitops.plan.utilities.Benchmark; -import main.java.com.djrapitops.plan.utilities.MiscUtils; +import org.apache.commons.dbcp2.BasicDataSource; import java.sql.Connection; import java.sql.SQLException; @@ -26,8 +25,6 @@ public abstract class SQLDB extends Database { private final boolean supportsModification; private final boolean usingMySQL; - private Connection connection; - /** * @param plugin * @param supportsModification @@ -37,7 +34,6 @@ public abstract class SQLDB extends Database { this.supportsModification = supportsModification; usingMySQL = getName().equals("MySQL"); - serverTable = new ServerTable(this, usingMySQL); usersTable = new UsersTable(this, usingMySQL); sessionsTable = new SessionsTable(this, usingMySQL); killsTable = new KillsTable(this, usingMySQL); @@ -49,31 +45,9 @@ public abstract class SQLDB extends Database { securityTable = new SecurityTable(this, usingMySQL); worldTable = new WorldTable(this, usingMySQL); worldTimesTable = new WorldTimesTable(this, usingMySQL); + serverTable = new ServerTable(this, usingMySQL); - startConnectionPingTask(); - } - - /** - * Starts repeating Async task that maintains the Database connection. - */ - public void startConnectionPingTask() { - // Maintains Connection. - plugin.getRunnableFactory().createNew(new AbsRunnable("DBConnectionPingTask " + getName()) { - @Override - public void run() { - Statement statement = null; - try { - if (connection != null && !connection.isClosed()) { - statement = connection.createStatement(); - statement.execute("/* ping */ SELECT 1"); - } - } catch (SQLException e) { - connection = getNewConnection(); - } finally { - MiscUtils.close(statement); - } - } - }).runTaskTimerAsynchronously(60L * 20L, 60L * 20L); + setupDataSource(); } /** @@ -93,9 +67,11 @@ public abstract class SQLDB extends Database { String benchName = "Init " + getConfigName(); Benchmark.start(benchName); try { - if (!checkConnection()) { + System.out.println("SETUP DATABASES"); + if (!setupDatabases()) { return false; } + System.out.println("CLEAN DATABASES"); clean(); return true; } catch (SQLException e) { @@ -115,37 +91,29 @@ public abstract class SQLDB extends Database { * @return Is the connection usable? * @throws SQLException */ - public boolean checkConnection() throws SQLException { - if (connection == null || connection.isClosed()) { - connection = getNewConnection(); + public boolean setupDatabases() throws SQLException { + boolean newDatabase = isNewDatabase(); - if (connection == null || connection.isClosed()) { - return false; - } + if (!versionTable.createTable()) { + Log.error("Failed to create table: " + versionTable.getTableName()); + return false; + } - boolean newDatabase = isNewDatabase(); + if (newDatabase) { + Log.info("New Database created."); + } - if (!versionTable.createTable()) { - Log.error("Failed to create table: " + versionTable.getTableName()); - return false; - } + if (!createTables()) { + return false; + } - if (newDatabase) { - Log.info("New Database created."); - setVersion(8); - } + if (newDatabase || getVersion() < 8) { + setVersion(8); + } - if (!createTables()) { - return false; - } - - if (!newDatabase && getVersion() < 8) { - setVersion(8); - } - - try (Statement statement = connection.createStatement()) { - statement.execute("DROP TABLE IF EXISTS plan_locations"); - } + try (Statement statement = getConnection().createStatement()) { + statement.execute("DROP TABLE IF EXISTS plan_locations"); + endTransaction(statement.getConnection()); } return true; } @@ -158,8 +126,10 @@ public abstract class SQLDB extends Database { * @return true if successful. */ private boolean createTables() { + System.out.println("Create Tables"); Benchmark.start("Create tables"); for (Table table : getAllTables()) { + System.out.println("Create Table " + table.getTableName()); if (!table.createTable()) { Log.error("Failed to create table: " + table.getTableName()); return false; @@ -188,7 +158,6 @@ public abstract class SQLDB extends Database { commandUseTable, tpsTable, worldTable, worldTimesTable, securityTable}; } - /** * @return */ @@ -201,18 +170,19 @@ public abstract class SQLDB extends Database { } /** - * @return + * Setups the {@link BasicDataSource} */ - public abstract Connection getNewConnection(); + public abstract void setupDataSource(); /** * @throws SQLException */ @Override public void close() throws SQLException { - if (connection != null) { - connection.close(); - } + /*if (!dataSource.isClosed()) { + dataSource.close(); + }*/ + setStatus("Closed"); Log.logDebug("Database"); // Log remaining Debug info if present } @@ -232,7 +202,6 @@ public abstract class SQLDB extends Database { @Override public void setVersion(int version) throws SQLException { versionTable.setVersion(version); - commit(); } /** @@ -268,25 +237,19 @@ public abstract class SQLDB extends Database { Benchmark.start("Remove Account"); Log.debug("Database", "Removing Account: " + uuid); try { - checkConnection(); + setupDatabases(); } catch (Exception e) { Log.toLog(this.getClass().getName(), e); return false; } int userId = usersTable.getUserId(uuid); - boolean success = userId != -1 + return userId != -1 && ipsTable.removeUserIPs(userId) && nicknamesTable.removeUserNicknames(userId) && sessionsTable.removeUserSessions(userId) && killsTable.removeUserKillsAndVictims(userId) && worldTimesTable.removeUserWorldTimes(userId) && usersTable.removeUser(uuid); - if (success) { - commit(); - } else { - rollback(); - } - return success; } finally { Benchmark.stop("Database", "Remove Account"); setAvailable(); @@ -300,7 +263,7 @@ public abstract class SQLDB extends Database { public void clean() { Log.info("Cleaning the database."); try { - checkConnection(); + setupDatabases(); tpsTable.clean(); Log.info("Clean complete."); } catch (SQLException e) { @@ -313,25 +276,19 @@ public abstract class SQLDB extends Database { */ @Override public boolean removeAllData() { - boolean success = true; - setStatus("Clearing all data"); try { + setStatus("Clearing all data"); + for (Table table : getAllTablesInRemoveOrder()) { if (!table.removeAllData()) { - success = false; - break; + return false; } } - if (success) { - commit(); - } else { - rollback(); // TODO Tests for this case - } - } catch (SQLException e) { - Log.toLog(this.getClass().getName(), e); + + return true; + } finally { + setAvailable(); } - setAvailable(); - return success; } @Override @@ -354,6 +311,7 @@ public abstract class SQLDB extends Database { if (data.isEmpty()) { return data; } + // TODO REWRITE Benchmark.stop("Database", "Get UserData for " + uuidsCol.size()); @@ -368,13 +326,6 @@ public abstract class SQLDB extends Database { return supportsModification; } - /** - * @return - */ - public Connection getConnection() { - return connection; - } - private void setStatus(String status) { Log.debug("Database", status); } @@ -383,14 +334,23 @@ public abstract class SQLDB extends Database { Log.logDebug("Database"); } + public Connection getConnection() throws SQLException { + return dataSource.getConnection(); + } + /** * Commits changes to the .db file when using SQLite Database. *

* MySQL has Auto Commit enabled. */ - public void commit() throws SQLException { - if (!usingMySQL) { - getConnection().commit(); + @Override + public void commit(Connection connection) throws SQLException { + try { + if (!usingMySQL) { + connection.commit(); + } + } finally { + endTransaction(connection); } } @@ -399,9 +359,17 @@ public abstract class SQLDB extends Database { *

* MySQL has Auto Commit enabled. */ - public void rollback() throws SQLException { - if (!usingMySQL) { - connection.rollback(); + public void rollback(Connection connection) throws SQLException { + try { + if (!usingMySQL) { + connection.rollback(); + } + } finally { + endTransaction(connection); } } + + public void endTransaction(Connection connection) throws SQLException { + connection.close(); + } } 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 0c5e41490..f76b5d430 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 @@ -1,11 +1,10 @@ package main.java.com.djrapitops.plan.database.databases; import main.java.com.djrapitops.plan.Plan; +import org.apache.commons.dbcp2.BasicDataSource; import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; +import java.util.Collections; /** * @author Rsl1122 @@ -33,36 +32,26 @@ public class SQLiteDB extends SQLDB { } /** - * Creates a new connection to the database. - * - * @return the new Connection. + * Setups the {@link BasicDataSource} */ @Override - public Connection getNewConnection() { - return getNewConnection(dbName); + public void setupDataSource() { + dataSource = new BasicDataSource(); + + dataSource.setUrl("jdbc:sqlite:" + new File(plugin.getDataFolder(), dbName + ".db").getAbsolutePath()); + + dataSource.setEnableAutoCommitOnReturn(false); + dataSource.setDefaultAutoCommit(false); + + dataSource.setConnectionInitSqls(Collections.singletonList("PRAGMA JOURNAL_MODE=WAL")); } /** - * @param dbName - * @return - */ - public Connection getNewConnection(String dbName) { - try { - Class.forName("org.sqlite.JDBC"); - - Connection connection = DriverManager.getConnection("jdbc:sqlite:" + new File(plugin.getDataFolder(), dbName + ".db").getAbsolutePath()); - connection.setAutoCommit(false); - return connection; - } catch (ClassNotFoundException | SQLException e) { - return null; - } - } - - /** - * @return + * @return the name of the Database */ @Override public String getName() { return "SQLite"; } + } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/ActionsTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/ActionsTable.java index dfeed963c..8d872c25e 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/ActionsTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/ActionsTable.java @@ -87,6 +87,7 @@ public class ActionsTable extends UserIDTable { statement.setString(5, action.getAdditionalInfo()); statement.execute(); } finally { + endTransaction(statement); close(statement); } } @@ -117,6 +118,7 @@ public class ActionsTable extends UserIDTable { } return actions; } finally { + endTransaction(statement); close(set, statement); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/CommandUseTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/CommandUseTable.java index 6d615fe26..af580bb0a 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/CommandUseTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/CommandUseTable.java @@ -101,8 +101,8 @@ public class CommandUseTable extends Table { } return commandUse; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); Benchmark.stop("Database", "Get CommandUse"); } } @@ -136,7 +136,6 @@ public class CommandUseTable extends Table { } updateCommands(updateData); - commit(); Benchmark.stop("Database", "Save Commanduse"); db.setAvailable(); } @@ -149,7 +148,7 @@ public class CommandUseTable extends Table { "WHERE (" + columnCommand + "=?) AND (" + columnServerID + "=" + serverTable.statementSelectServerID + ")"; statement = prepareStatement(updateStatement); - boolean commitRequired = false; + for (Map.Entry entrySet : data.entrySet()) { String key = entrySet.getKey(); Integer amount = entrySet.getValue(); @@ -162,13 +161,11 @@ public class CommandUseTable extends Table { statement.setString(2, key); statement.setString(3, Plan.getServerUUID().toString()); statement.addBatch(); - commitRequired = true; } - if (commitRequired) { - statement.executeBatch(); - } + statement.executeBatch(); } finally { + endTransaction(statement); close(statement); } } @@ -182,7 +179,6 @@ public class CommandUseTable extends Table { + columnServerID + ") VALUES (?, ?, " + serverTable.statementSelectServerID + ")"; statement = prepareStatement(insertStatement); - boolean addedRows = false; for (Map.Entry entrySet : data.entrySet()) { String key = entrySet.getKey(); Integer amount = entrySet.getValue(); @@ -195,20 +191,18 @@ public class CommandUseTable extends Table { statement.setInt(2, amount); statement.setString(3, Plan.getServerUUID().toString()); statement.addBatch(); - addedRows = true; } - if (addedRows) { - statement.executeBatch(); - } + statement.executeBatch(); } finally { + endTransaction(statement); close(statement); } } public Optional getCommandByID(int id) throws SQLException { PreparedStatement statement = null; - ResultSet set = null; + ResultSet set; try { statement = prepareStatement(Select.from(tableName, columnCommand).where(columnCommandId + "=?").toString()); statement.setInt(1, id); @@ -218,13 +212,14 @@ public class CommandUseTable extends Table { } return Optional.empty(); } finally { + endTransaction(statement); close(statement); } } public Optional getCommandID(String command) throws SQLException { PreparedStatement statement = null; - ResultSet set = null; + ResultSet set; try { statement = prepareStatement(Select.from(tableName, columnCommandId).where(columnCommand + "=?").toString()); statement.setString(1, command); @@ -234,6 +229,7 @@ public class CommandUseTable extends Table { } return Optional.empty(); } finally { + endTransaction(statement); close(statement); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/IPsTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/IPsTable.java index e80519d09..080a9004e 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/IPsTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/IPsTable.java @@ -91,6 +91,7 @@ public class IPsTable extends UserIDTable { return stringList; } finally { + endTransaction(statement); close(set, statement); } } @@ -100,6 +101,7 @@ public class IPsTable extends UserIDTable { if (ips.contains(ip)) { return; } + insertIp(uuid, ip, geolocation); } @@ -118,6 +120,7 @@ public class IPsTable extends UserIDTable { statement.setString(3, geolocation); statement.execute(); } finally { + endTransaction(statement); close(statement); } } @@ -136,6 +139,7 @@ public class IPsTable extends UserIDTable { } return Optional.empty(); } finally { + endTransaction(statement); close(set, statement); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/KillsTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/KillsTable.java index 34e57c3b3..9b1efd59c 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/KillsTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/KillsTable.java @@ -66,7 +66,9 @@ public class KillsTable extends Table { statement = prepareStatement("DELETE FROM " + tableName + " WHERE " + columnKillerUserID + " = ? OR " + columnVictimUserID + " = ?"); statement.setInt(1, userId); statement.setInt(2, userId); + statement.execute(); + commit(statement.getConnection()); return true; } catch (SQLException ex) { Log.toLog(this.getClass().getName(), ex); @@ -96,8 +98,8 @@ public class KillsTable extends Table { } return killData; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); } } @@ -120,7 +122,6 @@ public class KillsTable extends Table { + columnWeapon + ", " + columnDate + ") VALUES (?, ?, ?, ?)"); - boolean commitRequired = false; for (KillData kill : kills) { if (kill == null) { continue; @@ -130,13 +131,11 @@ public class KillsTable extends Table { statement.setString(3, kill.getWeapon()); statement.setLong(4, kill.getTime()); statement.addBatch(); - commitRequired = true; } - if (commitRequired) { - statement.executeBatch(); - } + statement.executeBatch(); } finally { + endTransaction(statement); close(statement); Benchmark.stop("Database", "Save Kills"); } @@ -172,8 +171,8 @@ public class KillsTable extends Table { } return kills; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); Benchmark.stop("Database", "Get Kills multiple"); } } @@ -199,7 +198,6 @@ public class KillsTable extends Table { + columnWeapon + ", " + columnDate + ") VALUES (?, ?, ?, ?)"); - boolean commitRequired = false; for (Map.Entry> entrySet : kills.entrySet()) { Integer id = entrySet.getKey(); List playerKills = entrySet.getValue(); @@ -216,14 +214,12 @@ public class KillsTable extends Table { statement.setString(3, kill.getWeapon()); statement.setLong(4, kill.getTime()); statement.addBatch(); - commitRequired = true; } - if (commitRequired) { - statement.executeBatch(); - } + statement.executeBatch(); } } finally { + endTransaction(statement); close(statement); Benchmark.stop("Database", "Save Kills multiple"); } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/NicknamesTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/NicknamesTable.java index 3b5b230f9..951fe4ee1 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/NicknamesTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/NicknamesTable.java @@ -99,6 +99,7 @@ public class NicknamesTable extends UserIDTable { return nicknames; } finally { + endTransaction(statement); close(set, statement); } } @@ -136,6 +137,7 @@ public class NicknamesTable extends UserIDTable { statement.executeBatch(); } finally { + endTransaction(statement); close(statement); } } @@ -192,6 +194,7 @@ public class NicknamesTable extends UserIDTable { return nicks; } finally { + endTransaction(statement); close(set, statement); Benchmark.stop("Database", "Get Nicknames Multiple"); } @@ -212,7 +215,6 @@ public class NicknamesTable extends UserIDTable { Map> saved = getNicknames(nicknames.keySet()); PreparedStatement statement = null; try { - boolean commitRequired = false; statement = prepareStatement("INSERT INTO " + tableName + " (" + columnUserID + ", " + columnCurrent + ", " @@ -239,14 +241,12 @@ public class NicknamesTable extends UserIDTable { statement.setInt(2, (name.equals(lastNick)) ? 1 : 0); statement.setString(3, name); statement.addBatch(); - commitRequired = true; } } - if (commitRequired) { - statement.executeBatch(); - } + statement.executeBatch(); } finally { + endTransaction(statement); close(statement); Benchmark.stop("Database", "Save Nicknames Multiple"); } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/SecurityTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/SecurityTable.java index ee3acf084..d909b8c89 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/SecurityTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/SecurityTable.java @@ -60,6 +60,12 @@ public class SecurityTable extends Table { Log.toLog(this.getClass().getName(), ex); return false; } finally { + try { + endTransaction(statement); + } catch (SQLException e) { + Log.toLog(this.getClass().getName(), e); + } + close(statement); } } @@ -80,7 +86,8 @@ public class SecurityTable extends Table { statement.setString(2, saltPassHash); statement.setInt(3, permLevel); statement.execute(); - commit(); + + commit(statement.getConnection()); } finally { close(statement); } @@ -104,8 +111,8 @@ public class SecurityTable extends Table { } return null; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); } } @@ -125,8 +132,8 @@ public class SecurityTable extends Table { } return list; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); } } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/ServerTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/ServerTable.java index f27652f63..fd1cc5186 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/ServerTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/ServerTable.java @@ -92,6 +92,7 @@ public class ServerTable extends Table { statement.setInt(5, info.getId()); statement.executeUpdate(); } finally { + endTransaction(statement); close(statement); } } @@ -122,6 +123,7 @@ public class ServerTable extends Table { statement.setBoolean(4, true); statement.execute(); } finally { + endTransaction(statement); close(statement); } } @@ -149,6 +151,7 @@ public class ServerTable extends Table { return Optional.empty(); } } finally { + endTransaction(statement); close(set, statement); } } @@ -176,6 +179,7 @@ public class ServerTable extends Table { return Optional.empty(); } } finally { + endTransaction(statement); close(set, statement); } } @@ -195,6 +199,7 @@ public class ServerTable extends Table { } return names; } finally { + endTransaction(statement); close(set, statement); } } @@ -224,6 +229,7 @@ public class ServerTable extends Table { return Optional.empty(); } } finally { + endTransaction(statement); close(set, statement); } } @@ -247,6 +253,7 @@ public class ServerTable extends Table { } return servers; } finally { + endTransaction(statement); close(set, statement); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/SessionsTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/SessionsTable.java index cc5c01536..5e291bc3e 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/SessionsTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/SessionsTable.java @@ -101,6 +101,7 @@ public class SessionsTable extends UserIDTable { statement.setString(6, Plan.getServerUUID().toString()); statement.execute(); } finally { + endTransaction(statement); close(statement); } @@ -132,6 +133,7 @@ public class SessionsTable extends UserIDTable { } return sessionsByServer; } finally { + endTransaction(statement); close(set, statement); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/TPSTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/TPSTable.java index 47647ef12..e6a82802b 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/TPSTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/TPSTable.java @@ -111,8 +111,8 @@ public class TPSTable extends Table { } return data; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); Benchmark.stop("Database", "Get TPS"); } } @@ -131,7 +131,6 @@ public class TPSTable extends Table { } }); db.setAvailable(); - commit(); } private void saveTPSBatch(List batch) throws SQLException { @@ -161,7 +160,9 @@ public class TPSTable extends Table { statement.setDouble(7, tps.getChunksLoaded()); statement.addBatch(); } + statement.executeBatch(); + commit(statement.getConnection()); } finally { close(statement); } @@ -179,6 +180,7 @@ public class TPSTable extends Table { statement.setLong(1, MiscUtils.getTime() - fiveWeeks); statement.execute(); } finally { + endTransaction(statement); close(statement); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/Table.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/Table.java index 15c185760..c54b0996f 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/Table.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/Table.java @@ -54,11 +54,7 @@ public abstract class Table { * @return @throws SQLException */ protected Connection getConnection() throws SQLException { - Connection connection = db.getConnection(); - if (connection == null || connection.isClosed()) { - connection = db.getNewConnection(); - } - return connection; + return db.getConnection(); } /** @@ -78,11 +74,11 @@ public abstract class Table { Statement statement = null; try { statement = connection.createStatement(); - return statement.execute(statementString); + boolean b = statement.execute(statementString); + commit(statement.getConnection()); + return b; } finally { - if (statement != null) { - statement.close(); - } + close(statement); } } @@ -180,7 +176,19 @@ public abstract class Table { * * @throws SQLException If commit fails or there is nothing to commit. */ - protected void commit() throws SQLException { - db.commit(); + protected void commit(Connection connection) throws SQLException { + db.commit(connection); + } + + protected void endTransaction(Connection connection) throws SQLException { + db.endTransaction(connection); + } + + protected void endTransaction(Statement statement) throws SQLException { + if (statement == null) { + return; + } + + endTransaction(statement.getConnection()); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/UserIDTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/UserIDTable.java index ef432747c..4e0c38b65 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/UserIDTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/UserIDTable.java @@ -33,6 +33,11 @@ public abstract class UserIDTable extends Table { Log.toLog(this.getClass().getName(), ex); return false; } finally { + try { + endTransaction(statement); + } catch (SQLException e) { + Log.toLog(this.getClass().getName(), e); + } close(statement); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java index 9219773e9..813777c90 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java @@ -183,8 +183,8 @@ public class UsersTable extends Table { } return userId; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); } } @@ -206,8 +206,8 @@ public class UsersTable extends Table { } return uuid; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); } } @@ -228,8 +228,8 @@ public class UsersTable extends Table { } return uuids; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); Benchmark.stop("Database", "Get Saved UUIDS"); } } @@ -251,11 +251,17 @@ public class UsersTable extends Table { try { statement = prepareStatement("DELETE FROM " + tableName + " WHERE (" + columnUUID + "=?)"); statement.setString(1, uuid); + statement.execute(); return true; } catch (SQLException ex) { return false; } finally { + try { + endTransaction(statement); + } catch (SQLException e) { + Log.toLog(this.getClass().getName(), e); + } close(statement); } } @@ -284,8 +290,8 @@ public class UsersTable extends Table { } } } finally { - close(statement); - close(set); + endTransaction(statement); + close(set, statement); } return containsBukkitData; } @@ -313,8 +319,8 @@ public class UsersTable extends Table { } return ids; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); Benchmark.stop("Database", "Get User IDS Multiple"); } } @@ -337,8 +343,8 @@ public class UsersTable extends Table { } return ids; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); Benchmark.stop("Database", "Get User IDS ALL"); } } @@ -368,8 +374,8 @@ public class UsersTable extends Table { } return null; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/VersionTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/VersionTable.java index c726a5781..5ed358e0d 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/VersionTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/VersionTable.java @@ -56,8 +56,8 @@ public class VersionTable extends Table { Log.debug("Database", "DB Schema version: " + version); return version; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); } } @@ -71,9 +71,9 @@ public class VersionTable extends Table { try { statement = prepareStatement("INSERT INTO " + tableName + " (version) VALUES (" + version + ")"); statement.executeUpdate(); + commit(statement.getConnection()); } finally { close(statement); } } - } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/WorldTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/WorldTable.java index b96ec2623..dbb2bbf15 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/WorldTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/WorldTable.java @@ -75,6 +75,7 @@ public class WorldTable extends Table { } return worldNames; } finally { + endTransaction(statement); close(set, statement); } } @@ -101,16 +102,14 @@ public class WorldTable extends Table { statement = prepareStatement("INSERT INTO " + tableName + " (" + columnWorldName + ") VALUES (?)"); - boolean commitRequired = false; for (String world : worlds) { statement.setString(1, world); statement.addBatch(); - commitRequired = true; - } - if (commitRequired) { - statement.executeBatch(); } + + statement.executeBatch(); } finally { + endTransaction(statement); close(statement); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/WorldTimesTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/WorldTimesTable.java index 205856b20..41bb37254 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/WorldTimesTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/WorldTimesTable.java @@ -95,8 +95,8 @@ public class WorldTimesTable extends UserIDTable { } return times; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); } } @@ -125,8 +125,8 @@ public class WorldTimesTable extends UserIDTable { } return times; } finally { - close(set); - close(statement); + endTransaction(statement); + close(set, statement); } } @@ -167,7 +167,6 @@ public class WorldTimesTable extends UserIDTable { " WHERE (" + selectWorldIDsql + "=" + columnWorldId + ")" + " AND (" + columnUserID + "=?)" ); - boolean commitRequired = false; for (Map.Entry entry : updateData.entrySet()) { String worldName = entry.getKey(); long time = entry.getValue(); @@ -175,12 +174,10 @@ public class WorldTimesTable extends UserIDTable { statement.setString(2, worldName); statement.setInt(3, userId); statement.addBatch(); - commitRequired = true; - } - if (commitRequired) { - statement.executeBatch(); } + statement.executeBatch(); } finally { + endTransaction(statement); close(statement); } } @@ -198,7 +195,6 @@ public class WorldTimesTable extends UserIDTable { + columnPlaytime + ") VALUES (?, " + selectWorldIDsql + ", ?)" ); - boolean commitRequired = false; for (Map.Entry entry : newData.entrySet()) { String worldName = entry.getKey(); long time = entry.getValue(); @@ -206,12 +202,10 @@ public class WorldTimesTable extends UserIDTable { statement.setString(2, worldName); statement.setLong(3, time); statement.addBatch(); - commitRequired = true; - } - if (commitRequired) { - statement.executeBatch(); } + statement.executeBatch(); } finally { + endTransaction(statement); close(statement); } } @@ -259,7 +253,6 @@ public class WorldTimesTable extends UserIDTable { " WHERE (" + selectWorldIDsql + "=" + columnWorldId + ")" + " AND (" + columnUserID + "=?)" ); - boolean commitRequired = false; for (Map.Entry> entry : updateData.entrySet()) { int userId = entry.getKey(); for (Map.Entry times : entry.getValue().entrySet()) { @@ -269,13 +262,11 @@ public class WorldTimesTable extends UserIDTable { statement.setString(2, worldName); statement.setInt(3, userId); statement.addBatch(); - commitRequired = true; } } - if (commitRequired) { - statement.executeBatch(); - } + statement.executeBatch(); } finally { + endTransaction(statement); close(statement); } } @@ -293,7 +284,6 @@ public class WorldTimesTable extends UserIDTable { + columnPlaytime + ") VALUES (?, " + selectWorldIDsql + ", ?)" ); - boolean commitRequired = false; for (Map.Entry> entry : newData.entrySet()) { int userId = entry.getKey(); for (Map.Entry times : entry.getValue().entrySet()) { @@ -303,13 +293,11 @@ public class WorldTimesTable extends UserIDTable { statement.setString(2, worldName); statement.setLong(3, time); statement.addBatch(); - commitRequired = true; } } - if (commitRequired) { - statement.executeBatch(); - } + statement.executeBatch(); } finally { + endTransaction(statement); close(statement); } } diff --git a/Plan/test/test/java/main/java/com/djrapitops/plan/data/cache/queue/QueueTest.java b/Plan/test/test/java/main/java/com/djrapitops/plan/data/cache/queue/QueueTest.java index bba6bf792..b4acc8faf 100644 --- a/Plan/test/test/java/main/java/com/djrapitops/plan/data/cache/queue/QueueTest.java +++ b/Plan/test/test/java/main/java/com/djrapitops/plan/data/cache/queue/QueueTest.java @@ -44,11 +44,7 @@ public class QueueTest { public void setUp() throws Exception { TestInit t = TestInit.init(); Plan plan = t.getPlanMock(); - db = new SQLiteDB(plan, "debug" + MiscUtils.getTime()) { - @Override - public void startConnectionPingTask() { - } - }; + db = new SQLiteDB(plan, "debug" + MiscUtils.getTime()); db.init(); when(plan.getDB()).thenReturn(db); dataCache = new DataCache(plan) { diff --git a/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseCommitTest.java b/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseCommitTest.java index 1a78e40ce..266150ebc 100644 --- a/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseCommitTest.java +++ b/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseCommitTest.java @@ -3,7 +3,6 @@ package test.java.main.java.com.djrapitops.plan.database; import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.data.TPS; import main.java.com.djrapitops.plan.data.WebUser; -import main.java.com.djrapitops.plan.database.Database; import main.java.com.djrapitops.plan.database.databases.SQLiteDB; import main.java.com.djrapitops.plan.utilities.MiscUtils; import main.java.com.djrapitops.plan.utilities.PassEncryptUtil; @@ -21,6 +20,7 @@ import test.java.utils.TestInit; import java.io.File; import java.io.IOException; +import java.sql.Connection; import java.sql.SQLException; import java.util.HashMap; import java.util.List; @@ -34,21 +34,18 @@ import static org.junit.Assert.assertTrue; public class DatabaseCommitTest { private Plan plan; - private Database db; + private SQLiteDB db; private int rows; @Before public void setUp() throws Exception { TestInit t = TestInit.init(); plan = t.getPlanMock(); - db = new SQLiteDB(plan, "debug" + MiscUtils.getTime()) { - @Override - public void startConnectionPingTask() { - - } - }; + db = new SQLiteDB(plan, "debug" + MiscUtils.getTime()); File f = new File(plan.getDataFolder(), "Errors.txt"); rows = FileUtil.lines(f).size(); + + db.init(); } /** @@ -72,9 +69,12 @@ public class DatabaseCommitTest { @Test public void testNoExceptionWhenCommitEmpty() throws SQLException { db.init(); - db.commit(); - db.commit(); - db.commit(); + + Connection con = db.getConnection(); + + db.commit(con); + db.commit(con); + db.commit(con); } @Ignore("//TODO") diff --git a/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java b/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java index 7094fb8f1..8d4af3d73 100644 --- a/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java +++ b/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java @@ -61,14 +61,11 @@ public class DatabaseTest { public void setUp() throws Exception { TestInit t = TestInit.init(); plan = t.getPlanMock(); - db = new SQLiteDB(plan, "debug" + MiscUtils.getTime()) { - @Override - public void startConnectionPingTask() { - - } - }; + db = new SQLiteDB(plan, "debug" + MiscUtils.getTime()); File f = new File(plan.getDataFolder(), "Errors.txt"); rows = FileUtil.lines(f).size(); + + db.init(); } /** @@ -122,12 +119,7 @@ public class DatabaseTest { */ @Test public void testMysqlGetConfigName() { - assertEquals("mysql", new MySQLDB(plan) { - @Override - public void startConnectionPingTask() { - - } - }.getConfigName()); + assertEquals("mysql", new MySQLDB(plan).getConfigName()); } /** @@ -135,12 +127,7 @@ public class DatabaseTest { */ @Test public void testMysqlGetName() { - assertEquals("MySQL", new MySQLDB(plan) { - @Override - public void startConnectionPingTask() { - - } - }.getName()); + assertEquals("MySQL", new MySQLDB(plan).getName()); } /** @@ -149,9 +136,9 @@ public class DatabaseTest { @Ignore("") @Test // TODO Rewrite public void testRemoveAll() throws SQLException { - db.init(); -// UserData data = MockUtils.mockUser(); -// db.saveUserData(data); + //db.init(); + //UserData data = MockUtils.mockUser(); + //db.saveUserData(data); HashMap c = new HashMap<>(); c.put("/plan", 1); c.put("/tp", 4); @@ -170,7 +157,7 @@ public class DatabaseTest { @Ignore("//TODO") @Test public void testSaveCommandUse() throws SQLException { - db.init(); + //db.init(); HashMap c = new HashMap<>(); c.put("/plan", 1); c.put("/tp", 4); @@ -195,11 +182,13 @@ public class DatabaseTest { */ @Test // TODO Rewrite public void testRemove() throws SQLException { + /* db.init(); -// UserData data = MockUtils.mockUser(); -// db.saveUserData(data); -// assertTrue(db.removeAccount(data.getUuid().toString())); -// assertTrue("Contains the user", !db.wasSeenBefore(data.getUuid())); + UserData data = MockUtils.mockUser(); + db.saveUserData(data); + assertTrue(db.removeAccount(data.getUuid().toString())); + assertTrue("Contains the user", !db.wasSeenBefore(data.getUuid())); + */ } /** @@ -222,7 +211,7 @@ public class DatabaseTest { @Test public void testTPSSaving() throws SQLException { - db.init(); + //db.init(); TPSTable tpsTable = db.getTpsTable(); List expected = new ArrayList<>(); Random r = new Random(); diff --git a/Plan/test/test/java/utils/TestInit.java b/Plan/test/test/java/utils/TestInit.java index dd23df24e..148a43c60 100644 --- a/Plan/test/test/java/utils/TestInit.java +++ b/Plan/test/test/java/utils/TestInit.java @@ -82,9 +82,9 @@ public class TestInit { when(planMock.getConfig()).thenReturn(config); File testFolder = getTestFolder(); - if (clearOnStart) { + /*if (clearOnStart) { clean(testFolder); - } + }*/ when(planMock.getDataFolder()).thenReturn(testFolder); // Html Files @@ -119,7 +119,7 @@ public class TestInit { } private RunnableFactory mockRunnableFactory() { - RunnableFactory runnableFactory = new RunnableFactory(planMock) { + return new RunnableFactory(planMock) { @Override public IRunnable createNew(String name, final AbsRunnable runnable) { return new IRunnable() { @@ -170,7 +170,6 @@ public class TestInit { }; } }; - return runnableFactory; } private static File getTestFolder() { From 654ff26fb6d9a614db8073033857b4f49a4aab23 Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Tue, 22 Aug 2017 19:44:59 +0200 Subject: [PATCH 10/16] Fixes Clearing of the data, the pool itself --- .../plan/database/databases/SQLDB.java | 6 +-- .../plan/database/databases/SQLiteDB.java | 4 +- .../plan/database/tables/SessionsTable.java | 1 - .../plan/data/time/WorldTimesTest.java | 9 ---- .../plan/database/DatabaseCommitTest.java | 9 ++-- .../plan/database/DatabaseTest.java | 6 +-- Plan/test/test/java/utils/DBTestSuite.java | 47 +++++++++++++++++++ Plan/test/test/java/utils/TestInit.java | 28 ++--------- 8 files changed, 60 insertions(+), 50 deletions(-) create mode 100644 Plan/test/test/java/utils/DBTestSuite.java 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 6d8228d8e..9cc89e2b0 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 @@ -34,6 +34,7 @@ public abstract class SQLDB extends Database { this.supportsModification = supportsModification; usingMySQL = getName().equals("MySQL"); + serverTable = new ServerTable(this, usingMySQL); usersTable = new UsersTable(this, usingMySQL); sessionsTable = new SessionsTable(this, usingMySQL); killsTable = new KillsTable(this, usingMySQL); @@ -45,7 +46,6 @@ public abstract class SQLDB extends Database { securityTable = new SecurityTable(this, usingMySQL); worldTable = new WorldTable(this, usingMySQL); worldTimesTable = new WorldTimesTable(this, usingMySQL); - serverTable = new ServerTable(this, usingMySQL); setupDataSource(); } @@ -67,11 +67,9 @@ public abstract class SQLDB extends Database { String benchName = "Init " + getConfigName(); Benchmark.start(benchName); try { - System.out.println("SETUP DATABASES"); if (!setupDatabases()) { return false; } - System.out.println("CLEAN DATABASES"); clean(); return true; } catch (SQLException e) { @@ -126,10 +124,8 @@ public abstract class SQLDB extends Database { * @return true if successful. */ private boolean createTables() { - System.out.println("Create Tables"); Benchmark.start("Create tables"); for (Table table : getAllTables()) { - System.out.println("Create Table " + table.getTableName()); if (!table.createTable()) { Log.error("Failed to create table: " + table.getTableName()); return false; 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 f76b5d430..a59c2f8ba 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 @@ -38,12 +38,14 @@ public class SQLiteDB extends SQLDB { public void setupDataSource() { dataSource = new BasicDataSource(); - dataSource.setUrl("jdbc:sqlite:" + new File(plugin.getDataFolder(), dbName + ".db").getAbsolutePath()); + String filePath = new File(plugin.getDataFolder(), dbName + ".db").getAbsolutePath(); + dataSource.setUrl("jdbc:sqlite:" + filePath); dataSource.setEnableAutoCommitOnReturn(false); dataSource.setDefaultAutoCommit(false); dataSource.setConnectionInitSqls(Collections.singletonList("PRAGMA JOURNAL_MODE=WAL")); + dataSource.setMaxTotal(-1); } /** diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/SessionsTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/SessionsTable.java index 5e291bc3e..7eb18640a 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/SessionsTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/SessionsTable.java @@ -56,7 +56,6 @@ public class SessionsTable extends UserIDTable { .foreignKey(columnServerID, serverTableName, serverTableID) .primaryKey(usingMySQL, columnSessionID) .toString(); - System.out.println(sql); execute(sql); return true; } catch (SQLException ex) { diff --git a/Plan/test/test/java/main/java/com/djrapitops/plan/data/time/WorldTimesTest.java b/Plan/test/test/java/main/java/com/djrapitops/plan/data/time/WorldTimesTest.java index abdcb4ace..d1b0859a0 100644 --- a/Plan/test/test/java/main/java/com/djrapitops/plan/data/time/WorldTimesTest.java +++ b/Plan/test/test/java/main/java/com/djrapitops/plan/data/time/WorldTimesTest.java @@ -29,14 +29,12 @@ public class WorldTimesTest { public void setUp() throws Exception { test = new WorldTimes(worldOne, gms[0]); time = test.getGMTimes(worldOne).getLastStateChange(); - System.out.println(test); } @Test public void testWorldChange() { long changeTime = time + 1000L; test.updateState(worldTwo, gms[0], changeTime); - System.out.println(test); assertEquals(1000L, (long) test.getWorldPlaytime(worldOne)); assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0])); } @@ -45,7 +43,6 @@ public class WorldTimesTest { public void testGMChange() { long changeTime = time + 1000L; test.updateState(worldOne, gms[0], changeTime); - System.out.println(test); assertEquals(1000L, (long) test.getWorldPlaytime(worldOne)); assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0])); } @@ -55,11 +52,9 @@ public class WorldTimesTest { long changeTime = time + 1000L; long changeTime2 = changeTime + 1000L; test.updateState(worldTwo, gms[2], changeTime); - System.out.println(test); assertEquals(1000L, (long) test.getWorldPlaytime(worldOne)); assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0])); test.updateState(worldOne, gms[1], changeTime2); - System.out.println(test); assertEquals(1000L, (long) test.getWorldPlaytime(worldOne)); assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0])); assertEquals(1000L, test.getGMTimes(worldTwo).getTime(gms[2])); @@ -98,7 +93,6 @@ public class WorldTimesTest { long time1 = test.getWorldPlaytime(worldOne); long time2 = test.getWorldPlaytime(worldTwo); - System.out.println(test); // Tests World time calculation. assertEquals(amount * 50, time1 + time2); @@ -156,13 +150,10 @@ public class WorldTimesTest { // No change should occur. test.updateState(worldOne, "ADVENTURE", time + 5000L); - System.out.println(test); assertEquals(1000L, worldOneGMTimes.getTime("ADVENTURE")); assertEquals(1000L, worldTwoGMTimes.getTime("CREATIVE")); test.updateState(worldTwo, "CREATIVE", time + 5000L); - System.out.println(test); test.updateState(worldOne, "ADVENTURE", time + 6000L); - System.out.println(test); assertEquals(1000L, worldOneGMTimes.getTime("ADVENTURE")); assertEquals(2000L, worldTwoGMTimes.getTime("CREATIVE")); diff --git a/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseCommitTest.java b/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseCommitTest.java index 266150ebc..0911d5fc0 100644 --- a/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseCommitTest.java +++ b/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseCommitTest.java @@ -20,7 +20,6 @@ import test.java.utils.TestInit; import java.io.File; import java.io.IOException; -import java.sql.Connection; import java.sql.SQLException; import java.util.HashMap; import java.util.List; @@ -70,11 +69,9 @@ public class DatabaseCommitTest { public void testNoExceptionWhenCommitEmpty() throws SQLException { db.init(); - Connection con = db.getConnection(); - - db.commit(con); - db.commit(con); - db.commit(con); + db.commit(db.getConnection()); + db.commit(db.getConnection()); + db.commit(db.getConnection()); } @Ignore("//TODO") diff --git a/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java b/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java index 8d4af3d73..d45ad9b5b 100644 --- a/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java +++ b/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java @@ -136,7 +136,7 @@ public class DatabaseTest { @Ignore("") @Test // TODO Rewrite public void testRemoveAll() throws SQLException { - //db.init(); + db.init(); //UserData data = MockUtils.mockUser(); //db.saveUserData(data); HashMap c = new HashMap<>(); @@ -157,7 +157,7 @@ public class DatabaseTest { @Ignore("//TODO") @Test public void testSaveCommandUse() throws SQLException { - //db.init(); + db.init(); HashMap c = new HashMap<>(); c.put("/plan", 1); c.put("/tp", 4); @@ -211,7 +211,7 @@ public class DatabaseTest { @Test public void testTPSSaving() throws SQLException { - //db.init(); + db.init(); TPSTable tpsTable = db.getTpsTable(); List expected = new ArrayList<>(); Random r = new Random(); diff --git a/Plan/test/test/java/utils/DBTestSuite.java b/Plan/test/test/java/utils/DBTestSuite.java new file mode 100644 index 000000000..1fb12b1c6 --- /dev/null +++ b/Plan/test/test/java/utils/DBTestSuite.java @@ -0,0 +1,47 @@ +/* + * Licence is provided in the jar as license.yml also here: + * https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml + */ +package test.java.utils; + +import org.junit.BeforeClass; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import test.java.main.java.com.djrapitops.plan.database.DatabaseCommitTest; +import test.java.main.java.com.djrapitops.plan.database.DatabaseTest; + +import java.io.File; +import java.io.IOException; + +/** + * @author Fuzzlemann + */ +@RunWith(Suite.class) +@Suite.SuiteClasses({DatabaseCommitTest.class, DatabaseTest.class}) +public class DBTestSuite { + @BeforeClass + public static void setUp() throws IOException { + clean(true); + } + + @BeforeClass + public static void tearDown() throws IOException { + clean(false); + } + + private static void clean(boolean dbOnly) throws IOException { + File testFolder = TestInit.getTestFolder(); + + if (!testFolder.exists() || !testFolder.isDirectory()) { + return; + } + + for (File f : testFolder.listFiles()) { + if (dbOnly && !f.getName().endsWith(".db")) { + continue; + } + + f.delete(); + } + } +} diff --git a/Plan/test/test/java/utils/TestInit.java b/Plan/test/test/java/utils/TestInit.java index 148a43c60..343c9800e 100644 --- a/Plan/test/test/java/utils/TestInit.java +++ b/Plan/test/test/java/utils/TestInit.java @@ -23,7 +23,6 @@ import org.powermock.api.mockito.PowerMockito; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.nio.file.Files; import java.util.logging.Logger; import static org.powermock.api.mockito.PowerMockito.when; @@ -63,17 +62,11 @@ public class TestInit { public static TestInit init() throws Exception { TestInit t = new TestInit(); - t.setUp(true); + t.setUp(); return t; } - public static TestInit init(boolean clearOnStart) throws Exception { - TestInit t = new TestInit(); - t.setUp(clearOnStart); - return t; - } - - private void setUp(boolean clearOnStart) throws Exception { + private void setUp() throws Exception { planMock = PowerMockito.mock(Plan.class); StaticHolder.setInstance(Plan.class, planMock); StaticHolder.setInstance(planMock.getClass(), planMock); @@ -82,9 +75,6 @@ public class TestInit { when(planMock.getConfig()).thenReturn(config); File testFolder = getTestFolder(); - /*if (clearOnStart) { - clean(testFolder); - }*/ when(planMock.getDataFolder()).thenReturn(testFolder); // Html Files @@ -172,24 +162,12 @@ public class TestInit { }; } - private static File getTestFolder() { + static File getTestFolder() { File testFolder = new File("temporaryTestFolder"); testFolder.mkdir(); return testFolder; } - public static void clean() throws IOException { - clean(getTestFolder()); - } - - public static void clean(File testFolder) throws IOException { - if (testFolder.exists() && testFolder.isDirectory()) { - for (File f : testFolder.listFiles()) { - Files.deleteIfExists(f.toPath()); - } - } - } - private Server mockServer() { Server mockServer = PowerMockito.mock(Server.class); From 5de5ea25a88ac52391f1663005ad28cc0c126324 Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Tue, 22 Aug 2017 20:27:01 +0200 Subject: [PATCH 11/16] Fix Test Suite --- .../java/com/djrapitops/plan/database/DatabaseTest.java | 6 +++++- Plan/test/test/java/utils/DBTestSuite.java | 5 +++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java b/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java index d45ad9b5b..9efafb711 100644 --- a/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java +++ b/Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java @@ -213,7 +213,6 @@ public class DatabaseTest { public void testTPSSaving() throws SQLException { db.init(); TPSTable tpsTable = db.getTpsTable(); - List expected = new ArrayList<>(); Random r = new Random(); OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); @@ -224,12 +223,17 @@ public class DatabaseTest { final int entityCount = 6123; final int chunksLoaded = 2134; + List expected = new ArrayList<>(); + expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded)); expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded)); expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded)); expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded)); + List tpsDataOld = tpsTable.getTPSData(); tpsTable.saveTPSData(expected); + + expected.addAll(0, tpsDataOld); assertEquals(expected, tpsTable.getTPSData()); } } diff --git a/Plan/test/test/java/utils/DBTestSuite.java b/Plan/test/test/java/utils/DBTestSuite.java index 1fb12b1c6..a8fc5e31e 100644 --- a/Plan/test/test/java/utils/DBTestSuite.java +++ b/Plan/test/test/java/utils/DBTestSuite.java @@ -4,6 +4,7 @@ */ package test.java.utils; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; @@ -24,7 +25,7 @@ public class DBTestSuite { clean(true); } - @BeforeClass + @AfterClass public static void tearDown() throws IOException { clean(false); } @@ -37,7 +38,7 @@ public class DBTestSuite { } for (File f : testFolder.listFiles()) { - if (dbOnly && !f.getName().endsWith(".db")) { + if (dbOnly && !f.getName().contains(".db")) { continue; } From dc08f96d439c16660ad05c645840d2b07a5ceb61 Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Wed, 23 Aug 2017 10:42:19 +0200 Subject: [PATCH 12/16] Removes DBCommitProcessor --- .../plan/data/handling/DBCommitProcessor.java | 29 --------------- .../data/listeners/PeriodicDBCommitTask.java | 35 ------------------- .../data/listeners/PlanPlayerListener.java | 4 +-- .../plan/database/databases/MySQLDB.java | 16 ++++++--- .../plan/database/databases/SQLDB.java | 10 +++--- .../djrapitops/plan/database/sql/Select.java | 3 -- .../plan/ui/webserver/WebServer.java | 6 ++-- 7 files changed, 20 insertions(+), 83 deletions(-) delete mode 100644 Plan/src/main/java/com/djrapitops/plan/data/handling/DBCommitProcessor.java delete mode 100644 Plan/src/main/java/com/djrapitops/plan/data/listeners/PeriodicDBCommitTask.java diff --git a/Plan/src/main/java/com/djrapitops/plan/data/handling/DBCommitProcessor.java b/Plan/src/main/java/com/djrapitops/plan/data/handling/DBCommitProcessor.java deleted file mode 100644 index 7cd0e6aa1..000000000 --- a/Plan/src/main/java/com/djrapitops/plan/data/handling/DBCommitProcessor.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Licence is provided in the jar as license.yml also here: - * https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml - */ -package main.java.com.djrapitops.plan.data.handling; - -import main.java.com.djrapitops.plan.database.Database; -import main.java.com.djrapitops.plan.queue.processing.Processor; - -/** - * Processor for queueing a Database Commit after changes. - * - * @author Rsl1122 - */ -public class DBCommitProcessor extends Processor { - public DBCommitProcessor(Database object) { - super(object); - } - - @Override - public void process() { - // TODO Prevent Commit during batch operations. - /*try { - TODO FIX object.commit(); - } catch (SQLException e) { - Log.toLog(this.getClass().getName(), e); - }*/ - } -} \ No newline at end of file diff --git a/Plan/src/main/java/com/djrapitops/plan/data/listeners/PeriodicDBCommitTask.java b/Plan/src/main/java/com/djrapitops/plan/data/listeners/PeriodicDBCommitTask.java deleted file mode 100644 index 305c2a941..000000000 --- a/Plan/src/main/java/com/djrapitops/plan/data/listeners/PeriodicDBCommitTask.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licence is provided in the jar as license.yml also here: - * https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml - */ -package main.java.com.djrapitops.plan.data.listeners; - -import com.djrapitops.plugin.task.AbsRunnable; -import main.java.com.djrapitops.plan.Plan; -import main.java.com.djrapitops.plan.data.handling.DBCommitProcessor; -import main.java.com.djrapitops.plan.database.Database; - -/** - * Periodically commits changes to the SQLite Database. - * - * @author Rsl1122 - */ -public class PeriodicDBCommitTask extends AbsRunnable { - - private Plan plugin; - - public PeriodicDBCommitTask(Plan plugin) { - super("PeriodicDBCommitTask"); - this.plugin = plugin; - } - - @Override - public void run() { - Database db = plugin.getDB(); - if ("mysql".equals(db.getConfigName())) { - this.cancel(); - return; - } - plugin.addToProcessQueue(new DBCommitProcessor(db)); - } -} \ No newline at end of file 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 6f22c8f6b..fc366c3dd 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 @@ -4,7 +4,6 @@ import com.djrapitops.plugin.utilities.player.Fetch; import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.data.Session; import main.java.com.djrapitops.plan.data.cache.DataCache; -import main.java.com.djrapitops.plan.data.handling.DBCommitProcessor; import main.java.com.djrapitops.plan.data.handling.player.*; import main.java.com.djrapitops.plan.utilities.MiscUtils; import org.bukkit.entity.Player; @@ -97,8 +96,7 @@ public class PlanPlayerListener implements Listener { plugin.addToProcessQueue( new RegisterProcessor(uuid, time, playersOnline), //TODO Add required variables after UsersTable is done. new IPUpdateProcessor(uuid, ip), - new NameProcessor(uuid, playerName, displayName), - new DBCommitProcessor(plugin.getDB()) + new NameProcessor(uuid, playerName, displayName) ); } 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 d942b1e7e..e9603136c 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 @@ -28,12 +28,18 @@ public class MySQLDB extends SQLDB { dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + config.getString("Database.MySQL.Host") + ":" + config.getString("Database.MySQL.Port") + "/" - + config.getString("Database.MySQL.Database") - + "?rewriteBatchedStatements=true"); + String host = config.getString("Database.MySQL.Host"); + String port = config.getString("Database.MySQL.Port"); + String database = config.getString("Database.MySQL.Database"); - dataSource.setUsername(config.getString("Database.MySQL.User")); - dataSource.setPassword(config.getString("Database.MySQL.Password")); + + dataSource.setUrl("jdbc:mysql://" + host + ":" + port + "/" + database + "?rewriteBatchedStatements=true"); + + String username = config.getString("Database.MySQL.User"); + String password = config.getString("Database.MySQL.Password"); + + dataSource.setUsername(username); + dataSource.setPassword(password); dataSource.setMaxTotal(-1); } 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 9cc89e2b0..6d7277d47 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 @@ -67,7 +67,7 @@ public abstract class SQLDB extends Database { String benchName = "Init " + getConfigName(); Benchmark.start(benchName); try { - if (!setupDatabases()) { + if (!setupDatabase()) { return false; } clean(); @@ -89,7 +89,7 @@ public abstract class SQLDB extends Database { * @return Is the connection usable? * @throws SQLException */ - public boolean setupDatabases() throws SQLException { + public boolean setupDatabase() throws SQLException { boolean newDatabase = isNewDatabase(); if (!versionTable.createTable()) { @@ -233,7 +233,7 @@ public abstract class SQLDB extends Database { Benchmark.start("Remove Account"); Log.debug("Database", "Removing Account: " + uuid); try { - setupDatabases(); + setupDatabase(); } catch (Exception e) { Log.toLog(this.getClass().getName(), e); return false; @@ -259,7 +259,7 @@ public abstract class SQLDB extends Database { public void clean() { Log.info("Cleaning the database."); try { - setupDatabases(); + setupDatabase(); tpsTable.clean(); Log.info("Clean complete."); } catch (SQLException e) { @@ -331,7 +331,7 @@ public abstract class SQLDB extends Database { } public Connection getConnection() throws SQLException { - return dataSource.getConnection(); + return getDataSource().getConnection(); } /** diff --git a/Plan/src/main/java/com/djrapitops/plan/database/sql/Select.java b/Plan/src/main/java/com/djrapitops/plan/database/sql/Select.java index 229c329b0..099420531 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/sql/Select.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/sql/Select.java @@ -1,7 +1,5 @@ package main.java.com.djrapitops.plan.database.sql; -import main.java.com.djrapitops.plan.Log; - public class Select extends WhereParser { public Select(String start) { @@ -19,7 +17,6 @@ public class Select extends WhereParser { } parser.append(" FROM ").append(table); - Log.debug(parser.toString()); return parser; } } diff --git a/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java b/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java index 74a509cb8..6186bc028 100644 --- a/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java +++ b/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java @@ -312,7 +312,7 @@ public class WebServer { Plan plan = Plan.getInstance(); - if (!checkKey(plan, key)) { + if (!checkKey(key)) { String error = "Server Key not given or invalid"; return PageCacheHandler.loadPage(error, () -> { ForbiddenResponse forbidden = new ForbiddenResponse(); @@ -336,8 +336,8 @@ public class WebServer { } } - private boolean checkKey(Plan plan, String key) { - UUID uuid = plan.getServerInfoManager().getServerUUID(); + private boolean checkKey(String key) { + UUID uuid = Plan.getServerUUID(); UUID keyUUID; try { keyUUID = UUID.fromString(key); From 8bffdba72568b4dcf321b2bc1de5363ba5c63fd1 Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Wed, 23 Aug 2017 14:11:50 +0200 Subject: [PATCH 13/16] Fix compilation error --- .../djrapitops/plan/database/Database.java | 2 -- .../plan/database/databases/SQLDB.java | 22 ++++++++----------- .../plan/database/tables/UsersTable.java | 6 ++--- 3 files changed, 11 insertions(+), 19 deletions(-) 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 a22d08da9..b1bd30b3a 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/Database.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/Database.java @@ -331,8 +331,6 @@ public abstract class Database { return serverTable; } - public abstract void commit() throws SQLException; - public ActionsTable getActionsTable() { return actionsTable; } 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 29f8c6e29..37842ad89 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 @@ -227,6 +227,7 @@ public abstract class SQLDB extends Database { if (uuid == null) { return false; } + try { Benchmark.start("Remove Account"); Log.debug("Database", "Removing Account: " + uuid); @@ -237,25 +238,20 @@ public abstract class SQLDB extends Database { return false; } - boolean success = true; for (Table t : getAllTablesInRemoveOrder()) { - if (t instanceof UserIDTable) { - UserIDTable table = (UserIDTable) t; - success = table.removeUser(uuid); - if (!success) { - break; - } + if (!(t instanceof UserIDTable)) { + continue; + } + + UserIDTable table = (UserIDTable) t; + if (!table.removeUser(uuid)) { + throw new IllegalStateException("Removal Failed"); } } - if (success) { - return true; - } - - throw new IllegalStateException("Removal Failed"); + return true; } catch (Exception e) { Log.toLog(this.getClass().getName(), e); - rollback(); // TODO Test case return false; } finally { Benchmark.stop("Database", "Remove Account"); diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java index 76d44bb33..7307bf9c8 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java @@ -1,11 +1,9 @@ package main.java.com.djrapitops.plan.database.tables; +import com.djrapitops.plugin.utilities.Verify; import main.java.com.djrapitops.plan.Log; import main.java.com.djrapitops.plan.database.databases.SQLDB; -import main.java.com.djrapitops.plan.database.sql.Select; -import main.java.com.djrapitops.plan.database.sql.Sql; -import main.java.com.djrapitops.plan.database.sql.TableSqlParser; -import main.java.com.djrapitops.plan.database.sql.Update; +import main.java.com.djrapitops.plan.database.sql.*; import java.sql.PreparedStatement; import java.sql.ResultSet; From 7587792c73b60819b73107632c08cccbf3843441 Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Wed, 23 Aug 2017 14:25:50 +0200 Subject: [PATCH 14/16] Add missing endTransactions Rename usingHTTPS() to isUsingHTTPS() --- .../com/djrapitops/plan/database/tables/UserIDTable.java | 5 +++++ .../java/com/djrapitops/plan/database/tables/UsersTable.java | 2 ++ .../java/com/djrapitops/plan/ui/webserver/WebServer.java | 2 +- .../java/com/djrapitops/plan/utilities/NewPlayerCreator.java | 1 + .../com/djrapitops/plan/utilities/file/dump/DumpUtils.java | 2 +- 5 files changed, 10 insertions(+), 2 deletions(-) diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/UserIDTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/UserIDTable.java index c451a7b56..468ae668c 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/UserIDTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/UserIDTable.java @@ -56,6 +56,11 @@ public abstract class UserIDTable extends Table { Log.toLog(this.getClass().getName(), ex); return false; } finally { + try { + endTransaction(statement); + } catch (SQLException e) { + Log.toLog(this.getClass().getName(), e); + } close(statement); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java index 7307bf9c8..acb99c3d0 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java @@ -169,6 +169,7 @@ public class UsersTable extends UserIDTable { statement.setString(3, name); statement.execute(); } finally { + endTransaction(statement); close(statement); } } @@ -233,6 +234,7 @@ public class UsersTable extends UserIDTable { statement.setString(2, uuid.toString()); statement.execute(); } finally { + endTransaction(statement); close(statement); } } diff --git a/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java b/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java index 6186bc028..9c8866bd1 100644 --- a/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java +++ b/Plan/src/main/java/com/djrapitops/plan/ui/webserver/WebServer.java @@ -544,7 +544,7 @@ public class WebServer { return usingHttps ? "https" : "http"; } - public boolean usingHttps() { + public boolean isUsingHTTPS() { return usingHttps; } diff --git a/Plan/src/main/java/com/djrapitops/plan/utilities/NewPlayerCreator.java b/Plan/src/main/java/com/djrapitops/plan/utilities/NewPlayerCreator.java index c0e7f9aba..ae27c7802 100644 --- a/Plan/src/main/java/com/djrapitops/plan/utilities/NewPlayerCreator.java +++ b/Plan/src/main/java/com/djrapitops/plan/utilities/NewPlayerCreator.java @@ -7,6 +7,7 @@ import main.java.com.djrapitops.plan.data.UserData; /** * @author Rsl1122 + * @deprecated Will be removed once it's sure that it's unnecessary */ @Deprecated // TODO Remove once sure that this is unnecessary. public class NewPlayerCreator { diff --git a/Plan/src/main/java/com/djrapitops/plan/utilities/file/dump/DumpUtils.java b/Plan/src/main/java/com/djrapitops/plan/utilities/file/dump/DumpUtils.java index 88dc6b5ee..2c542cafc 100644 --- a/Plan/src/main/java/com/djrapitops/plan/utilities/file/dump/DumpUtils.java +++ b/Plan/src/main/java/com/djrapitops/plan/utilities/file/dump/DumpUtils.java @@ -198,7 +198,7 @@ public class DumpUtils { * @param plan The Plan instance */ private static void addConfigurationDetails(DumpLog log, Plan plan) { - boolean usingHTTPS = plan.getUiServer().usingHttps(); + boolean usingHTTPS = plan.getUiServer().isUsingHTTPS(); boolean analysisExport = Settings.ANALYSIS_EXPORT.isTrue(); boolean usingAlternativeServerIP = Settings.SHOW_ALTERNATIVE_IP.isTrue(); From a5d90f092d6d0b9945c38b0e29396f67847fc5d2 Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Wed, 23 Aug 2017 14:33:51 +0200 Subject: [PATCH 15/16] Fix Tests --- .../java/com/djrapitops/plan/database/databases/SQLDB.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 37842ad89..53b4d08ff 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 @@ -48,8 +48,6 @@ public abstract class SQLDB extends Database { killsTable = new KillsTable(this, usingMySQL); worldTable = new WorldTable(this, usingMySQL); worldTimesTable = new WorldTimesTable(this, usingMySQL); - - setupDataSource(); } /** @@ -69,6 +67,8 @@ public abstract class SQLDB extends Database { String benchName = "Init " + getConfigName(); Benchmark.start(benchName); try { + setupDataSource(); + if (!setupDatabase()) { return false; } From 68f81590270acb7e1ab8b62d0624df2b5225ae71 Mon Sep 17 00:00:00 2001 From: Fuzzlemann Date: Wed, 23 Aug 2017 14:43:44 +0200 Subject: [PATCH 16/16] Closes 2 not-closed sets Add error-handling if the processor wasn't added into the Queue --- .../djrapitops/plan/database/tables/CommandUseTable.java | 8 ++++---- .../djrapitops/plan/queue/processing/ProcessingQueue.java | 4 +++- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Plan/src/main/java/com/djrapitops/plan/database/tables/CommandUseTable.java b/Plan/src/main/java/com/djrapitops/plan/database/tables/CommandUseTable.java index 2ba744178..09776433a 100644 --- a/Plan/src/main/java/com/djrapitops/plan/database/tables/CommandUseTable.java +++ b/Plan/src/main/java/com/djrapitops/plan/database/tables/CommandUseTable.java @@ -195,7 +195,7 @@ public class CommandUseTable extends Table { public Optional getCommandByID(int id) throws SQLException { PreparedStatement statement = null; - ResultSet set; + ResultSet set = null; try { statement = prepareStatement(Select.from(tableName, columnCommand).where(columnCommandId + "=?").toString()); statement.setInt(1, id); @@ -206,13 +206,13 @@ public class CommandUseTable extends Table { return Optional.empty(); } finally { endTransaction(statement); - close(statement); + close(set, statement); } } public Optional getCommandID(String command) throws SQLException { PreparedStatement statement = null; - ResultSet set; + ResultSet set = null; try { statement = prepareStatement(Select.from(tableName, columnCommandId).where(columnCommand + "=?").toString()); statement.setString(1, command); @@ -223,7 +223,7 @@ public class CommandUseTable extends Table { return Optional.empty(); } finally { endTransaction(statement); - close(statement); + close(set, statement); } } } diff --git a/Plan/src/main/java/com/djrapitops/plan/queue/processing/ProcessingQueue.java b/Plan/src/main/java/com/djrapitops/plan/queue/processing/ProcessingQueue.java index bb44f6262..fed1c8074 100644 --- a/Plan/src/main/java/com/djrapitops/plan/queue/processing/ProcessingQueue.java +++ b/Plan/src/main/java/com/djrapitops/plan/queue/processing/ProcessingQueue.java @@ -32,7 +32,9 @@ public class ProcessingQueue extends Queue { * @param processor processing object. */ public void addToQueue(Processor processor) { - queue.offer(processor); + if (!queue.offer(processor)) { + Log.toLog("ProcessingQueue.addToQueue", new IllegalStateException("Processor was not added to Queue")); + } } }