From 5186526d0a15d0d987e79ce16ffad92b4d948045 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Fri, 3 Sep 2021 12:20:24 +0200 Subject: [PATCH] Remove JDBC RAM leak Signed-off-by: Lixfel --- src/de/steamwar/bungeecore/BungeeCore.java | 11 +- .../commands/PollresultCommand.java | 2 +- .../bungeecore/commands/TeamCommand.java | 2 +- .../bungeecore/sql/BannedUserIPs.java | 46 +++--- .../bungeecore/sql/BauweltMember.java | 46 +++--- .../bungeecore/sql/CheckedSchematic.java | 17 +-- src/de/steamwar/bungeecore/sql/Elo.java | 33 ++--- src/de/steamwar/bungeecore/sql/Event.java | 55 +++---- .../steamwar/bungeecore/sql/EventFight.java | 32 ++-- .../steamwar/bungeecore/sql/IgnoreSystem.java | 20 +-- src/de/steamwar/bungeecore/sql/Mod.java | 23 ++- .../steamwar/bungeecore/sql/PollAnswer.java | 43 ++---- .../steamwar/bungeecore/sql/Punishment.java | 49 +++---- src/de/steamwar/bungeecore/sql/SQL.java | 95 ------------ .../steamwar/bungeecore/sql/SWException.java | 4 +- src/de/steamwar/bungeecore/sql/Schematic.java | 80 +++++----- .../bungeecore/sql/SchematicMember.java | 85 ++--------- src/de/steamwar/bungeecore/sql/Session.java | 5 +- src/de/steamwar/bungeecore/sql/Statement.java | 137 ++++++++++++++++++ .../steamwar/bungeecore/sql/SteamwarUser.java | 132 +++++++++-------- src/de/steamwar/bungeecore/sql/Team.java | 88 +++++------ .../bungeecore/sql/TeamTeilnahme.java | 43 +++--- 22 files changed, 466 insertions(+), 582 deletions(-) delete mode 100644 src/de/steamwar/bungeecore/sql/SQL.java create mode 100644 src/de/steamwar/bungeecore/sql/Statement.java diff --git a/src/de/steamwar/bungeecore/BungeeCore.java b/src/de/steamwar/bungeecore/BungeeCore.java index f2bd01f1..9d5ffd94 100644 --- a/src/de/steamwar/bungeecore/BungeeCore.java +++ b/src/de/steamwar/bungeecore/BungeeCore.java @@ -24,11 +24,11 @@ import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig; import de.steamwar.bungeecore.commands.*; import de.steamwar.bungeecore.comms.SpigotReceiver; import de.steamwar.bungeecore.listeners.*; -import de.steamwar.bungeecore.listeners.mods.ModLoaderBlocker; import de.steamwar.bungeecore.listeners.mods.Forge; import de.steamwar.bungeecore.listeners.mods.LabyMod; +import de.steamwar.bungeecore.listeners.mods.ModLoaderBlocker; import de.steamwar.bungeecore.listeners.mods.WorldDownloader; -import de.steamwar.bungeecore.sql.SQL; +import de.steamwar.bungeecore.sql.Statement; import de.steamwar.bungeecore.sql.SteamwarUser; import de.steamwar.bungeecore.sql.Team; import net.dv8tion.jda.api.JDA; @@ -145,19 +145,20 @@ public class BungeeCore extends Plugin { new EventStarter(); new SessionManager(); new SpigotReceiver(); - new SteamwarDiscordBot(); new TablistManager(); getProxy().getScheduler().schedule(this, () -> { SteamwarUser.clearCache(); Team.clearCache(); }, 1, 1, TimeUnit.HOURS); + + new SteamwarDiscordBot(); } @Override public void onDisable(){ ErrorLogger.stop(); - SQL.close(); + Statement.close(); try { SteamwarDiscordBot.instance().getJda().shutdownNow(); SteamwarDiscordBot.instance().getJda().awaitStatus(JDA.Status.SHUTDOWN); @@ -258,7 +259,7 @@ public class BungeeCore extends Plugin { Persistent.setChatPrefix(CHAT_PREFIX); Persistent.setLobbyServer(LOBBY_SERVER); - SQL.connect( + Statement.connect( config.getString("db.url"), config.getString("db.username"), config.getString("db.password") diff --git a/src/de/steamwar/bungeecore/commands/PollresultCommand.java b/src/de/steamwar/bungeecore/commands/PollresultCommand.java index 1d39e9ea..cfebd66a 100644 --- a/src/de/steamwar/bungeecore/commands/PollresultCommand.java +++ b/src/de/steamwar/bungeecore/commands/PollresultCommand.java @@ -46,7 +46,7 @@ public class PollresultCommand extends BasicCommand { ProxiedPlayer player = (ProxiedPlayer) sender; Map voted = PollAnswer.getCurrentResults(); - Message.send("POLLRESULT_HEADER", player, PollAnswer.getAllAnswered(), PollSystem.getQuestion()); + Message.send("POLLRESULT_HEADER", player, voted.values().stream().reduce(Integer::sum), PollSystem.getQuestion()); for (Map.Entry e: voted.entrySet()) { Message.send("POLLRESULT_LIST", sender, e.getKey(), e.getValue()); } diff --git a/src/de/steamwar/bungeecore/commands/TeamCommand.java b/src/de/steamwar/bungeecore/commands/TeamCommand.java index af3a84ba..3889da28 100644 --- a/src/de/steamwar/bungeecore/commands/TeamCommand.java +++ b/src/de/steamwar/bungeecore/commands/TeamCommand.java @@ -177,7 +177,7 @@ public class TeamCommand extends BasicCommand { if(checkTeamName(player, team, args[2])) return; - Team.create(args[1], args[2], user); + Team.create(args[1], args[2]); user.setTeam(Team.get(args[1]).getTeamId()); user.setLeader(true); Message.send("TEAM_CREATE_CREATED", player, args[2]); diff --git a/src/de/steamwar/bungeecore/sql/BannedUserIPs.java b/src/de/steamwar/bungeecore/sql/BannedUserIPs.java index 6b371ccc..4a754845 100644 --- a/src/de/steamwar/bungeecore/sql/BannedUserIPs.java +++ b/src/de/steamwar/bungeecore/sql/BannedUserIPs.java @@ -19,18 +19,18 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - -import java.sql.ResultSet; -import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; public class BannedUserIPs { - private int userID; - private Timestamp timestamp; + private static final Statement getByID = new Statement("SELECT * FROM BannedUserIPs WHERE UserID = ? ORDER BY Timestamp ASC"); + private static final Statement getByIP = new Statement("SELECT * FROM BannedUserIPs WHERE IP = ? ORDER BY Timestamp DESC"); + private static final Statement banIP = new Statement("INSERT INTO BannedUserIPs (UserID, Timestamp, IP) VALUES (?, NOW(), ?) ON DUPLICATE KEY UPDATE Timestamp=NOW()"); + + private final int userID; + private final Timestamp timestamp; private BannedUserIPs(int userID, Timestamp timestamp){ this.userID = userID; @@ -38,37 +38,31 @@ public class BannedUserIPs { } public static List get(int userID){ - List userIPs = new ArrayList<>(); - ResultSet dbentry = SQL.select("SELECT * FROM BannedUserIPs WHERE UserID = ? ORDER BY Timestamp ASC", userID); - try { - while(dbentry.next()){ + return getByID.select(rs -> { + List userIPs = new ArrayList<>(); + while(rs.next()) { userIPs.add(new BannedUserIPs( userID, - dbentry.getTimestamp("Timestamp"))); + rs.getTimestamp("Timestamp"))); } - } catch (SQLException e) { - BungeeCore.log("Get BannedUserIPs failed", e); - } - return userIPs; + return userIPs; + }, userID); } public static List get(String ip){ - List userIDs = new ArrayList<>(); - ResultSet dbentry = SQL.select("SELECT * FROM BannedUserIPs WHERE IP = ? ORDER BY Timestamp DESC", ip); - try { - while(dbentry.next()){ + return getByIP.select(rs -> { + List userIDs = new ArrayList<>(); + while(rs.next()) { userIDs.add(new BannedUserIPs( - dbentry.getInt("UserID"), - dbentry.getTimestamp("Timestamp"))); + rs.getInt("UserID"), + rs.getTimestamp("Timestamp"))); } - } catch (SQLException e) { - BungeeCore.log("Get BannedUserIPs failed", e); - } - return userIDs; + return userIDs; + }, ip); } static void banIP(SteamwarUser user, String ip){ - SQL.update("INSERT INTO BannedUserIPs (UserID, Timestamp, IP) VALUES (?, NOW(), ?) ON DUPLICATE KEY UPDATE Timestamp=NOW()", user.getId(), ip); + banIP.update(user.getId(), ip); } public int getUserID() { diff --git a/src/de/steamwar/bungeecore/sql/BauweltMember.java b/src/de/steamwar/bungeecore/sql/BauweltMember.java index f05cab23..f89650e2 100644 --- a/src/de/steamwar/bungeecore/sql/BauweltMember.java +++ b/src/de/steamwar/bungeecore/sql/BauweltMember.java @@ -19,15 +19,17 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class BauweltMember{ + + private static final Statement delete = new Statement("DELETE FROM BauweltMember WHERE BauweltID = ? AND MemberID = ?"); + private static final Statement update = new Statement("INSERT INTO BauweltMember (BauweltID, MemberID, WorldEdit, World) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE WorldEdit = VALUES(WorldEdit), World = VALUES(World)"); + private static final Statement getMember = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ? AND MemberID = ?"); + private static final Statement getMembers = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ?"); + private final int bauweltID; private final int memberID; private boolean worldEdit; @@ -52,12 +54,11 @@ public class BauweltMember{ } public void remove(){ - SQL.update("DELETE FROM BauweltMember WHERE BauweltID = " + bauweltID + " AND MemberID = " + memberID); + delete.update(bauweltID, memberID); } private void updateDB(){ - SQL.update("INSERT INTO BauweltMember (BauweltID, MemberID, WorldEdit, World) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE WorldEdit = VALUES(WorldEdit), World = VALUES(World)", - bauweltID, memberID, worldEdit, world); + update.update(bauweltID, memberID, worldEdit, world); } public static BauweltMember getBauMember(UUID ownerID, UUID memberID){ @@ -65,18 +66,12 @@ public class BauweltMember{ } public static BauweltMember getBauMember(int ownerID, int memberID){ - ResultSet member = SQL.select("SELECT * FROM BauweltMember WHERE BauweltID = ? AND MemberID = ?", ownerID, memberID); - try { - if(member == null || !member.next()){ + return getMember.select(rs -> { + if(!rs.next()) return null; - } - boolean worldEdit = member.getBoolean("WorldEdit"); - boolean world = member.getBoolean("World"); - return new BauweltMember(ownerID, memberID, worldEdit, world, false); - } catch (SQLException e) { - BungeeCore.log("Could not load BauweltMember", e); - } - return null; + + return new BauweltMember(ownerID, memberID, rs.getBoolean("WorldEdit"), rs.getBoolean("World"), false); + }, ownerID, memberID); } public static List getMembers(UUID bauweltID){ @@ -84,20 +79,13 @@ public class BauweltMember{ } public static List getMembers(int bauweltID){ - try{ - ResultSet memberlist = SQL.select("SELECT * FROM BauweltMember WHERE BauweltID = ?", bauweltID); + return getMembers.select(rs -> { List members = new ArrayList<>(); - while(memberlist.next()){ - int memberID = memberlist.getInt("MemberID"); - boolean worldEdit = memberlist.getBoolean("WorldEdit"); - boolean world = memberlist.getBoolean("World"); - members.add(new BauweltMember(bauweltID, memberID, worldEdit, world, false)); + while(rs.next()){ + members.add(new BauweltMember(bauweltID, rs.getInt("MemberID"), rs.getBoolean("WorldEdit"), rs.getBoolean("World"), false)); } return members; - }catch(SQLException e){ - BungeeCore.log("Could not load BauweltMembers", e); - } - return new ArrayList<>(); + }, bauweltID); } public int getBauweltID() { diff --git a/src/de/steamwar/bungeecore/sql/CheckedSchematic.java b/src/de/steamwar/bungeecore/sql/CheckedSchematic.java index 0424e4aa..436d5ab3 100644 --- a/src/de/steamwar/bungeecore/sql/CheckedSchematic.java +++ b/src/de/steamwar/bungeecore/sql/CheckedSchematic.java @@ -27,6 +27,9 @@ import java.util.List; public class CheckedSchematic { + private static final Statement create = new Statement("INSERT INTO CheckedSchematic (SchemName, SchemOwner, Validator, StartTime, EndTime, DeclineReason) VALUES (?, ?, ?, ?, ?, ?)"); + private static final Statement previous = new Statement("SELECT * FROM CheckedSchematic WHERE SchemName = ? AND SchemOwner = ? ORDER BY EndTime ASC"); + private final String schemName; private final int schemOwner; @@ -45,20 +48,16 @@ public class CheckedSchematic { } public static void create(String schemName, int schemOwner, int validator, Timestamp startTime, Timestamp endTime, String reason){ - SQL.update("INSERT INTO CheckedSchematic (SchemName, SchemOwner, Validator, StartTime, EndTime, DeclineReason) VALUES (?, ?, ?, ?, ?, ?)", - schemName, schemOwner, validator, startTime, endTime, reason); + create.update(schemName, schemOwner, validator, startTime, endTime, reason); } public static List previousChecks(String schemName, int schemOwner){ - ResultSet rs = SQL.select("SELECT * FROM CheckedSchematic WHERE SchemName = ? AND SchemOwner = ? ORDER BY EndTime ASC", schemName, schemOwner); - List schematics = new ArrayList<>(); - try { + return previous.select(rs -> { + List schematics = new ArrayList<>(); while(rs.next()) schematics.add(new CheckedSchematic(rs)); - } catch (SQLException e) { - throw new SecurityException("Could not load previous checks", e); - } - return schematics; + return schematics; + }, schemName, schemOwner); } public int getValidator() { diff --git a/src/de/steamwar/bungeecore/sql/Elo.java b/src/de/steamwar/bungeecore/sql/Elo.java index 07a95c2e..b61c8a3b 100644 --- a/src/de/steamwar/bungeecore/sql/Elo.java +++ b/src/de/steamwar/bungeecore/sql/Elo.java @@ -19,33 +19,26 @@ package de.steamwar.bungeecore.sql; -import java.sql.ResultSet; -import java.sql.SQLException; - public class Elo { + + private static final Statement elo = new Statement("SELECT Elo FROM Elo WHERE UserID = ? AND GameMode = ?"); + private static final Statement place = new Statement("SELECT COUNT(*) AS Place FROM Elo WHERE GameMode = ? AND Elo > ?"); + private Elo(){} public static int getElo(int userID, String gameMode){ - ResultSet rs = SQL.select("SELECT Elo FROM Elo WHERE UserID = ? AND GameMode = ?", userID, gameMode); - int elo = 1000; - try { + return elo.select(rs -> { if(rs.next()) - elo = rs.getInt("Elo"); - } catch (SQLException e) { - throw new SecurityException("Could not get Elo", e); - } - return elo; + return rs.getInt("Elo"); + return 1000; + }, userID, gameMode); } public static int getPlacement(int elo, String gameMode){ - ResultSet rs = SQL.select("SELECT COUNT(*) AS Place FROM Elo WHERE GameMode = ? AND Elo > ?", gameMode, elo); - try{ - if(!rs.next()) - return -1; - - return rs.getInt("Place"); - }catch(SQLException e){ - throw new SecurityException("Could not get place", e); - } + return place.select(rs -> { + if(rs.next()) + return rs.getInt("Place"); + return -1; + }, gameMode, elo); } } diff --git a/src/de/steamwar/bungeecore/sql/Event.java b/src/de/steamwar/bungeecore/sql/Event.java index 72db0659..93fd211b 100644 --- a/src/de/steamwar/bungeecore/sql/Event.java +++ b/src/de/steamwar/bungeecore/sql/Event.java @@ -19,17 +19,20 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; -import java.util.LinkedList; +import java.util.ArrayList; import java.util.List; public class Event { + private static final Statement byCurrent = new Statement("SELECT * FROM Event WHERE Start < now() AND End > now()"); + private static final Statement byId = new Statement("SELECT * FROM Event WHERE EventID = ?"); + private static final Statement byName = new Statement("SELECT * FROM Event WHERE lower(EventName) = ?"); + private static final Statement byComing = new Statement("SELECT * FROM Event WHERE Start > now()"); + private final int eventID; private final String eventName; private final Timestamp start; @@ -56,57 +59,39 @@ public class Event { if(current != null && current.now()) return current; - ResultSet rs = SQL.select("SELECT * FROM Event WHERE Start < now() AND End > now()"); - try{ - if(!rs.next()){ + return byCurrent.select(rs -> { + if(rs.next()) + current = new Event(rs); + else current = null; - return null; - } - - current = new Event(rs); return current; - }catch (SQLException e){ - BungeeCore.log("Failed to load current Event", e); - throw new SecurityException(); - } + }); } public static Event get(int eventID){ - ResultSet rs = SQL.select("SELECT * FROM Event WHERE EventID = " + eventID); - try{ + return byId.select(rs -> { if(!rs.next()) - throw new IllegalArgumentException(); - + throw new SQLException("Couldn't find event " + eventID); return new Event(rs); - }catch (SQLException e){ - BungeeCore.log("Failed to load Event", e); - throw new SecurityException(); - } + }, eventID); } public static Event get(String eventName){ - ResultSet rs = SQL.select("SELECT * FROM Event WHERE lower(EventName) = ?", eventName.toLowerCase()); - try{ + return byName.select(rs -> { if(!rs.next()) return null; return new Event(rs); - }catch (SQLException e){ - BungeeCore.log("Failed to load Event by name", e); - throw new SecurityException(); - } + }, eventName.toLowerCase()); } public static List getComing(){ - List events = new LinkedList<>(); - ResultSet rs = SQL.select("SELECT * FROM Event WHERE Start > now()"); - try{ + return byComing.select(rs -> { + List events = new ArrayList<>(); while(rs.next()) events.add(new Event(rs)); - }catch (SQLException e){ - BungeeCore.log("Failed to load Events", e); - } - return events; + return events; + }); } private boolean now(){ diff --git a/src/de/steamwar/bungeecore/sql/EventFight.java b/src/de/steamwar/bungeecore/sql/EventFight.java index c86b145d..ffcbe6f8 100644 --- a/src/de/steamwar/bungeecore/sql/EventFight.java +++ b/src/de/steamwar/bungeecore/sql/EventFight.java @@ -20,7 +20,6 @@ package de.steamwar.bungeecore.sql; import de.steamwar.bungeecore.ArenaMode; -import de.steamwar.bungeecore.BungeeCore; import java.sql.ResultSet; import java.sql.SQLException; @@ -31,7 +30,11 @@ import static java.time.temporal.ChronoUnit.SECONDS; public class EventFight implements Comparable { - private static Queue fights = new PriorityQueue<>(); + private static final Statement reschedule = new Statement("UPDATE EventFight SET StartTime = ? WHERE EventID = ? AND FightID = ?"); + private static final Statement allComing = new Statement("SELECT * FROM EventFight WHERE StartTime > now() ORDER BY `StartTime` ASC"); + private static final Statement event = new Statement("SELECT * FROM EventFight WHERE EventID = ? ORDER BY `StartTime` ASC"); + + private static final Queue fights = new PriorityQueue<>(); private final int eventID; private final int fightID; @@ -57,31 +60,26 @@ public class EventFight implements Comparable { public void reschedule(){ startTime = Timestamp.from(new Date().toInstant().plus(30, SECONDS)); - SQL.update("UPDATE EventFight SET StartTime = ? WHERE EventID = ? AND FightID = ?", startTime, eventID, fightID); + reschedule.update(startTime, eventID, fightID); } public static void loadAllComingFights(){ - ResultSet rs = SQL.select("SELECT * FROM EventFight WHERE StartTime > now() ORDER BY `StartTime` ASC"); - fights.clear(); - try{ + allComing.select(rs -> { + fights.clear(); while(rs.next()){ - fights.add(new EventFight(rs)); + fights.add(new EventFight(rs)); } - }catch (SQLException e){ - BungeeCore.log("Failed to load EventFights", e); - } + return null; + }); } public static List getEvent(int eventID){ - ResultSet rs = SQL.select("SELECT * FROM EventFight WHERE EventID = ? ORDER BY `StartTime` ASC", eventID); - List fights = new LinkedList<>(); - try{ + return event.select(rs -> { + List fights = new LinkedList<>(); while(rs.next()) fights.add(new EventFight(rs)); - }catch (SQLException e){ - BungeeCore.log("Failed to load EventFights", e); - } - return fights; + return fights; + }, eventID); } public static Queue getFights() { diff --git a/src/de/steamwar/bungeecore/sql/IgnoreSystem.java b/src/de/steamwar/bungeecore/sql/IgnoreSystem.java index 73c15009..185fb089 100644 --- a/src/de/steamwar/bungeecore/sql/IgnoreSystem.java +++ b/src/de/steamwar/bungeecore/sql/IgnoreSystem.java @@ -22,9 +22,13 @@ package de.steamwar.bungeecore.sql; import net.md_5.bungee.api.connection.ProxiedPlayer; import java.sql.ResultSet; -import java.sql.SQLException; public class IgnoreSystem{ + + private static final Statement select = new Statement("SELECT COUNT(*) AS blocked FROM IgnoredPlayers WHERE Ignorer = ? AND Ignored = ?"); + private static final Statement insert = new Statement("INSERT INTO IgnoredPlayers (Ignorer, Ignored) VALUES (?, ?)"); + private static final Statement delete = new Statement("DELETE FROM IgnoredPlayers WHERE Ignorer = ? AND Ignored = ?"); + private IgnoreSystem(){} public static boolean isIgnored(ProxiedPlayer ignorer, ProxiedPlayer ignored){ @@ -34,22 +38,14 @@ public class IgnoreSystem{ } public static boolean isIgnored(SteamwarUser ignorer, SteamwarUser ignored) { - try { - ResultSet rs = SQL.select("SELECT COUNT(*) AS blocked FROM IgnoredPlayers WHERE Ignorer = ? AND Ignored = ?", ignorer.getId(), ignored.getId()); - if(!rs.next()) - return false; - - return rs.getInt("blocked") > 0; - } catch (SQLException e) { - throw new SecurityException("Could not check if ignored", e); - } + return select.select(ResultSet::next, ignorer.getId(), ignored.getId()); } public static void ignore(SteamwarUser ignorer, SteamwarUser ignored) { - SQL.update("INSERT INTO IgnoredPlayers (Ignorer, Ignored) VALUES (?, ?)", ignorer.getId(), ignored.getId()); + insert.update(ignorer.getId(), ignored.getId()); } public static void unIgnore(SteamwarUser ignorer, SteamwarUser ignored) { - SQL.update("DELETE FROM IgnoredPlayers WHERE Ignorer = ? AND Ignored = ?", ignorer.getId(), ignored.getId()); + delete.update(ignorer.getId(), ignored.getId()); } } diff --git a/src/de/steamwar/bungeecore/sql/Mod.java b/src/de/steamwar/bungeecore/sql/Mod.java index 98034bb5..9aad08b0 100644 --- a/src/de/steamwar/bungeecore/sql/Mod.java +++ b/src/de/steamwar/bungeecore/sql/Mod.java @@ -19,12 +19,11 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - -import java.sql.ResultSet; -import java.sql.SQLException; - public class Mod { + + private static final Statement get = new Statement("SELECT * FROM Mods WHERE ModName = ? AND Platform = ?"); + private static final Statement insert = new Statement("INSERT INTO Mods (ModName, Platform) VALUES (?, ?)"); + private final String modName; private final Platform platform; private final ModType modType; @@ -36,15 +35,15 @@ public class Mod { } public static Mod get(String modName, Platform platform){ - ResultSet rs = SQL.select("SELECT * FROM Mods WHERE ModName = ? AND Platform = ?", modName, platform.value); - try{ + Mod mod = get.select(rs -> { if(rs.next()) return new Mod(modName, platform, ModType.valueOf(rs.getInt("ModType"))); - }catch (SQLException e){ - BungeeCore.log("Failed to load Mod", e); - throw new SecurityException(); - } - SQL.update("INSERT INTO Mods (ModName, Platform) VALUES (?, ?)", modName, platform.value); + return null; + }, modName, platform.value); + if(mod != null) + return mod; + + insert.update(modName, platform.value); return new Mod(modName, platform, ModType.UNKLASSIFIED); } diff --git a/src/de/steamwar/bungeecore/sql/PollAnswer.java b/src/de/steamwar/bungeecore/sql/PollAnswer.java index 62fcee04..7d23c384 100644 --- a/src/de/steamwar/bungeecore/sql/PollAnswer.java +++ b/src/de/steamwar/bungeecore/sql/PollAnswer.java @@ -19,7 +19,6 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.listeners.PollSystem; import java.sql.ResultSet; @@ -29,6 +28,10 @@ import java.util.Map; public class PollAnswer { + private static final Statement get = new Statement("SELECT * FROM PollAnswer WHERE UserID = ? AND Question = ?"); + private static final Statement getResults = new Statement("SELECT Count(UserID) AS Times, Answer FROM PollAnswer WHERE Question = ? GROUP BY Answer ORDER BY `Times` ASC"); + private static final Statement insert = new Statement("INSERT INTO PollAnswer (UserID, Question, Answer) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Answer = VALUES(Answer)"); + private final int userID; private final String question; private int answer; @@ -44,38 +47,20 @@ public class PollAnswer { } public static PollAnswer get(int userID){ - ResultSet rs = SQL.select("SELECT * FROM PollAnswer WHERE UserID = ? AND Question = ?", userID, PollSystem.getQuestion()); - try { - if(!rs.next()) - return new PollAnswer(userID, PollSystem.getQuestion()); - return new PollAnswer(rs); - } catch (SQLException e) { - throw new SecurityException("Unable to get PollAnswer", e); - } + return get.select(rs -> { + if(rs.next()) + return new PollAnswer(rs); + return new PollAnswer(userID, PollSystem.getQuestion()); + }, userID, PollSystem.getQuestion()); } public static Map getCurrentResults() { - ResultSet set = SQL.select("SELECT Count(UserID) AS Times, Answer FROM PollAnswer WHERE Question = ? GROUP BY Answer ORDER BY `Times` ASC", PollSystem.getQuestion()); - try { + return getResults.select(rs -> { Map retMap = new HashMap<>(); - while (set.next()) { - retMap.put(PollSystem.getAnswer(set.getInt("Answer")), set.getInt("Times")); - } + while (rs.next()) + retMap.put(PollSystem.getAnswer(rs.getInt("Answer")), rs.getInt("Times")); return retMap; - }catch (SQLException e) { - throw new SecurityException("Unable to get PollAnswer", e); - } - } - - public static Integer getAllAnswered() { - ResultSet set = SQL.select("SELECT Count(UserID) AS Times FROM PollAnswer WHERE Question = ?", PollSystem.getQuestion()); - try { - if(!set.next()) - throw new SecurityException("Could not get PollAnswers"); - return set.getInt("Times"); - }catch (SQLException e) { - throw new SecurityException("Unable to get PollAnswer", e); - } + }, PollSystem.getQuestion()); } public boolean hasAnswered(){ @@ -84,6 +69,6 @@ public class PollAnswer { public void setAnswer(int answer){ this.answer = answer; - SQL.update("INSERT INTO PollAnswer (UserID, Question, Answer) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Answer = VALUES(Answer)", userID, question, answer); + insert.update(userID, question, answer); } } diff --git a/src/de/steamwar/bungeecore/sql/Punishment.java b/src/de/steamwar/bungeecore/sql/Punishment.java index e4d90348..914e6b85 100644 --- a/src/de/steamwar/bungeecore/sql/Punishment.java +++ b/src/de/steamwar/bungeecore/sql/Punishment.java @@ -31,45 +31,40 @@ import java.util.*; public class Punishment { + private static final Statement getPunishment = new Statement("SELECT * FROM Punishments WHERE UserId = ? AND Type = ? ORDER BY PunishmentId DESC LIMIT 1"); + private static final Statement getPunishments = new Statement("SELECT * FROM Punishments WHERE PunishmentId IN (SELECT MAX(PunishmentId) FROM Punishments WHERE UserId = ? GROUP BY Type)"); + private static final Statement getAllPunishments = new Statement("SELECT * FROM Punishments WHERE UserId = ? ORDER BY `PunishmentId` DESC"); + private static final Statement insert = new Statement("INSERT INTO Punishments (UserId, Punisher, Type, Reason, EndTime, Perma) VALUES (?, ?, ?, ?, ?, ?)"); + private static final Statement update = new Statement("UPDATE Punishments SET EndTime = ?, Reason = ?, Perma = ? WHERE PunishmentId = ?"); + public static Punishment getPunishmentOfPlayer(int user, PunishmentType type) { - ResultSet set = SQL.select("SELECT * FROM Punishments WHERE UserId = ? AND Type = ? ORDER BY PunishmentId DESC LIMIT 1", user, type.name()); - try { - if(!set.next()) - return null; - return new Punishment(set); - } catch (SQLException e) { - throw new SecurityException("Could not Load Punishments", e); - } + return getPunishment.select(rs -> { + if(rs.next()) + return new Punishment(rs); + return null; + }, user, type.name()); } public static Map getPunishmentsOfPlayer(int user) { - ResultSet set = SQL.select("SELECT * FROM Punishments WHERE PunishmentId IN (SELECT MAX(PunishmentId) FROM Punishments WHERE UserId = ? GROUP BY Type)", user); - try { + return getPunishments.select(rs -> { Map punishments = new HashMap<>(); - while (set.next()) - punishments.put(PunishmentType.valueOf(set.getString("Type")), new Punishment(set)); + while (rs.next()) + punishments.put(PunishmentType.valueOf(rs.getString("Type")), new Punishment(rs)); return punishments; - } catch (SQLException e) { - throw new SecurityException("Could not Load Punishments", e); - } + }, user); } public static List getAllPunishmentsOfPlayer(int user) { - ResultSet set = SQL.select("SELECT * FROM Punishments WHERE UserId = ? ORDER BY `PunishmentId` DESC", user); - try { + return getAllPunishments.select(rs -> { List punishments = new ArrayList<>(); - while (set.next()) { - punishments.add(new Punishment(set)); - } + while (rs.next()) + punishments.add(new Punishment(rs)); return punishments; - } catch (SQLException e) { - throw new SecurityException("Could not Load all Punishments", e); - } + }, user); } public static Punishment createPunishment(int user, int executor, PunishmentType type, String reason, Timestamp endTime, boolean perma) { - SQL.update("INSERT INTO Punishments (UserId, Punisher, Type, Reason, EndTime, Perma) VALUES (?, ?, ?, ?, ?, ?)", - user, executor, type.name(), reason, endTime, perma); + insert.update(user, executor, type.name(), reason, endTime, perma); return getPunishmentOfPlayer(user, type); } @@ -122,7 +117,7 @@ public class Punishment { } public void updateEndTime(int from, String newreason, Timestamp newUpdate, boolean perma) { - if(newreason.equals(reason) && newUpdate.equals(endTime) && perma == perma) + if(newreason.equals(reason) && newUpdate.equals(endTime) && this.perma == perma) return; ProxiedPlayer player = BungeeCore.get().getProxy().getPlayer(SteamwarUser.get(from).getUuid()); String newReason = Message.parse("BAN_CHANGED", player, reason, @@ -131,7 +126,7 @@ public class Punishment { getBantime(newUpdate, perma), newreason); - SQL.update("UPDATE Punishments SET EndTime = ?, Reason = ?, Perma = ? WHERE PunishmentId = ?", newUpdate, newReason, perma, id); + update.update(newUpdate, newReason, perma, id); this.reason = newReason; this.perma = perma; this.endTime = newUpdate; diff --git a/src/de/steamwar/bungeecore/sql/SQL.java b/src/de/steamwar/bungeecore/sql/SQL.java deleted file mode 100644 index 947e2b60..00000000 --- a/src/de/steamwar/bungeecore/sql/SQL.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - This file is a part of the SteamWar software. - - Copyright (C) 2020 SteamWar.de-Serverteam - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package de.steamwar.bungeecore.sql; - -import de.steamwar.bungeecore.BungeeCore; -import net.md_5.bungee.api.ProxyServer; - -import java.sql.*; - - -public class SQL { - private SQL(){} - - private static Connection con; - private static String url; - private static String user; - private static String password; - - public static void connect(String url, String user, String password) { - SQL.url = url; - SQL.user = user; - SQL.password = password; - try { - con = DriverManager.getConnection(url + "?autoreconnect=true", user, password); - }catch (SQLException e) { - ProxyServer.getInstance().stop(); - throw new SecurityException("Could not start SQL-Exception", e); - } - } - - public static void close() { - try { - if(con != null) - con.close(); - }catch (SQLException e) { - BungeeCore.log("Could not close SQL-Connection", e); - } - } - - static void update(String qry, Object... objects) { - try { - prepare(con, qry, objects).executeUpdate(); - } catch (SQLException e) { - sqlException(); - try (PreparedStatement st = con.prepareStatement(qry)) { - st.executeUpdate(); - } catch (SQLException ex) { - throw new SecurityException("Could not execute update statement", ex); - } - } - } - - static ResultSet select(String qry, Object... objects){ - try{ - return prepare(con, qry, objects).executeQuery(); - } catch (SQLException e) { - sqlException(); - try { - return prepare(con, qry, objects).executeQuery(); - } catch (SQLException ex) { - throw new SecurityException("Could not run Select-Statement", ex); - } - } - } - - private static PreparedStatement prepare(Connection connection, String qry, Object... objects) throws SQLException{ - PreparedStatement st = connection.prepareStatement(qry); - for(int i = 0; i < objects.length; i++){ - st.setObject(i+1, objects[i]); - } - return st; - } - - private static void sqlException(){ - close(); - connect(url, user, password); - } -} diff --git a/src/de/steamwar/bungeecore/sql/SWException.java b/src/de/steamwar/bungeecore/sql/SWException.java index 44a43cab..8a2c2e1f 100644 --- a/src/de/steamwar/bungeecore/sql/SWException.java +++ b/src/de/steamwar/bungeecore/sql/SWException.java @@ -22,7 +22,9 @@ package de.steamwar.bungeecore.sql; public class SWException { private SWException(){} + private static final Statement insert = new Statement("INSERT INTO Exception (server, message, stacktrace) VALUES (?, ?, ?)"); + public static void log(String server, String message, String stacktrace){ - SQL.update("INSERT INTO Exception (server, message, stacktrace) VALUES (?, ?, ?)", server, message, stacktrace); + insert.update(server, message, stacktrace); } } diff --git a/src/de/steamwar/bungeecore/sql/Schematic.java b/src/de/steamwar/bungeecore/sql/Schematic.java index 9d25a384..b7155100 100644 --- a/src/de/steamwar/bungeecore/sql/Schematic.java +++ b/src/de/steamwar/bungeecore/sql/Schematic.java @@ -23,14 +23,22 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import java.util.UUID; public class Schematic { + + private static final Statement schemByName = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemName = ? AND SchemOwner = ?"); + private static final Statement schemById = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemID = ?"); + private static final Statement schemsByType = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemType = ?"); + private static final Statement schemsByUserType = new Statement("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemType = ? AND SchemOwner = ?"); + private static final Statement schemsOfUser = new Statement("SELECT SchemID, SchemName, SchemOwner, Item, SchemType, Rank, SchemFormat, Item FROM Schematic WHERE SchemOwner = ? ORDER BY SchemName"); + private static final Statement updateType = new Statement("UPDATE Schematic SET SchemType = ? WHERE SchemID = ?"); + private static final Statement updateRank = new Statement("UPDATE Schematic SET Rank = ? WHERE SchemID = ?"); + private final int schemID; private final String schemName; private final int schemOwner; private SchematicType schemType; - private String schemItem; + private final String schemItem; private Schematic(ResultSet rs) throws SQLException { this.schemID = rs.getInt("SchemID"); @@ -40,74 +48,52 @@ public class Schematic { this.schemItem = rs.getString("Item"); } - public static Schematic getSchemFromDB(String schemName, UUID schemOwner){ - return getSchemFromDB(schemName, SteamwarUser.get(schemOwner).getId()); - } - public static Schematic getSchemFromDB(String schemName, int schemOwner){ - ResultSet schematic = SQL.select("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemName = ? AND SchemOwner = ?", schemName, schemOwner); - try { - if(schematic == null || !schematic.next()){ - return null; - } - return new Schematic(schematic); - } catch (SQLException e) { - throw new SecurityException("Failed loading schematic", e); - } + return schemByName.select(rs -> { + if(!rs.next()) + return new Schematic(rs); + return null; + }, schemName, schemOwner); } public static Schematic getSchemFromDB(int schemID){ - ResultSet schematic = SQL.select("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemID = ?", schemID); - try { - if(!schematic.next()) + return schemById.select(rs -> { + if(!rs.next()) throw new SecurityException("Failed loading schematic " + schemID); - return new Schematic(schematic); - } catch (SQLException e) { - throw new SecurityException("Failed loading schematic", e); - } + return new Schematic(rs); + }, schemID); } public static List getAllSchemsOfType(SchematicType schemType){ - try{ - ResultSet schematic = SQL.select("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemType = ?", schemType.toDB()); + return schemsByType.select(rs -> { List schematics = new ArrayList<>(); - while(schematic.next()){ - schematics.add(new Schematic(schematic)); - } + while(rs.next()) + schematics.add(new Schematic(rs)); return schematics; - }catch(SQLException e){ - throw new SecurityException("Failed loading all schems of type", e); - } + }, schemType.toDB()); } public static List getSchemsOfType(int userId, SchematicType schemType){ - try{ - ResultSet schematic = SQL.select("SELECT SchemID, SchemName, SchemOwner, SchemType, Item FROM Schematic WHERE SchemType = ? AND SchemOwner = ?", schemType.toDB(), userId); + return schemsByUserType.select(rs -> { List schematics = new ArrayList<>(); - while(schematic.next()){ - schematics.add(new Schematic(schematic)); - } + while(rs.next()) + schematics.add(new Schematic(rs)); return schematics; - }catch(SQLException e){ - throw new SecurityException("Failed loading schems of type", e); - } + }, schemType.toDB(), userId); } public static List getSchemsAccessibleByUser(int schemOwner){ - try{ - ResultSet schematic = SQL.select("SELECT SchemID, SchemName, SchemOwner, Item, SchemType, Rank, SchemFormat, Item FROM Schematic WHERE SchemOwner = ? ORDER BY SchemName", schemOwner); + return schemsOfUser.select(rs -> { List schematics = new ArrayList<>(); - while(schematic.next()){ - schematics.add(new Schematic(schematic)); + while(rs.next()){ + schematics.add(new Schematic(rs)); } List addedSchems = SchematicMember.getAccessibleSchems(schemOwner); for(SchematicMember schem : addedSchems){ schematics.add(getSchemFromDB(schem.getSchemName(), schem.getSchemOwner())); } return schematics; - }catch(SQLException e){ - throw new SecurityException("Failed listing schematics", e); - } + }, schemOwner); } public int getSchemID() { @@ -132,10 +118,10 @@ public class Schematic { public void setSchemType(SchematicType schemType) { this.schemType = schemType; - SQL.update("UPDATE Schematic SET SchemType = ? WHERE SchemID = ?", schemType.toDB(), schemID); + updateType.update(schemType.toDB(), schemID); } public void setRank(int rank) { - SQL.update("UPDATE Schematic SET Rank = ? WHERE SchemID = ?", rank, schemID); + updateRank.update(rank, schemID); } } diff --git a/src/de/steamwar/bungeecore/sql/SchematicMember.java b/src/de/steamwar/bungeecore/sql/SchematicMember.java index 85b84855..c4ac21ac 100644 --- a/src/de/steamwar/bungeecore/sql/SchematicMember.java +++ b/src/de/steamwar/bungeecore/sql/SchematicMember.java @@ -19,13 +19,15 @@ package de.steamwar.bungeecore.sql; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import java.util.UUID; public class SchematicMember { + + private static final Statement insert = new Statement("INSERT INTO SchemMember (SchemName, SchemOwner, Member) VALUES (?, ?, ?)"); + private static final Statement selectSchems = new Statement("SELECT * FROM SchemMember WHERE Member = ?"); + private static final Statement delete = new Statement("DELETE FROM SchemMember WHERE SchemOwner = ? AND SchemName = ? AND Member = ?"); + private final int schemOwner; private final String schemName; private final int member; @@ -38,82 +40,17 @@ public class SchematicMember { updateDB(); } - public SchematicMember(String schemName, int schemOwner, int schemMember){ - this(schemName, schemOwner, schemMember, true); - } - - public SchematicMember(String schemName, UUID schemOwner, UUID schemMember){ - this(schemName, SteamwarUser.get(schemOwner).getId(), SteamwarUser.get(schemMember).getId(), true); - } - private void updateDB(){ - SQL.update("INSERT INTO SchemMember (SchemName, SchemOwner, Member) VALUES (?, ?, ?)", schemName, schemOwner, member); - } - - public static SchematicMember getSchemMemberFromDB(String schemName, UUID schemOwner, UUID schemMember){ - return getSchemMemberFromDB(schemName, SteamwarUser.get(schemOwner).getId(), SteamwarUser.get(schemMember).getId()); - } - - public static SchematicMember getSchemMemberFromDB(String schemName, int schemOwner, int schemMember){ - ResultSet schematicMember = SQL.select("SELECT * FROM SchemMember WHERE SchemName = ? AND SchemOwner = ? AND Member = ?", schemName, schemOwner, schemMember); - try { - if(schematicMember == null || !schematicMember.next()){ - return null; - } - return new SchematicMember(schemName, schemOwner, schemMember, false); - } catch (SQLException e) { - throw new SecurityException("Could not get schemmember", e); - } - } - - public static SchematicMember getMemberBySchematic(String schemName, int schemMember){ - ResultSet schematicMember = SQL.select("SELECT * FROM SchemMember WHERE SchemName = ? AND Member = ?", schemName, schemMember); - try { - if(schematicMember == null || !schematicMember.next()){ - return null; - } - int schemOwner = schematicMember.getInt("SchemOwner"); - return new SchematicMember(schemName, schemOwner, schemMember, false); - } catch (SQLException e) { - throw new SecurityException("Could not get member", e); - } - } - - public static List getSchemMembers(String schemName, UUID schemOwner){ - return getSchemMembers(schemName, SteamwarUser.get(schemOwner).getId()); - } - - public static List getSchemMembers(String schemName, int schemOwner){ - ResultSet schematicMember = SQL.select("SELECT * FROM SchemMember WHERE SchemName = ? AND SchemOwner = ?", schemName, schemOwner); - try { - List schematicMembers = new ArrayList<>(); - while(schematicMember.next()){ - int schemMember = schematicMember.getInt("Member"); - schematicMembers.add(new SchematicMember(schemName, schemOwner, schemMember, false)); - } - return schematicMembers; - } catch (SQLException e) { - throw new SecurityException("Could not get schemmembers", e); - } - } - - public static List getAccessibleSchems(UUID schemMember){ - return getAccessibleSchems(SteamwarUser.get(schemMember).getId()); + insert.update(schemName, schemOwner, member); } public static List getAccessibleSchems(int schemMember){ - ResultSet schematicMember = SQL.select("SELECT * FROM SchemMember WHERE Member = ?", schemMember); - try { + return selectSchems.select(rs -> { List schematicMembers = new ArrayList<>(); - while(schematicMember.next()){ - String schemName = schematicMember.getString("SchemName"); - int schemOwner = schematicMember.getInt("SchemOwner"); - schematicMembers.add(new SchematicMember(schemName, schemOwner, schemMember, false)); - } + while(rs.next()) + schematicMembers.add(new SchematicMember(rs.getString("SchemName"), rs.getInt("SchemOwner"), schemMember, false)); return schematicMembers; - } catch (SQLException e) { - throw new SecurityException("Could not get accessible schems", e); - } + }, schemMember); } public int getSchemOwner() { @@ -129,6 +66,6 @@ public class SchematicMember { } public void remove(){ - SQL.update("DELETE FROM SchemMember WHERE SchemOwner = ? AND SchemName = ? AND Member = ?", schemOwner, schemName, member); + delete.update(schemOwner, schemName, member); } } diff --git a/src/de/steamwar/bungeecore/sql/Session.java b/src/de/steamwar/bungeecore/sql/Session.java index 7f48659a..9793c353 100644 --- a/src/de/steamwar/bungeecore/sql/Session.java +++ b/src/de/steamwar/bungeecore/sql/Session.java @@ -22,9 +22,12 @@ package de.steamwar.bungeecore.sql; import java.sql.Timestamp; public class Session { + + private static final Statement insert = new Statement("INSERT INTO Session (UserID, StartTime, EndTime) VALUES (?, ?, NOW())"); + private Session(){} public static void insertSession(int userID, Timestamp startTime){ - SQL.update("INSERT INTO Session (UserID, StartTime, EndTime) VALUES (?, ?, NOW())", userID, startTime); + insert.update(userID, startTime); } } diff --git a/src/de/steamwar/bungeecore/sql/Statement.java b/src/de/steamwar/bungeecore/sql/Statement.java new file mode 100644 index 00000000..eac76505 --- /dev/null +++ b/src/de/steamwar/bungeecore/sql/Statement.java @@ -0,0 +1,137 @@ +/* + This file is a part of the SteamWar software. + + Copyright (C) 2020 SteamWar.de-Serverteam + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + */ + +package de.steamwar.bungeecore.sql; + +import de.steamwar.bungeecore.BungeeCore; +import net.md_5.bungee.api.ProxyServer; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; + +public class Statement { + private static final List statements = new ArrayList<>(); + + private static Connection con; + private static String url; + private static String user; + private static String password; + + public static void connect(String url, String user, String password) { + Statement.url = url; + Statement.user = user; + Statement.password = password; + try { + con = DriverManager.getConnection(url + "?autoreconnect=true", user, password); + } catch (SQLException e) { + ProxyServer.getInstance().stop(); + throw new SecurityException("Could not start SQL-Connection", e); + } + } + + private static void reset(SQLException e) { + BungeeCore.get().getLogger().log(Level.WARNING, "SQL Exception thrown", e); + close(); + connect(url, user, password); + try { + for (Statement statement : statements) { + statement.init(); + } + } catch (SQLException ex) { + throw new SecurityException("Could not reprepare SQL Statements", ex); + } + } + + public static void close() { + for (Statement statement : statements) { + try { + statement.st.close(); + } catch (SQLException e) { + BungeeCore.get().getLogger().log(Level.INFO, "Could not close statement", e); + } + } + + try { + con.close(); + } catch (SQLException e) { + BungeeCore.log("Could not close SQL-Connection", e); + } + } + + private final String sql; + private PreparedStatement st; + + Statement(String sql) { + this.sql = sql; + statements.add(this); + try { + init(); + } catch (SQLException e) { + reset(e); + } + } + + private synchronized void init() throws SQLException { + st = con.prepareStatement(sql); + } + + T select(ResultSetUser user, Object... objects) { + return prepare(() -> { + ResultSet rs = st.executeQuery(); + T result = user.use(rs); + rs.close(); + return result; + }, objects); + } + + void update(Object... objects) { + prepare(st::executeUpdate, objects); + } + + private synchronized T prepare(SQLRunnable runnable, Object... objects) { + try { + setObjects(objects); + return runnable.run(); + } catch (SQLException e) { + reset(e); + try { + setObjects(objects); + return runnable.run(); + } catch (SQLException ex) { + throw new SecurityException("Could not execute SQL statement", ex); + } + } + } + + private void setObjects(Object... objects) throws SQLException { + for (int i = 0; i < objects.length; i++) { + st.setObject(i + 1, objects[i]); + } + } + + interface ResultSetUser { + T use(ResultSet rs) throws SQLException; + } + + private interface SQLRunnable { + T run() throws SQLException; + } +} diff --git a/src/de/steamwar/bungeecore/sql/SteamwarUser.java b/src/de/steamwar/bungeecore/sql/SteamwarUser.java index 00fd2218..0956d671 100644 --- a/src/de/steamwar/bungeecore/sql/SteamwarUser.java +++ b/src/de/steamwar/bungeecore/sql/SteamwarUser.java @@ -24,16 +24,14 @@ import de.steamwar.bungeecore.BungeeCore; import de.steamwar.bungeecore.Message; import de.steamwar.bungeecore.commands.WebregisterCommand; import de.steamwar.bungeecore.listeners.ConnectionListener; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Scanner; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.PendingConnection; import net.md_5.bungee.api.connection.ProxiedPlayer; +import java.io.IOException; import java.net.InetAddress; +import java.net.URL; import java.net.UnknownHostException; import java.sql.ResultSet; import java.sql.SQLException; @@ -41,18 +39,26 @@ import java.sql.Timestamp; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map; +import java.util.Scanner; import java.util.UUID; +import java.util.logging.Level; public class SteamwarUser { - private final int id; - private final UUID uuid; - private String userName; - private UserGroup userGroup; - private int team; - private boolean leader; - private Map punishments; - private String discordId; + + private static final Statement updateName = new Statement("UPDATE UserData SET UserName = ? WHERE id = ?"); + private static final Statement updateBedrock = new Statement("UPDATE UserData SET Bedrock = ? WHERE id = ?"); + private static final Statement insert = new Statement("INSERT INTO UserData (UUID, UserName, UserGroup) VALUES (?, ?, 'Member')"); + private static final Statement byUUID = new Statement("SELECT * FROM UserData WHERE UUID = ?"); + private static final Statement byName = new Statement("SELECT * FROM UserData WHERE lower(UserName) = ?"); + private static final Statement byID = new Statement("SELECT * FROM UserData WHERE id = ?"); + private static final Statement byDiscord = new Statement("SELECT * FROM UserData WHERE DiscordId = ?"); + private static final Statement updateTeam = new Statement("Update UserData SET Team = ? WHERE id = ?"); + private static final Statement updateDiscord = new Statement("Update UserData SET DiscordId = ? WHERE id = ?"); + private static final Statement deleteIPs = new Statement("DELETE FROM BannedUserIPs WHERE UserID = ?"); + private static final Statement updateLeader = new Statement("Update UserData SET Leader = ? WHERE id = ?"); + private static final Statement getPlaytime = new Statement("SELECT SUM(UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime)) as Playtime FROM Session WHERE UserID = ?"); + private static final Statement getFirstjoin = new Statement("SELECT MIN(StartTime) AS FirstJoin FROM Session WHERE UserID = ?"); private static final Map usersByName = new HashMap<>(); private static final Map usersByUUID = new HashMap<>(); @@ -62,6 +68,15 @@ public class SteamwarUser { private static final String API_URL = "https://api.mojang.com/users/profiles/minecraft/"; private static final JsonParser jsonParser = new JsonParser(); + private final int id; + private final UUID uuid; + private String userName; + private final UserGroup userGroup; + private int team; + private boolean leader; + private final Map punishments; + private String discordId; + static { try { LIXFEL_DE = InetAddress.getByAddress(new byte[]{(byte) 195, (byte) 201, (byte) 242, 43}); @@ -93,7 +108,7 @@ public class SteamwarUser { if(user != null){ String userName = connection.getName(); if(!user.userName.equals(userName)){ - SQL.update("UPDATE UserData SET UserName = ? WHERE id = ?", userName, user.id); + updateName.update(userName, user.id); WebregisterCommand.changeUsername(user.userName, userName); user.userName = userName; } @@ -105,7 +120,7 @@ public class SteamwarUser { } boolean bedrock = connection.getAddress().getAddress().equals(LIXFEL_DE); - SQL.update("UPDATE UserData SET Bedrock = ? WHERE id = ?", bedrock, user.id); + updateBedrock.update(bedrock, user.id); return user; } @@ -115,7 +130,7 @@ public class SteamwarUser { return user; } - UUID uuid = SteamwarUser.loadUUID(name); + UUID uuid = SteamwarUser.getUUIDofOfflinePlayer(name); if (uuid == null) { return null; } @@ -124,21 +139,28 @@ public class SteamwarUser { } private static SteamwarUser createUserInDatabase(UUID uuid, String name) { - SQL.update("INSERT INTO UserData (UUID, UserName, UserGroup) VALUES (?, ?, 'Member')", uuid.toString(), name); - return dbInit(SQL.select("SELECT * FROM UserData WHERE UUID = ?", uuid.toString())); + insert.update(uuid.toString(), name); + return get(uuid); } public static SteamwarUser get(String userName){ userName = userName.toLowerCase(); if(usersByName.containsKey(userName)) return usersByName.get(userName); - return dbInit(SQL.select("SELECT * FROM UserData WHERE lower(UserName) = ?", userName)); + return byName.select(rs -> { + if(rs.next()) + return new SteamwarUser(rs); + return null; + }, userName); } public static SteamwarUser get(UUID uuid){ if(usersByUUID.containsKey(uuid)) return usersByUUID.get(uuid); - return dbInit(SQL.select("SELECT * FROM UserData WHERE UUID = ?", uuid.toString())); + return byUUID.select(rs -> { + rs.next(); + return new SteamwarUser(rs); + }, uuid.toString()); } public static SteamwarUser get(ProxiedPlayer player){ @@ -148,13 +170,20 @@ public class SteamwarUser { public static SteamwarUser get(int id){ if(usersById.containsKey(id)) return usersById.get(id); - return dbInit(SQL.select("SELECT * FROM UserData WHERE id = ?", id)); + return byID.select(rs -> { + rs.next(); + return new SteamwarUser(rs); + }, id); } public static SteamwarUser get(Long discordId) { if(usersByDiscord.containsKey(discordId.toString())) return usersByDiscord.get(discordId.toString()); - return dbInit(SQL.select("SELECT * FROM UserData WHERE DiscordId = ?", discordId)); + return byDiscord.select(rs -> { + if(rs.next()) + return new SteamwarUser(rs); + return null; + }, discordId); } public static void clearCache(){ @@ -164,25 +193,20 @@ public class SteamwarUser { usersByDiscord.clear(); } - public static UUID loadUUID(String playerName) { + private static UUID getUUIDofOfflinePlayer(String playerName) { try { final URL url = new URL(API_URL + playerName); - return getUniqueIdFromString(jsonParser.parse(new Scanner(url.openConnection().getInputStream()).nextLine()).getAsJsonObject().get("id").getAsString()); - } catch (MalformedURLException e) { - e.printStackTrace(); + String uuid = jsonParser.parse(new Scanner(url.openConnection().getInputStream()).nextLine()).getAsJsonObject().get("id").getAsString(); + return UUID.fromString(uuid.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); } catch (IOException e) { - e.printStackTrace(); + BungeeCore.get().getLogger().log(Level.SEVERE, "Could not get offline player UUID", e); + return null; } - return null; - } - - private static UUID getUniqueIdFromString(String uuid) { - return UUID.fromString(uuid.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); } public void setTeam(int team){ this.team = team; - SQL.update("Update UserData SET Team = ? WHERE id = ?", team, id); + updateTeam.update(team, id); setLeader(false); } @@ -217,7 +241,7 @@ public class SteamwarUser { public void setDiscordId(String discordId) { usersByDiscord.remove(this.discordId); this.discordId = discordId; - SQL.update("Update UserData SET DiscordId = ? WHERE id = ?", discordId, id); + updateDiscord.update(discordId, id); if(discordId != null) { usersByDiscord.put(discordId, this); } @@ -227,7 +251,7 @@ public class SteamwarUser { if(!punishments.containsKey(Punishment.PunishmentType.Ban)) return false; if(!punishments.get(Punishment.PunishmentType.Ban).isCurrent()) { - SQL.update("DELETE FROM BannedUserIPs WHERE UserID = ?", id); + deleteIPs.update(id); punishments.remove(Punishment.PunishmentType.Ban); return false; } @@ -298,38 +322,20 @@ public class SteamwarUser { punishments.put(Punishment.PunishmentType.Mute, Punishment.createPunishment(id, from, Punishment.PunishmentType.Mute, muteReason, time, perma)); } - private static SteamwarUser dbInit(ResultSet rs){ - try { - if(!rs.next()) - return null; - return new SteamwarUser(rs); - } catch (SQLException e) { - throw new SecurityException(e); - } - } - public double getOnlinetime() { - ResultSet set = SQL.select("SELECT SUM(UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime)) as Playtime FROM Session WHERE UserID = ?", id); - try { - if(!set.next()) - return 0; - return set.getBigDecimal("Playtime").doubleValue(); - } catch (SQLException throwables) { - throw new SecurityException("Could not load Online Time", throwables); - } catch (NullPointerException e) { //When no Sessions are recorded - return 0; - } + return getPlaytime.select(rs -> { + if(rs.next()) + return rs.getBigDecimal("Playtime").doubleValue(); + return 0.0; + }, id); } public Timestamp getFirstjoin() { - ResultSet set = SQL.select("SELECT MIN(StartTime) AS FirstJoin FROM Session WHERE UserID = ?", id); - try { - if(!set.next()) - return null; - return set.getTimestamp("FirstJoin"); - } catch (SQLException throwables) { - throw new SecurityException("Could not load First Join"); - } + return getFirstjoin.select(rs -> { + if(rs.next()) + return rs.getTimestamp("FirstJoin"); + return null; + }, id); } public boolean isLeader() { @@ -338,6 +344,6 @@ public class SteamwarUser { public void setLeader(boolean leader) { this.leader = leader; - SQL.update("Update UserData SET Leader = ? WHERE id = ?", leader, id); + updateLeader.update(leader, id); } } diff --git a/src/de/steamwar/bungeecore/sql/Team.java b/src/de/steamwar/bungeecore/sql/Team.java index b5c083bd..f721fa5d 100644 --- a/src/de/steamwar/bungeecore/sql/Team.java +++ b/src/de/steamwar/bungeecore/sql/Team.java @@ -19,25 +19,31 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; -import static de.steamwar.bungeecore.sql.SQL.select; - public class Team { + + private static final Statement insert = new Statement("INSERT INTO Team (TeamKuerzel, TeamName) VALUES (?, ?)"); + private static final Statement delete = new Statement("UPDATE Team SET TeamDeleted = 1 WHERE TeamID = ?"); + private static final Statement update = new Statement("INSERT INTO Team (TeamID, TeamKuerzel, TeamName, TeamColor) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE TeamName = VALUES(TeamName), TeamKuerzel = VALUES(TeamKuerzel), TeamColor = VALUES(TeamColor)"); + private static final Statement getSize = new Statement("SELECT COUNT(id) FROM UserData WHERE Team = ?"); + private static final Statement getMembers = new Statement("SELECT id FROM UserData WHERE Team = ?"); + private static final Statement byId = new Statement("SELECT * FROM Team WHERE TeamID = ?"); + private static final Statement byName = new Statement("SELECT * FROM Team WHERE (lower(TeamName) = ? OR lower(TeamKuerzel) = ?) AND NOT TeamDeleted"); + private static final Statement all = new Statement("SELECT * FROM Team WHERE NOT TeamDeleted"); + + private static final List teamCache = new LinkedList<>(); + private static final Team pub = new Team(0, "PUB", "Öffentlich", "8"); + private final int teamId; private String teamKuerzel; private String teamName; private String teamColor; - private static final List teamCache = new LinkedList<>(); - private static final Team pub = new Team(0, "PUB", "Öffentlich", "8"); - private Team(int id, String kuerzel, String name, String color){ teamId = id; teamKuerzel = kuerzel; @@ -52,8 +58,8 @@ public class Team { this(rs.getInt("TeamID"), rs.getString("TeamKuerzel"), rs.getString("TeamName"), rs.getString("TeamColor")); } - public static void create(String kuerzel, String name, SteamwarUser user){ - SQL.update("INSERT INTO Team (TeamKuerzel, TeamName) VALUES (?, ?)", kuerzel, name); + public static void create(String kuerzel, String name){ + insert.update(kuerzel, name); } public static Team get(int id){ @@ -64,51 +70,38 @@ public class Team { for(Team team : teamCache) if(team.teamId == id) return team; - return load(select("SELECT * FROM Team WHERE TeamID = ?", id)); + return byId.select(rs -> { + rs.next(); + return new Team(rs); + }, id); } public static Team get(String name){ for(Team team : teamCache) - if(team.teamName.equalsIgnoreCase(name)) + if(team.teamName.equalsIgnoreCase(name) || team.teamKuerzel.equalsIgnoreCase(name)) return team; - for(Team team : teamCache) - if(team.teamKuerzel.equalsIgnoreCase(name)) - return team; - return load(select("SELECT * FROM Team WHERE (lower(TeamName) = ? OR lower(TeamKuerzel) = ?) AND NOT TeamDeleted", name.toLowerCase(), name.toLowerCase())); + return byName.select(rs -> { + if(rs.next()) + return new Team(rs); + return null; + }, name.toLowerCase(), name.toLowerCase()); } public static List getAll(){ clearCache(); - try{ - ResultSet rs = select("SELECT * FROM Team WHERE NOT TeamDeleted"); - if(rs == null) - return teamCache; - + return all.select(rs -> { while(rs.next()) new Team(rs); - } catch (SQLException e) { - BungeeCore.log("Could not get all Teams", e); - } - return teamCache; + return teamCache; + }); } public static void clearCache(){ teamCache.clear(); } - private static Team load(ResultSet dbteam){ - try { - if(!dbteam.next()) - return null; - return new Team(dbteam); - } catch (SQLException e) { - BungeeCore.log("Could not load Team", e); - return null; - } - } - private void updateDB(){ - SQL.update("INSERT INTO Team (TeamID, TeamKuerzel, TeamName, TeamColor) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE TeamName = VALUES(TeamName), TeamKuerzel = VALUES(TeamKuerzel), TeamColor = VALUES(TeamColor)", teamId, teamKuerzel, teamName, teamColor); + update.update(teamId, teamKuerzel, teamName, teamColor); } public int getTeamId() { @@ -143,33 +136,24 @@ public class Team { } public int size(){ - ResultSet rs = select("SELECT COUNT(id) FROM UserData WHERE Team = ?", teamId); - try { + return getSize.select(rs -> { rs.next(); return rs.getInt("COUNT(id)"); - }catch (SQLException e) { - BungeeCore.log("Could not get Teamsize", e); - return 1000; - } + }, teamId); } public void disband(SteamwarUser user){ user.setLeader(false); - SQL.update("UPDATE Team SET TeamDeleted = 1 WHERE TeamID = ?", teamId); + delete.update(teamId); teamCache.remove(this); } public List getMembers(){ - try{ - ResultSet memberlist = select("SELECT id FROM UserData WHERE Team = ?", teamId); + return getMembers.select(rs -> { List members = new ArrayList<>(); - while(memberlist.next()){ - members.add(memberlist.getInt("id")); - } + while(rs.next()) + members.add(rs.getInt("id")); return members; - }catch(SQLException e){ - BungeeCore.log("Could not get Teammembers", e); - } - return new ArrayList<>(); + }, teamId); } } diff --git a/src/de/steamwar/bungeecore/sql/TeamTeilnahme.java b/src/de/steamwar/bungeecore/sql/TeamTeilnahme.java index 2da396b9..68b1192e 100644 --- a/src/de/steamwar/bungeecore/sql/TeamTeilnahme.java +++ b/src/de/steamwar/bungeecore/sql/TeamTeilnahme.java @@ -19,55 +19,46 @@ package de.steamwar.bungeecore.sql; -import de.steamwar.bungeecore.BungeeCore; - import java.sql.ResultSet; -import java.sql.SQLException; import java.util.HashSet; import java.util.Set; public class TeamTeilnahme { private TeamTeilnahme(){} + private static final Statement insert = new Statement("INSERT INTO TeamTeilnahme (TeamID, EventID) VALUES (?, ?)"); + private static final Statement delete = new Statement("DELETE FROM TeamTeilnahme WHERE TeamID = ? AND EventID = ?"); + private static final Statement byEventTeam = new Statement("SELECT * FROM TeamTeilnahme WHERE TeamID = ? AND EventID = ?"); + private static final Statement byEvent = new Statement("SELECT * FROM TeamTeilnahme WHERE EventID = ?"); + private static final Statement byTeam = new Statement("SELECT * FROM TeamTeilnahme WHERE TeamID = ?"); + public static void teilnehmen(int teamID, int eventID){ - SQL.update("INSERT INTO TeamTeilnahme (TeamID, EventID) VALUES (?, ?)", teamID, eventID); + insert.update(teamID, eventID); } public static void notTeilnehmen(int teamID, int eventID){ - SQL.update("DELETE FROM TeamTeilnahme WHERE TeamID = ? AND EventID = ?", teamID, eventID); + delete.update(teamID, eventID); } public static boolean nimmtTeil(int teamID, int eventID){ - ResultSet rs = SQL.select("SELECT * FROM TeamTeilnahme WHERE TeamID = ? AND EventID = ?", teamID, eventID); - try{ - return rs.next(); - }catch (SQLException e){ - BungeeCore.log("Failed to load TeamTeilnahme", e); - throw new SecurityException(); - } + return byEventTeam.select(ResultSet::next, teamID, eventID); } public static Set getTeams(int eventID){ - Set teams = new HashSet<>(); - ResultSet rs = SQL.select("SELECT * FROM TeamTeilnahme WHERE EventID = ?", eventID); - try{ + return byEvent.select(rs -> { + Set teams = new HashSet<>(); while(rs.next()) teams.add(Team.get(rs.getInt("TeamID"))); - }catch (SQLException e){ - BungeeCore.log("Failed to load TeamTeilnahmen", e); - } - return teams; + return teams; + }, eventID); } public static Set getEvents(int teamID){ - Set events = new HashSet<>(); - ResultSet rs = SQL.select("SELECT * FROM TeamTeilnahme WHERE TeamID = ?", teamID); - try{ + return byTeam.select(rs -> { + Set events = new HashSet<>(); while(rs.next()) events.add(Event.get(rs.getInt("EventID"))); - }catch (SQLException e){ - BungeeCore.log("Failed to load TeamTeilnahmen", e); - } - return events; + return events; + }, teamID); } }