From 877aaea1dff3d682a6f7de240c121716780676f3 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 1 Feb 2022 13:29:07 +0100 Subject: [PATCH 1/9] WIP standalone SpigotCore --- .../src/de/steamwar/core/Core.java | 15 +- .../src/de/steamwar/sql/BauweltMember.java | 53 +++--- .../src/de/steamwar/sql/CheckedSchematic.java | 51 ++---- SpigotCore_Main/src/de/steamwar/sql/Elo.java | 11 +- .../src/de/steamwar/sql/Event.java | 29 ++-- .../src/de/steamwar/sql/EventFight.java | 38 ++--- .../src/de/steamwar/sql/Fight.java | 21 +-- .../src/de/steamwar/sql/FightPlayer.java | 4 +- .../src/de/steamwar/sql/NodeDownload.java | 5 +- .../src/de/steamwar/sql/Provider.java | 51 ++++++ .../src/de/steamwar/sql/SQLProvider.java | 157 ++++++++++++++++++ .../de/steamwar/sql/StandaloneProvider.java | 91 ++++++++++ .../src/de/steamwar/sql/Statement.java | 54 +++--- 13 files changed, 411 insertions(+), 169 deletions(-) create mode 100644 SpigotCore_Main/src/de/steamwar/sql/Provider.java create mode 100644 SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java create mode 100644 SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java diff --git a/SpigotCore_Main/src/de/steamwar/core/Core.java b/SpigotCore_Main/src/de/steamwar/core/Core.java index 8a47d30..7caba9d 100644 --- a/SpigotCore_Main/src/de/steamwar/core/Core.java +++ b/SpigotCore_Main/src/de/steamwar/core/Core.java @@ -31,6 +31,7 @@ import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import java.io.BufferedReader; +import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.logging.Level; @@ -66,6 +67,8 @@ public class Core extends JavaPlugin{ } private ErrorHandler errorHandler; + private File sqlConfig; + private boolean standalone; @Override public void onLoad() { @@ -74,6 +77,8 @@ public class Core extends JavaPlugin{ @Override public void onEnable() { + sqlConfig = new File(Core.getInstance().getDataFolder(), "MySQL.yml"); + standalone = !sqlConfig.exists(); errorHandler = new ErrorHandler(); Bukkit.getPluginManager().registerEvents(new PlayerJoinedEvent(), this); @@ -84,7 +89,7 @@ public class Core extends JavaPlugin{ AuthlibInjector.inject(); TinyProtocol.init(); try { - Bukkit.getLogger().log(Level.INFO, "Running on: " + new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec("hostname").getInputStream())).readLine()); + getLogger().log(Level.INFO, "Running on: " + new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec("hostname").getInputStream())).readLine()); } catch (IOException e) { throw new SecurityException("Could not load Hostname", e); } @@ -97,6 +102,14 @@ public class Core extends JavaPlugin{ Statement.close(); } + public static File sqlConfig() { + return instance.sqlConfig; + } + + public static boolean standalone() { + return instance.standalone; + } + public static Core getInstance() { return instance; } diff --git a/SpigotCore_Main/src/de/steamwar/sql/BauweltMember.java b/SpigotCore_Main/src/de/steamwar/sql/BauweltMember.java index 305aac5..564b916 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/BauweltMember.java +++ b/SpigotCore_Main/src/de/steamwar/sql/BauweltMember.java @@ -23,28 +23,11 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -public class BauweltMember{ - - 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 final boolean worldEdit; - private final boolean world; - - private static final List members = new ArrayList<>(); +public class BauweltMember { + private static final List memberCache = new ArrayList<>(); public static void clear() { - members.clear(); - } - - private BauweltMember(int ownerID, int memberID, boolean worldEdit, boolean world) { - bauweltID = ownerID; - this.memberID = memberID; - this.worldEdit = worldEdit; - this.world = world; - members.add(this); + memberCache.clear(); } public static BauweltMember getBauMember(UUID ownerID, UUID memberID){ @@ -52,14 +35,10 @@ public class BauweltMember{ } public static BauweltMember getBauMember(int ownerID, int memberID){ - for(BauweltMember member : members) - if(member.memberID == memberID) + for(BauweltMember member : memberCache) + if(member.getMemberID() == memberID) return member; - return getMember.select(rs -> { - if(!rs.next()) - return null; - return new BauweltMember(ownerID, memberID, rs.getBoolean("WorldEdit"), rs.getBoolean("World")); - }, ownerID, memberID); + return Provider.impl.getBauMember(ownerID, memberID); } public static List getMembers(UUID bauweltID){ @@ -67,12 +46,20 @@ public class BauweltMember{ } public static List getMembers(int bauweltID){ - return getMembers.select(rs -> { - List members = new ArrayList<>(); - while(rs.next()) - members.add(new BauweltMember(bauweltID, rs.getInt("MemberID"), rs.getBoolean("WorldEdit"), rs.getBoolean("World"))); - return members; - }, bauweltID); + return Provider.impl.getMembers(bauweltID); + } + + private final int bauweltID; + private final int memberID; + private final boolean worldEdit; + private final boolean world; + + public BauweltMember(int bauweltID, int memberID, boolean worldEdit, boolean world) { + this.bauweltID = bauweltID; + this.memberID = memberID; + this.worldEdit = worldEdit; + this.world = world; + memberCache.add(this); } public int getBauweltID() { diff --git a/SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java b/SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java index e130c70..3c19e4e 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java +++ b/SpigotCore_Main/src/de/steamwar/sql/CheckedSchematic.java @@ -20,45 +20,17 @@ package de.steamwar.sql; import java.sql.Timestamp; -import java.util.ArrayList; import java.util.List; import java.util.UUID; public class CheckedSchematic { - private static final Statement checkHistory = new Statement("SELECT * FROM CheckedSchematic WHERE NodeId IN (SELECT NodeId FROM SchematicNode WHERE NodeOwner = ?) AND DeclineReason != '' AND DeclineReason != 'Prüfvorgang abgebrochen' AND NodeId is not NULL ORDER BY EndTime DESC"); - private static final Statement nodeHistory = new Statement("SELECT * FROM CheckedSchematic WHERE NodeId = ? AND DeclineReason != '' AND DeclineReason != 'Prüfvorgang abgebrochen' ORDER BY EndTime DESC"); - - private final Integer node; - private final int validator; - private final Timestamp startTime; - private final Timestamp endTime; - private final String declineReason; - - private CheckedSchematic(int node, int validator, Timestamp startTime, Timestamp endTime, String declineReason){ - this.node = node; - this.validator = validator; - this.startTime = startTime; - this.endTime = endTime; - this.declineReason = declineReason; - } - public static List getLastDeclinedOfNode(SchematicNode node){ return getLastDeclinedOfNode(node.getId()); } public static List getLastDeclinedOfNode(int node){ - return nodeHistory.select(rs -> { - List lastDeclined = new ArrayList<>(); - while(rs.next()){ - int validator = rs.getInt("Validator"); - Timestamp startTime = rs.getTimestamp("StartTime"); - Timestamp endTime = rs.getTimestamp("EndTime"); - String declineReason = rs.getString("DeclineReason"); - lastDeclined.add(new CheckedSchematic(node, validator, startTime, endTime, declineReason)); - } - return lastDeclined; - }, node); + return Provider.impl.getLastDeclinedOfNode(node); } public static List getLastDeclined(UUID uuid){ @@ -66,12 +38,21 @@ public class CheckedSchematic { } public static List getLastDelined(int schemOwner){ - return checkHistory.select(rs -> { - List history = new ArrayList<>(); - while(rs.next()) - history.add(new CheckedSchematic(rs.getInt("NodeId"), rs.getInt("Validator"), rs.getTimestamp("StartTime"), rs.getTimestamp("EndTime"), rs.getString("DeclineReason"))); - return history; - }, schemOwner); + return Provider.impl.getLastDelined(schemOwner); + } + + private final Integer node; + private final int validator; + private final Timestamp startTime; + private final Timestamp endTime; + private final String declineReason; + + public CheckedSchematic(Integer node, int validator, Timestamp startTime, Timestamp endTime, String declineReason) { + this.node = node; + this.validator = validator; + this.startTime = startTime; + this.endTime = endTime; + this.declineReason = declineReason; } public int getValidator() { diff --git a/SpigotCore_Main/src/de/steamwar/sql/Elo.java b/SpigotCore_Main/src/de/steamwar/sql/Elo.java index 6fa6504..8eeeab7 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/Elo.java +++ b/SpigotCore_Main/src/de/steamwar/sql/Elo.java @@ -22,18 +22,11 @@ package de.steamwar.sql; public class Elo { private Elo(){} - private static final Statement get = new Statement("SELECT Elo FROM Elo WHERE UserID = ? AND GameMode = ?"); - private static final Statement set = new Statement("INSERT INTO Elo (UserID, GameMode, Elo) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Elo = VALUES(Elo)"); - public static int getElo(int userId, String gameMode){ - return get.select(rs -> { - if(rs.next()) - return rs.getInt("Elo"); - return 1000; - }, userId, gameMode); + return Provider.impl.getElo(userId, gameMode); } public static void setElo(int userId, String gameMode, int elo){ - set.update(userId, gameMode, elo); + Provider.impl.setElo(userId, gameMode, elo); } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/Event.java b/SpigotCore_Main/src/de/steamwar/sql/Event.java index 12ab5dd..a08ad8f 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/Event.java +++ b/SpigotCore_Main/src/de/steamwar/sql/Event.java @@ -19,13 +19,13 @@ package de.steamwar.sql; -import java.sql.ResultSet; -import java.sql.SQLException; import java.sql.Timestamp; public class Event { - private static final Statement get = new Statement("SELECT * FROM Event WHERE EventID = ?"); + public static Event get(int eventID){ + return Provider.impl.getEvent(eventID); + } private final int eventID; private final String eventName; @@ -35,21 +35,14 @@ public class Event { private final boolean publicSchemsOnly; private final boolean spectateSystem; - private Event(ResultSet rs) throws SQLException{ - this.eventID = rs.getInt("EventID"); - this.eventName = rs.getString("EventName"); - this.start = rs.getTimestamp("Start"); - this.end = rs.getTimestamp("End"); - this.maximumTeamMembers = rs.getInt("MaximumTeamMembers"); - this.publicSchemsOnly = rs.getBoolean("PublicSchemsOnly"); - this.spectateSystem = rs.getBoolean("SpectateSystem"); - } - - public static Event get(int eventID){ - return get.select(rs -> { - rs.next(); - return new Event(rs); - }, eventID); + public Event(int eventID, String eventName, Timestamp start, Timestamp end, int maximumTeamMembers, boolean publicSchemsOnly, boolean spectateSystem) { + this.eventID = eventID; + this.eventName = eventName; + this.start = start; + this.end = end; + this.maximumTeamMembers = maximumTeamMembers; + this.publicSchemsOnly = publicSchemsOnly; + this.spectateSystem = spectateSystem; } public int getEventID() { diff --git a/SpigotCore_Main/src/de/steamwar/sql/EventFight.java b/SpigotCore_Main/src/de/steamwar/sql/EventFight.java index 684cd7a..056e38a 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/EventFight.java +++ b/SpigotCore_Main/src/de/steamwar/sql/EventFight.java @@ -19,14 +19,13 @@ package de.steamwar.sql; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.util.function.BiConsumer; public class EventFight { - private static final Statement get = new Statement("SELECT * FROM EventFight WHERE FightID = ?"); - private static final Statement setResult = new Statement("UPDATE EventFight SET Ergebnis = ? WHERE FightID = ?"); - private static final Statement setFight = new Statement("UPDATE EventFight SET Fight = ? WHERE FightID = ?"); + public static EventFight get(int fightID) { + return Provider.impl.getEventFight(fightID); + } private final int eventID; private final int fightID; @@ -34,30 +33,27 @@ public class EventFight { private final int teamRed; private final int kampfleiter; private final int ergebnis; + private final BiConsumer setErgebnis; + private final BiConsumer setFight; - private EventFight(ResultSet rs) throws SQLException{ - this.eventID = rs.getInt("EventID"); - this.fightID = rs.getInt("FightID"); - this.teamBlue = rs.getInt("TeamBlue"); - this.teamRed = rs.getInt("TeamRed"); - this.kampfleiter = rs.getInt("Kampfleiter"); - this.ergebnis = rs.getInt("Ergebnis"); - } - - public static EventFight get(int fightID){ - return get.select(rs -> { - rs.next(); - return new EventFight(rs); - }, fightID); + public EventFight(int eventID, int fightID, int teamBlue, int teamRed, int kampfleiter, int ergebnis, BiConsumer setErgebnis, BiConsumer setFight) { + this.eventID = eventID; + this.fightID = fightID; + this.teamBlue = teamBlue; + this.teamRed = teamRed; + this.kampfleiter = kampfleiter; + this.ergebnis = ergebnis; + this.setErgebnis = setErgebnis; + this.setFight = setFight; } public void setErgebnis(int winner){ - setResult.update(winner, fightID); + setErgebnis.accept(this, winner); } public void setFight(int fight){ //Fight.FightID, not EventFight.FightID - setFight.update(fight, fightID); + setFight.accept(this, fight); } public int getTeamBlue() { diff --git a/SpigotCore_Main/src/de/steamwar/sql/Fight.java b/SpigotCore_Main/src/de/steamwar/sql/Fight.java index eb5cd30..4f46ca6 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/Fight.java +++ b/SpigotCore_Main/src/de/steamwar/sql/Fight.java @@ -27,32 +27,19 @@ import java.util.function.Consumer; public class Fight { private Fight(){} - private static final Statement create = new Statement("INSERT INTO Fight (GameMode, Server, StartTime, Duration, BlueLeader, RedLeader, BlueSchem, RedSchem, Win, WinCondition, ReplayLock) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); - private static final Statement lastId = new Statement("SELECT LAST_INSERT_ID() AS FightID"); - private static final Statement getReplay = new Statement("SELECT Replay FROM Fight WHERE FightID = ?"); - private static final Statement setReplay = new Statement("UPDATE Fight SET Replay = ? WHERE FightID = ?"); - public static int create(String gamemode, String server, Timestamp starttime, int duration, int blueleader, int redleader, Integer blueschem, Integer redschem, int win, String wincondition){ - return create(gamemode, server, starttime, duration, blueleader, redleader, blueschem, redschem, win, wincondition, Timestamp.from(Instant.now())); + return create(gamemode, server, starttime, duration, blueleader, redleader, blueschem, redschem, win, wincondition, Timestamp.from(Instant.now())); } public static int create(String gamemode, String server, Timestamp starttime, int duration, int blueleader, int redleader, Integer blueschem, Integer redschem, int win, String wincondition, Timestamp replayLock){ - create.update(gamemode, server, starttime, duration, blueleader, redleader, blueschem, redschem, win, wincondition, replayLock); - return lastId.select(rs -> { - rs.next(); - return rs.getInt("FightID"); - }); + return Provider.impl.createFight(gamemode, server, starttime, duration, blueleader, redleader, blueschem, redschem, win, wincondition, replayLock); } public static void getReplay(int fightID, Consumer reader) { - getReplay.select(rs -> { - rs.next(); - reader.accept(rs.getBinaryStream("Replay")); - return null; - }, fightID); + Provider.impl.getReplay(fightID, reader); } public static void setReplay(int fightID, InputStream data) { - setReplay.update(data, fightID); + Provider.impl.setReplay(fightID, data); } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/FightPlayer.java b/SpigotCore_Main/src/de/steamwar/sql/FightPlayer.java index 4814560..df65d54 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/FightPlayer.java +++ b/SpigotCore_Main/src/de/steamwar/sql/FightPlayer.java @@ -22,9 +22,7 @@ package de.steamwar.sql; public class FightPlayer { private FightPlayer(){} - private static final Statement create = new Statement("INSERT INTO FightPlayer (FightID, UserID, Team, Kit, Kills, IsOut) VALUES (?, ?, ?, ?, ?, ?)"); - public static void create(int fightID, int userID, boolean blue, String kit, int kills, boolean isOut){ - create.update(fightID, userID, blue ? 1 : 2, kit, kills, isOut); + Provider.impl.createFightPlayer(fightID, userID, blue, kit, kills, isOut); } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/NodeDownload.java b/SpigotCore_Main/src/de/steamwar/sql/NodeDownload.java index b19348d..2ffc7d9 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/NodeDownload.java +++ b/SpigotCore_Main/src/de/steamwar/sql/NodeDownload.java @@ -26,8 +26,7 @@ import java.security.NoSuchAlgorithmException; import java.time.Instant; public class NodeDownload { - - private static final Statement createLink = new Statement("INSERT INTO NodeDownload (NodeId, Link) VALUES (?, ?) ON DUPLICATE KEY UPDATE Link = VALUES(Link)"); + private NodeDownload() {} private static final String BASE = "https://steamwar.de/download.php?schem="; @@ -43,7 +42,7 @@ public class NodeDownload { digest.reset(); digest.update((Instant.now().toString() + schem.getOwner() + schem.getId()).getBytes()); String hash = BaseEncoding.base16().encode(digest.digest()); - createLink.update(schem.getId(), hash); + Provider.impl.createDownloadLink(schem.getId(), hash); return BASE + hash; } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/Provider.java b/SpigotCore_Main/src/de/steamwar/sql/Provider.java new file mode 100644 index 0000000..ff0a613 --- /dev/null +++ b/SpigotCore_Main/src/de/steamwar/sql/Provider.java @@ -0,0 +1,51 @@ +/* + * This file is a part of the SteamWar software. + * + * Copyright (C) 2022 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.sql; + +import de.steamwar.core.Core; + +import java.io.InputStream; +import java.sql.Timestamp; +import java.util.List; +import java.util.function.Consumer; + +public interface Provider { + Provider impl = Core.standalone() ? new StandaloneProvider() : new SQLProvider(); + + BauweltMember getBauMember(int ownerID, int memberID); + List getMembers(int bauweltID); + + List getLastDeclinedOfNode(int node); + List getLastDelined(int schemOwner); + + int getElo(int userId, String gameMode); + void setElo(int userId, String gameMode, int elo); + + Event getEvent(int eventID); + EventFight getEventFight(int fightID); + + int createFight(String gamemode, String server, Timestamp starttime, int duration, int blueleader, int redleader, Integer blueschem, Integer redschem, int win, String wincondition, Timestamp replayLock); + void getReplay(int fightID, Consumer reader); + void setReplay(int fightID, InputStream data); + + void createFightPlayer(int fightID, int userID, boolean blue, String kit, int kills, boolean isOut); + + void createDownloadLink(int nodeId, String hash); +} diff --git a/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java b/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java new file mode 100644 index 0000000..d21338e --- /dev/null +++ b/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java @@ -0,0 +1,157 @@ +/* + * This file is a part of the SteamWar software. + * + * Copyright (C) 2022 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.sql; + +import java.io.InputStream; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +public class SQLProvider implements Provider { + + private static final Statement getMember = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ? AND MemberID = ?"); + @Override + public BauweltMember getBauMember(int ownerID, int memberID) { + return getMember.select(rs -> rs.next() ? newBauweltMember(rs) : null, ownerID, memberID); + } + + private static final Statement getMembers = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ?"); + @Override + public List getMembers(int bauweltID) { + return getMembers.select(rs -> { + List members = new ArrayList<>(); + while(rs.next()) + members.add(newBauweltMember(rs)); + return members; + }, bauweltID); + } + + private BauweltMember newBauweltMember(ResultSet rs) throws SQLException { + return new BauweltMember(rs.getInt("BauweltID"), rs.getInt("MemberID"), rs.getBoolean("WorldEdit"), rs.getBoolean("World")); + } + + private static final Statement nodeHistory = new Statement("SELECT * FROM CheckedSchematic WHERE NodeId = ? AND DeclineReason != '' AND DeclineReason != 'Prüfvorgang abgebrochen' ORDER BY EndTime DESC"); + @Override + public List getLastDeclinedOfNode(int node) { + return nodeHistory.select(rs -> { + List lastDeclined = new ArrayList<>(); + while(rs.next()) + lastDeclined.add(newCheckedSchematic(rs)); + return lastDeclined; + }, node); + } + + private static final Statement checkHistory = new Statement("SELECT * FROM CheckedSchematic WHERE NodeId IN (SELECT NodeId FROM SchematicNode WHERE NodeOwner = ?) AND DeclineReason != '' AND DeclineReason != 'Prüfvorgang abgebrochen' AND NodeId is not NULL ORDER BY EndTime DESC"); + @Override + public List getLastDelined(int schemOwner) { + return checkHistory.select(rs -> { + List history = new ArrayList<>(); + while(rs.next()) + history.add(newCheckedSchematic(rs)); + return history; + }, schemOwner); + } + + private CheckedSchematic newCheckedSchematic(ResultSet rs) throws SQLException { + return new CheckedSchematic(rs.getInt("NodeId"), rs.getInt("Validator"), rs.getTimestamp("StartTime"), rs.getTimestamp("EndTime"), rs.getString("DeclineReason")); + } + + private static final Statement getElo = new Statement("SELECT Elo FROM Elo WHERE UserID = ? AND GameMode = ?"); + @Override + public int getElo(int userId, String gameMode) { + return getElo.select(rs -> { + if(rs.next()) + return rs.getInt("Elo"); + return 1000; + }, userId, gameMode); + } + + private static final Statement setElo = new Statement("INSERT INTO Elo (UserID, GameMode, Elo) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Elo = VALUES(Elo)"); + @Override + public void setElo(int userId, String gameMode, int elo) { + setElo.update(userId, gameMode, elo); + } + + private static final Statement getEvent = new Statement("SELECT * FROM Event WHERE EventID = ?"); + @Override + public Event getEvent(int eventID) { + return getEvent.select(rs -> { + rs.next(); + return new Event(rs.getInt("EventID"), rs.getString("EventName"), rs.getTimestamp("Start"), rs.getTimestamp("End"), rs.getInt("MaximumTeamMembers"), rs.getBoolean("PublicSchemsOnly"), rs.getBoolean("SpectateSystem")); + }, eventID); + } + + private static final Statement getEventFight = new Statement("SELECT * FROM EventFight WHERE FightID = ?"); + private static final Statement setEventFightResult = new Statement("UPDATE EventFight SET Ergebnis = ? WHERE FightID = ?"); + private static final Statement setEventFightFightID = new Statement("UPDATE EventFight SET Fight = ? WHERE FightID = ?"); + @Override + public EventFight getEventFight(int fightID) { + return getEventFight.select(rs -> { + rs.next(); + return new EventFight( + rs.getInt("EventID"), rs.getInt("FightID"), rs.getInt("TeamBlue"), rs.getInt("TeamRed"), rs.getInt("Kampfleiter"), rs.getInt("Ergebnis"), + (eventFight, winner) -> setEventFightResult.update(winner, eventFight.getFightID()), + (eventFight, fight) -> setEventFightFightID.update(fight, eventFight.getFightID()) + ); + }, fightID); + } + + private static final Statement createFight = new Statement("INSERT INTO Fight (GameMode, Server, StartTime, Duration, BlueLeader, RedLeader, BlueSchem, RedSchem, Win, WinCondition, ReplayLock) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + private static final Statement getLastFightID = new Statement("SELECT LAST_INSERT_ID() AS FightID"); + @Override + public int createFight(String gamemode, String server, Timestamp starttime, int duration, int blueleader, int redleader, Integer blueschem, Integer redschem, int win, String wincondition, Timestamp replayLock) { + createFight.update(gamemode, server, starttime, duration, blueleader, redleader, blueschem, redschem, win, wincondition, replayLock); + return getLastFightID.select(rs -> { + rs.next(); + return rs.getInt("FightID"); + }); + } + + private static final Statement getReplay = new Statement("SELECT Replay FROM Fight WHERE FightID = ?"); + @Override + public void getReplay(int fightID, Consumer reader) { + getReplay.select(rs -> { + rs.next(); + reader.accept(rs.getBinaryStream("Replay")); + return null; + }, fightID); + } + + private static final Statement setReplay = new Statement("UPDATE Fight SET Replay = ? WHERE FightID = ?"); + @Override + public void setReplay(int fightID, InputStream data) { + setReplay.update(data, fightID); + } + + private static final Statement create = new Statement("INSERT INTO FightPlayer (FightID, UserID, Team, Kit, Kills, IsOut) VALUES (?, ?, ?, ?, ?, ?)"); + @Override + public void createFightPlayer(int fightID, int userID, boolean blue, String kit, int kills, boolean isOut) { + create.update(fightID, userID, blue ? 1 : 2, kit, kills, isOut); + } + + private static final Statement createLink = new Statement("INSERT INTO NodeDownload (NodeId, Link) VALUES (?, ?) ON DUPLICATE KEY UPDATE Link = VALUES(Link)"); + @Override + public void createDownloadLink(int nodeId, String hash) { + createLink.update(nodeId, hash); + } +} diff --git a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java new file mode 100644 index 0000000..2fa3b2d --- /dev/null +++ b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java @@ -0,0 +1,91 @@ +/* + * This file is a part of the SteamWar software. + * + * Copyright (C) 2022 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.sql; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; + +import java.io.InputStream; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +public class StandaloneProvider implements Provider { + @Override + public BauweltMember getBauMember(int ownerID, int memberID) { + OfflinePlayer player = Bukkit.getOfflinePlayer(SteamwarUser.get(memberID).getUUID()); + return new BauweltMember(ownerID, memberID, player.isOp(), player.isOp()); + } + + @Override + public List getMembers(int bauweltID) { + return Bukkit.getOnlinePlayers().stream().map(player -> getBauMember(bauweltID, SteamwarUser.get(player.getUniqueId()).getId())).collect(Collectors.toList()); + } + + @Override + public List getLastDeclinedOfNode(int node) { + return new ArrayList<>(); + } + + @Override + public List getLastDelined(int schemOwner) { + return new ArrayList<>(); + } + + @Override + public int getElo(int userId, String gameMode) { + return 1000; + } + + @Override + public void setElo(int userId, String gameMode, int elo) {} + + @Override + public Event getEvent(int eventID) { + return new Event(eventID, "DummyEvent", Timestamp.from(Instant.now()), Timestamp.from(Instant.now()), 6, false, false); + } + + @Override + public EventFight getEventFight(int fightID) { + return new EventFight(0, fightID, 0, 0, 0, 0, (eventFight, winner) -> {}, (eventFight, fightId) -> {}); + } + + @Override + public int createFight(String gamemode, String server, Timestamp starttime, int duration, int blueleader, int redleader, Integer blueschem, Integer redschem, int win, String wincondition, Timestamp replayLock) { + return 0; + } + + @Override + public void getReplay(int fightID, Consumer reader) {} + + @Override + public void setReplay(int fightID, InputStream data) {} + + @Override + public void createFightPlayer(int fightID, int userID, boolean blue, String kit, int kills, boolean isOut) {} + + @Override + public void createDownloadLink(int nodeId, String hash) {} + + +} diff --git a/SpigotCore_Main/src/de/steamwar/sql/Statement.java b/SpigotCore_Main/src/de/steamwar/sql/Statement.java index 48719e6..13eec67 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/Statement.java +++ b/SpigotCore_Main/src/de/steamwar/sql/Statement.java @@ -40,7 +40,7 @@ public class Statement { private static final List statements = new ArrayList<>(); static { - File file = new File(Core.getInstance().getDataFolder(), "MySQL.yml"); + File file = Core.sqlConfig(); YamlConfiguration config = YamlConfiguration.loadConfiguration(file); if(!file.exists()) @@ -63,10 +63,12 @@ public class Statement { public static void close() { for (Statement statement : statements) { - try { - statement.st.close(); - } catch (SQLException e) { - Core.getInstance().getLogger().log(Level.INFO, "Could not close statement", e); + if (statement.st != null) { + try { + statement.st.close(); + } catch (SQLException e) { + Core.getInstance().getLogger().log(Level.INFO, "Could not close statement", e); + } } } @@ -80,14 +82,6 @@ public class Statement { private static void reset() { close(); connect(); - - try { - for (Statement statement : statements) { - statement.init(); - } - } catch (SQLException ex) { - throw new SecurityException("Could not reprepare SQL Statements", ex); - } } public static boolean connectionStable() { @@ -101,31 +95,22 @@ public class Statement { private final String sql; private PreparedStatement st; - Statement(String sql) { + public Statement(String sql) { this.sql = sql; - try { - init(); - } catch (SQLException e) { - throw new SecurityException("Could not init statement", e); - } statements.add(this); } - private synchronized void init() throws SQLException { - st = con.prepareStatement(sql); - } - - T select(ResultSetUser user, Object... objects) { + public T select(ResultSetUser user, Object... objects) { return prepare(() -> { - ResultSet rs = st.executeQuery(); + ResultSet rs = getSt().executeQuery(); T result = user.use(rs); rs.close(); return result; }, objects); } - void update(Object... objects) { - prepare(st::executeUpdate, objects); + public void update(Object... objects) { + prepare(getSt()::executeUpdate, objects); } private synchronized T prepare(SQLRunnable runnable, Object... objects) { @@ -143,13 +128,24 @@ public class Statement { } } + private PreparedStatement getSt() { + if(st == null) { + try { + st = con.prepareStatement(sql); + } catch (SQLException e) { + throw new SecurityException("Could not prepare statement", e); + } + } + return st; + } + private void setObjects(Object... objects) throws SQLException { for (int i = 0; i < objects.length; i++) { - st.setObject(i + 1, objects[i]); + getSt().setObject(i + 1, objects[i]); } } - interface ResultSetUser { + public interface ResultSetUser { T use(ResultSet rs) throws SQLException; } -- 2.39.5 From 846147b5213da47c95b32103edd1fb2bdb24c76d Mon Sep 17 00:00:00 2001 From: Lixfel Date: Tue, 1 Feb 2022 16:36:19 +0100 Subject: [PATCH 2/9] WIP Standalone SpigotCore --- .../src/de/steamwar/sql/EventFight.java | 16 +- .../src/de/steamwar/sql/NodeMember.java | 46 +--- .../src/de/steamwar/sql/PersonalKit.java | 106 ++++---- .../src/de/steamwar/sql/Provider.java | 32 +++ .../src/de/steamwar/sql/Punishment.java | 53 ++-- .../src/de/steamwar/sql/SQLProvider.java | 226 +++++++++++++++++- .../src/de/steamwar/sql/SWException.java | 4 +- .../de/steamwar/sql/StandaloneProvider.java | 110 ++++++++- .../src/de/steamwar/sql/SteamwarUser.java | 45 +--- SpigotCore_Main/src/de/steamwar/sql/Team.java | 24 +- .../src/de/steamwar/sql/TeamTeilnahme.java | 54 ----- .../src/de/steamwar/sql/UserConfig.java | 14 +- 12 files changed, 455 insertions(+), 275 deletions(-) delete mode 100644 SpigotCore_Main/src/de/steamwar/sql/TeamTeilnahme.java diff --git a/SpigotCore_Main/src/de/steamwar/sql/EventFight.java b/SpigotCore_Main/src/de/steamwar/sql/EventFight.java index 056e38a..c60e227 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/EventFight.java +++ b/SpigotCore_Main/src/de/steamwar/sql/EventFight.java @@ -19,8 +19,6 @@ package de.steamwar.sql; -import java.util.function.BiConsumer; - public class EventFight { public static EventFight get(int fightID) { @@ -33,27 +31,23 @@ public class EventFight { private final int teamRed; private final int kampfleiter; private final int ergebnis; - private final BiConsumer setErgebnis; - private final BiConsumer setFight; - public EventFight(int eventID, int fightID, int teamBlue, int teamRed, int kampfleiter, int ergebnis, BiConsumer setErgebnis, BiConsumer setFight) { + public EventFight(int eventID, int fightID, int teamBlue, int teamRed, int kampfleiter, int ergebnis) { this.eventID = eventID; this.fightID = fightID; this.teamBlue = teamBlue; this.teamRed = teamRed; this.kampfleiter = kampfleiter; this.ergebnis = ergebnis; - this.setErgebnis = setErgebnis; - this.setFight = setFight; } - public void setErgebnis(int winner){ - setErgebnis.accept(this, winner); + public void setErgebnis(int winner) { + Provider.impl.setEventFightResult(this, winner); } - public void setFight(int fight){ + public void setFight(int fight) { //Fight.FightID, not EventFight.FightID - setFight.accept(this, fight); + Provider.impl.setEventFightFightID(this, fight); } public int getTeamBlue() { diff --git a/SpigotCore_Main/src/de/steamwar/sql/NodeMember.java b/SpigotCore_Main/src/de/steamwar/sql/NodeMember.java index cca8bd3..e52298a 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/NodeMember.java +++ b/SpigotCore_Main/src/de/steamwar/sql/NodeMember.java @@ -19,56 +19,36 @@ package de.steamwar.sql; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashSet; import java.util.Set; +import java.util.function.Consumer; public class NodeMember { - private static final Statement getNodeMember = new Statement("SELECT * FROM NodeMember WHERE NodeId = ? AND UserId = ?"); - private static final Statement getNodeMembers = new Statement("SELECT * FROM NodeMember WHERE NodeId = ?"); - private static final Statement getSchematics = new Statement("SELECT * FROM NodeMember WHERE UserId = ?"); - private static final Statement createNodeMember = new Statement("INSERT INTO NodeMember (NodeId, UserId) VALUES (?, ?)"); - private static final Statement deleteNodeMember = new Statement("DELETE FROM NodeMember WHERE NodeId = ? AND UserId = ?"); - public static NodeMember getNodeMember(int node, int member) { - return getNodeMember.select(rs -> { - if(!rs.next()) - return null; - return new NodeMember(rs); - }, node, member); + return Provider.impl.getNodeMember(node, member); } public static Set getNodeMembers(int node) { - return getNodeMembers.select(rs -> { - Set members = new HashSet<>(); - while (rs.next()) - members.add(new NodeMember(rs)); - return members; - }, node); + return Provider.impl.getNodeMembers(node); } public static Set getSchematics(int member) { - return getSchematics.select(rs -> { - Set members = new HashSet<>(); - while (rs.next()) - members.add(new NodeMember(rs)); - return members; - }, member); + return Provider.impl.getMemberSchematics(member); } public static NodeMember createNodeMember(int node, int member) { - createNodeMember.update(node, member); + Provider.impl.createNodeMember(node, member); return getNodeMember(node, member); } - final int node; - final int member; + private final int node; + private final int member; + private final Consumer delete; - private NodeMember(ResultSet set) throws SQLException { - node = set.getInt("NodeId"); - member = set.getInt("UserId"); + public NodeMember(int node, int member, Consumer delete) { + this.node = node; + this.member = member; + this.delete = delete; } public int getNode() { @@ -80,6 +60,6 @@ public class NodeMember { } public void delete() { - deleteNodeMember.update(node, member); + delete.accept(this); } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java b/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java index 7e9663a..b267e5c 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java +++ b/SpigotCore_Main/src/de/steamwar/sql/PersonalKit.java @@ -23,19 +23,31 @@ import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.inventory.ItemStack; import java.io.StringReader; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; import java.util.List; import java.util.Objects; public class PersonalKit { - private static final Statement getKits = new Statement("SELECT * FROM PersonalKit WHERE UserID = ? AND GameMode = ?"); - private static final Statement getKit = new Statement("SELECT * FROM PersonalKit WHERE UserID = ? AND GameMode = ? AND Name = ?"); - private static final Statement getKitInUse = new Statement("SELECT * FROM PersonalKit WHERE UserID = ? AND GameMode = ? AND InUse = 1"); - private static final Statement delete = new Statement("DELETE FROM `PersonalKit` WHERE UserID = ? AND GameMode = ? AND Name = ?"); - private static final Statement update = new Statement("INSERT INTO PersonalKit (UserID, GameMode, Name, Inventory, Armor, InUse) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE Inventory = VALUES(Inventory), Armor = VALUES(Armor), Name = VALUES(Name), InUse = VALUES(InUse)"); + public static List get(int userID, String gamemode){ + return Provider.impl.getKits(userID, gamemode); + } + + public static PersonalKit get(int userID, String gamemode, String name) { + return Provider.impl.getKit(userID, gamemode, name); + } + + public static PersonalKit create(int userID, String gamemode, String name, ItemStack[] inventory, ItemStack[] armor){ + if(armor == null) { + armor = new ItemStack[]{null, null, null, null}; + } + PersonalKit kit = new PersonalKit(userID, name, gamemode, saveInvConfig("Inventory", inventory), saveInvConfig("Armor", armor), true); + Provider.impl.updateKit(kit); + return kit; + } + + public static PersonalKit getKitInUse(int userID, String gamemode) { + return Provider.impl.getKitInUse(userID, gamemode); + } private final int userID; private String name; @@ -44,49 +56,13 @@ public class PersonalKit { private String armor; private boolean inUse; - private PersonalKit(ResultSet rs) throws SQLException { - userID = rs.getInt("UserID"); - gamemode = rs.getString("GameMode"); - inventory = rs.getString("Inventory"); - armor = rs.getString("Armor"); - name = rs.getString("Name"); - inUse = rs.getBoolean("InUse"); - } - - public static List get(int userID, String gamemode){ - return getKits.select(rs -> { - List list = new ArrayList<>(); - while (rs.next()) - list.add(new PersonalKit(rs)); - return list; - }, userID, gamemode); - } - - public static PersonalKit get(int userID, String gamemode, String name) { - return getKit.select(rs -> { - if(rs.next()) - return new PersonalKit(rs); - return null; - }, userID, gamemode, name); - } - - public static PersonalKit create(int userID, String gamemode, String name, ItemStack[] inventory, ItemStack[] armor){ - if(armor == null) { - armor = new ItemStack[]{null, null, null, null}; - } - update.update(userID, gamemode, name, saveInvConfig("Inventory", inventory), saveInvConfig("Armor", armor), true); - return get(userID, gamemode, name); - } - - public static PersonalKit getKitInUse(int userID, String gamemode) { - return getKitInUse.select(rs -> { - if(!rs.next()) - return null; - PersonalKit kit = new PersonalKit(rs); - while (rs.next()) - new PersonalKit(rs).setUse(false); //TODO: Violation of integrity, should not be necessary? - return kit; - }, userID, gamemode); + public PersonalKit(int userID, String name, String gamemode, String inventory, String armor, boolean inUse) { + this.userID = userID; + this.name = name; + this.gamemode = gamemode; + this.inventory = inventory; + this.armor = armor; + this.inUse = inUse; } public ItemStack[] getInventory(){ @@ -107,6 +83,18 @@ public class PersonalKit { return name; } + public String getGamemode() { + return gamemode; + } + + public String getRawInventory() { + return inventory; + } + + public String getRawArmor() { + return armor; + } + public boolean isInUse() { return inUse; } @@ -120,32 +108,32 @@ public class PersonalKit { private void setUse(boolean inUse) { this.inUse = inUse; - updateDB(); + Provider.impl.updateKit(this); } public void setName(String name) { this.name = name; - updateDB(); + Provider.impl.updateKit(this); } public void setInventory(ItemStack[] inventory) { this.inventory = saveInvConfig("Inventory", inventory); - updateDB(); + Provider.impl.updateKit(this); } public void setArmor(ItemStack[] armor) { this.armor = saveInvConfig("Armor", armor); - updateDB(); + Provider.impl.updateKit(this); } public void setContainer(ItemStack[] inventory, ItemStack[] armor) { this.armor = saveInvConfig("Armor", armor); this.inventory = saveInvConfig("Inventory", inventory); - updateDB(); + Provider.impl.updateKit(this); } public void delete() { - delete.update(userID, gamemode, name); + Provider.impl.deleteKit(this); } private static String saveInvConfig(String name, ItemStack[] inv) { @@ -154,8 +142,4 @@ public class PersonalKit { return armorConfig.saveToString(); } - - private void updateDB() { - update.update(userID, gamemode, name, inventory, armor, inUse); - } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/Provider.java b/SpigotCore_Main/src/de/steamwar/sql/Provider.java index ff0a613..962bdba 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/Provider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/Provider.java @@ -24,6 +24,9 @@ import de.steamwar.core.Core; import java.io.InputStream; import java.sql.Timestamp; import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import java.util.function.Consumer; public interface Provider { @@ -40,6 +43,8 @@ public interface Provider { Event getEvent(int eventID); EventFight getEventFight(int fightID); + void setEventFightResult(EventFight fight, int winner); + void setEventFightFightID(EventFight fight, int fightID); int createFight(String gamemode, String server, Timestamp starttime, int duration, int blueleader, int redleader, Integer blueschem, Integer redschem, int win, String wincondition, Timestamp replayLock); void getReplay(int fightID, Consumer reader); @@ -48,4 +53,31 @@ public interface Provider { void createFightPlayer(int fightID, int userID, boolean blue, String kit, int kills, boolean isOut); void createDownloadLink(int nodeId, String hash); + + NodeMember getNodeMember(int node, int member); + Set getNodeMembers(int node); + Set getMemberSchematics(int member); + void createNodeMember(int node, int member); + + List getKits(int userID, String gamemode); + PersonalKit getKit(int userID, String gamemode, String name); + void updateKit(PersonalKit kit); + void deleteKit(PersonalKit kit); + PersonalKit getKitInUse(int userID, String gamemode); + + Punishment getPunishmentOfPlayer(int user, Punishment.PunishmentType type); + Map getPunishmentsOfPlayer(int user); + + SteamwarUser getUserByName(String userName); + SteamwarUser getUserByUUID(UUID uuid); + SteamwarUser getUserByID(int id); + + void logException(String server, String message, String stacktrace); + + Team getTeam(int id); + List getTeamMembers(Team team); + + String getConfig(int player, String config); + void updatePlayerConfig(int id, String config, String value); + void removePlayerConfig(int id, String config); } diff --git a/SpigotCore_Main/src/de/steamwar/sql/Punishment.java b/SpigotCore_Main/src/de/steamwar/sql/Punishment.java index 003a8b6..f97285c 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/Punishment.java +++ b/SpigotCore_Main/src/de/steamwar/sql/Punishment.java @@ -22,33 +22,21 @@ package de.steamwar.sql; import lombok.AllArgsConstructor; import lombok.Getter; -import java.sql.ResultSet; -import java.sql.SQLException; import java.sql.Timestamp; import java.time.format.DateTimeFormatter; -import java.util.*; +import java.util.Date; +import java.util.Map; import java.util.function.Consumer; 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)"); public static Punishment getPunishmentOfPlayer(int user, PunishmentType type) { - return getPunishment.select(rs -> { - if (rs.next()) - return new Punishment(rs); - return null; - }, user, type.name()); + return Provider.impl.getPunishmentOfPlayer(user, type); } public static Map getPunishmentsOfPlayer(int user) { - return getPunishments.select(rs -> { - Map punishments = new HashMap<>(); - while (rs.next()) - punishments.put(PunishmentType.valueOf(rs.getString("Type")), new Punishment(rs)); - return punishments; - }, user); + return Provider.impl.getPunishmentsOfPlayer(user); } public static boolean isPunished(SteamwarUser user, Punishment.PunishmentType type, Consumer callback) { @@ -61,24 +49,23 @@ public class Punishment { } } - private final Timestamp startTime; - private Timestamp endTime; - private final PunishmentType type; - private final int user; - private final int id; - private String reason; - private final int punisher; - private boolean perma; - private Punishment(ResultSet set) throws SQLException { - user = set.getInt("UserId"); - reason = set.getString("Reason"); - type = PunishmentType.valueOf(set.getString("Type")); - startTime = set.getTimestamp("StartTime"); - endTime = set.getTimestamp("EndTime"); - punisher = set.getInt("Punisher"); - perma = set.getBoolean("Perma"); - id = set.getInt("PunishmentId"); + private final int user; + private final int punisher; + private final PunishmentType type; + private final Timestamp startTime; + private final Timestamp endTime; + private final boolean perma; + private final String reason; + + public Punishment(int user, int punisher, PunishmentType type, Timestamp startTime, Timestamp endTime, boolean perma, String reason) { + this.user = user; + this.punisher = punisher; + this.type = type; + this.startTime = startTime; + this.endTime = endTime; + this.perma = perma; + this.reason = reason; } public Timestamp getStartTime() { diff --git a/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java b/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java index d21338e..da12849 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java @@ -23,22 +23,21 @@ import java.io.InputStream; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.List; +import java.util.*; import java.util.function.Consumer; public class SQLProvider implements Provider { - private static final Statement getMember = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ? AND MemberID = ?"); + private static final Statement getBauMember = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ? AND MemberID = ?"); @Override public BauweltMember getBauMember(int ownerID, int memberID) { - return getMember.select(rs -> rs.next() ? newBauweltMember(rs) : null, ownerID, memberID); + return getBauMember.select(rs -> rs.next() ? newBauweltMember(rs) : null, ownerID, memberID); } - private static final Statement getMembers = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ?"); + private static final Statement getBauMembers = new Statement("SELECT * FROM BauweltMember WHERE BauweltID = ?"); @Override public List getMembers(int bauweltID) { - return getMembers.select(rs -> { + return getBauMembers.select(rs -> { List members = new ArrayList<>(); while(rs.next()) members.add(newBauweltMember(rs)); @@ -102,20 +101,26 @@ public class SQLProvider implements Provider { } private static final Statement getEventFight = new Statement("SELECT * FROM EventFight WHERE FightID = ?"); - private static final Statement setEventFightResult = new Statement("UPDATE EventFight SET Ergebnis = ? WHERE FightID = ?"); - private static final Statement setEventFightFightID = new Statement("UPDATE EventFight SET Fight = ? WHERE FightID = ?"); @Override public EventFight getEventFight(int fightID) { return getEventFight.select(rs -> { rs.next(); - return new EventFight( - rs.getInt("EventID"), rs.getInt("FightID"), rs.getInt("TeamBlue"), rs.getInt("TeamRed"), rs.getInt("Kampfleiter"), rs.getInt("Ergebnis"), - (eventFight, winner) -> setEventFightResult.update(winner, eventFight.getFightID()), - (eventFight, fight) -> setEventFightFightID.update(fight, eventFight.getFightID()) - ); + return new EventFight(rs.getInt("EventID"), rs.getInt("FightID"), rs.getInt("TeamBlue"), rs.getInt("TeamRed"), rs.getInt("Kampfleiter"), rs.getInt("Ergebnis")); }, fightID); } + private static final Statement setEventFightResult = new Statement("UPDATE EventFight SET Ergebnis = ? WHERE FightID = ?"); + @Override + public void setEventFightResult(EventFight fight, int winner) { + setEventFightResult.update(winner, fight.getFightID()); + } + + private static final Statement setEventFightFightID = new Statement("UPDATE EventFight SET Fight = ? WHERE FightID = ?"); + @Override + public void setEventFightFightID(EventFight fight, int fightID) { + setEventFightFightID.update(fight, fight.getFightID()); + } + private static final Statement createFight = new Statement("INSERT INTO Fight (GameMode, Server, StartTime, Duration, BlueLeader, RedLeader, BlueSchem, RedSchem, Win, WinCondition, ReplayLock) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); private static final Statement getLastFightID = new Statement("SELECT LAST_INSERT_ID() AS FightID"); @Override @@ -154,4 +159,199 @@ public class SQLProvider implements Provider { public void createDownloadLink(int nodeId, String hash) { createLink.update(nodeId, hash); } + + private static final Statement getNodeMember = new Statement("SELECT * FROM NodeMember WHERE NodeId = ? AND UserId = ?"); + @Override + public NodeMember getNodeMember(int node, int member) { + return getNodeMember.select(rs -> { + if(!rs.next()) + return null; + return newNodeMember(rs); + }, node, member); + } + + private static final Statement getNodeMembers = new Statement("SELECT * FROM NodeMember WHERE NodeId = ?"); + @Override + public Set getNodeMembers(int node) { + return getNodeMembers.select(rs -> { + Set members = new HashSet<>(); + while (rs.next()) + members.add(newNodeMember(rs)); + return members; + }, node); + } + + private static final Statement getSchematics = new Statement("SELECT * FROM NodeMember WHERE UserId = ?"); + @Override + public Set getMemberSchematics(int member) { + return getSchematics.select(rs -> { + Set members = new HashSet<>(); + while (rs.next()) + members.add(newNodeMember(rs)); + return members; + }, member); + } + + private static final Statement deleteNodeMember = new Statement("DELETE FROM NodeMember WHERE NodeId = ? AND UserId = ?"); + private NodeMember newNodeMember(ResultSet rs) throws SQLException { + return new NodeMember(rs.getInt("NodeId"), rs.getInt("UserId"), member -> deleteNodeMember.update(member.getNode(), member.getMember())); + } + + private static final Statement createNodeMember = new Statement("INSERT INTO NodeMember (NodeId, UserId) VALUES (?, ?)"); + @Override + public void createNodeMember(int node, int member) { + createNodeMember.update(node, member); + } + + private static final Statement getKits = new Statement("SELECT * FROM PersonalKit WHERE UserID = ? AND GameMode = ?"); + @Override + public List getKits(int userID, String gamemode) { + return getKits.select(rs -> { + List list = new ArrayList<>(); + while (rs.next()) + list.add(newPersonalKit(rs)); + return list; + }, userID, gamemode); + } + + private static final Statement getKit = new Statement("SELECT * FROM PersonalKit WHERE UserID = ? AND GameMode = ? AND Name = ?"); + @Override + public PersonalKit getKit(int userID, String gamemode, String name) { + return getKit.select(rs -> { + if(rs.next()) + return newPersonalKit(rs); + return null; + }, userID, gamemode, name); + } + + private PersonalKit newPersonalKit(ResultSet rs) throws SQLException { + return new PersonalKit(rs.getInt("UserID"), rs.getString("Name"), rs.getString("GameMode"), rs.getString("Inventory"), rs.getString("Armor"), rs.getBoolean("InUse")); + } + + private static final Statement updateKit = new Statement("INSERT INTO PersonalKit (UserID, GameMode, Name, Inventory, Armor, InUse) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE Inventory = VALUES(Inventory), Armor = VALUES(Armor), Name = VALUES(Name), InUse = VALUES(InUse)"); + @Override + public void updateKit(PersonalKit kit) { + updateKit.update(kit.getUserID(), kit.getGamemode(), kit.getName(), kit.getRawInventory(), kit.getRawArmor(), kit.isInUse()); + } + + private static final Statement deleteKit = new Statement("DELETE FROM `PersonalKit` WHERE UserID = ? AND GameMode = ? AND Name = ?"); + @Override + public void deleteKit(PersonalKit kit) { + deleteKit.update(kit.getUserID(), kit.getGamemode(), kit.getName()); + } + + private static final Statement getKitInUse = new Statement("SELECT * FROM PersonalKit WHERE UserID = ? AND GameMode = ? AND InUse = 1"); + @Override + public PersonalKit getKitInUse(int userID, String gamemode) { + return getKitInUse.select(rs -> { + if(rs.next()) + return newPersonalKit(rs); + return null; + }, userID, gamemode); + } + + private static final Statement getPunishment = new Statement("SELECT * FROM Punishments WHERE UserId = ? AND Type = ? ORDER BY PunishmentId DESC LIMIT 1"); + @Override + public Punishment getPunishmentOfPlayer(int user, Punishment.PunishmentType type) { + return getPunishment.select(rs -> { + if (rs.next()) + return newPunishment(rs); + return null; + }, user, type.name()); + } + + private Punishment newPunishment(ResultSet rs) throws SQLException { + return new Punishment(rs.getInt("UserId"), rs.getInt("Punisher"), Punishment.PunishmentType.valueOf(rs.getString("Type")), rs.getTimestamp("StartTime"), rs.getTimestamp("EndTime"), rs.getBoolean("Perma"), rs.getString("Reason")); + } + + private static final Statement getPunishments = new Statement("SELECT * FROM Punishments WHERE PunishmentId IN (SELECT MAX(PunishmentId) FROM Punishments WHERE UserId = ? GROUP BY Type)"); + @Override + public Map getPunishmentsOfPlayer(int user) { + return getPunishments.select(rs -> { + Map punishments = new HashMap<>(); + while (rs.next()) + punishments.put(Punishment.PunishmentType.valueOf(rs.getString("Type")), newPunishment(rs)); + return punishments; + }, user); + } + + private static final Statement getUserName = new Statement("SELECT * FROM UserData WHERE lower(UserName) = ?"); + @Override + public SteamwarUser getUserByName(String userName) { + return getUserName.select(rs -> { + if(rs.next()) + return newSteamwarUser(rs); + return null; + }, userName.toLowerCase()); + } + + private static final Statement getUserUUID = new Statement("SELECT * FROM UserData WHERE UUID = ?"); + @Override + public SteamwarUser getUserByUUID(UUID uuid) { + return getUserUUID.select(rs -> { + rs.next(); + return newSteamwarUser(rs); + }, uuid.toString()); + } + + private static final Statement getUserId = new Statement("SELECT * FROM UserData WHERE id = ?"); + @Override + public SteamwarUser getUserByID(int id) { + return getUserId.select(rs -> { + rs.next(); + return newSteamwarUser(rs); + }, id); + } + + private SteamwarUser newSteamwarUser(ResultSet rs) throws SQLException { + return new SteamwarUser(rs.getInt("id"), UUID.fromString(rs.getString("UUID")), rs.getString("UserName"), UserGroup.getUsergroup(rs.getString("UserGroup")), rs.getInt("Team"), rs.getBoolean("Bedrock")); + } + + private static final Statement insert = new Statement("INSERT INTO Exception (server, message, stacktrace) VALUES (?, ?, ?)"); + @Override + public void logException(String server, String message, String stacktrace) { + insert.update(server, message, stacktrace); + } + + private static final Statement getTeam = new Statement("SELECT * FROM Team WHERE TeamID = ?"); + @Override + public Team getTeam(int id) { + return getTeam.select(rs -> { + rs.next(); + return new Team(rs.getInt("TeamID"), rs.getString("TeamKuerzel"), rs.getString("TeamName"), rs.getString("TeamColor")); + }, id); + } + + private static final Statement getTeamMembers = new Statement("SELECT id FROM UserData WHERE Team = ?"); + @Override + public List getTeamMembers(Team team) { + return getTeamMembers.select(rs -> { + List members = new ArrayList<>(); + while(rs.next()) + members.add(rs.getInt("id")); + return members; + }, team.getTeamId()); + } + + private static final Statement getConfig = new Statement("SELECT Value FROM UserConfig WHERE User = ? AND Config = ?"); + @Override + public String getConfig(int player, String config) { + return getConfig.select(rs -> { + if(rs.next()) + return rs.getString("Value"); + return null; + }, player, config); + } + + private static final Statement setConfig = new Statement("INSERT INTO UserConfig (User, Config, Value) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Value = VALUES(Value)"); + @Override + public void updatePlayerConfig(int id, String config, String value) { + setConfig.update(id, config, value); + } + + private static final Statement deleteConfig = new Statement("DELETE FROM UserConfig WHERE User = ? AND Config = ?"); + @Override + public void removePlayerConfig(int id, String config) { + deleteConfig.update(id, config); + } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/SWException.java b/SpigotCore_Main/src/de/steamwar/sql/SWException.java index 99c34ac..d3703a6 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/SWException.java +++ b/SpigotCore_Main/src/de/steamwar/sql/SWException.java @@ -25,8 +25,6 @@ import org.bukkit.entity.Player; public class SWException { private SWException(){} - private static final Statement insert = new Statement("INSERT INTO Exception (server, message, stacktrace) VALUES (?, ?, ?)"); - public static void log(String message, String stacktrace){ message += "\n"; for(Player player : Bukkit.getOnlinePlayers()) @@ -38,6 +36,6 @@ public class SWException { else server = Bukkit.getWorlds().get(0).getName(); - insert.update(server, message, stacktrace); + Provider.impl.logException(server, message, stacktrace); } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java index 2fa3b2d..c005c3d 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java @@ -21,12 +21,12 @@ package de.steamwar.sql; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; import java.io.InputStream; import java.sql.Timestamp; import java.time.Instant; -import java.util.ArrayList; -import java.util.List; +import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; @@ -67,9 +67,15 @@ public class StandaloneProvider implements Provider { @Override public EventFight getEventFight(int fightID) { - return new EventFight(0, fightID, 0, 0, 0, 0, (eventFight, winner) -> {}, (eventFight, fightId) -> {}); + return new EventFight(0, fightID, 0, 0, 0, 0); } + @Override + public void setEventFightResult(EventFight fight, int winner) {} + + @Override + public void setEventFightFightID(EventFight fight, int fightID) {} + @Override public int createFight(String gamemode, String server, Timestamp starttime, int duration, int blueleader, int redleader, Integer blueschem, Integer redschem, int win, String wincondition, Timestamp replayLock) { return 0; @@ -87,5 +93,103 @@ public class StandaloneProvider implements Provider { @Override public void createDownloadLink(int nodeId, String hash) {} + @Override + public NodeMember getNodeMember(int node, int member) { + return null; + } + + @Override + public Set getNodeMembers(int node) { + return Collections.emptySet(); + } + + @Override + public Set getMemberSchematics(int member) { + return Collections.emptySet(); + } + + @Override + public void createNodeMember(int node, int member) {} + + @Override + public List getKits(int userID, String gamemode) { + return Collections.emptyList(); + } + + @Override + public PersonalKit getKit(int userID, String gamemode, String name) { + return null; + } + + @Override + public void updateKit(PersonalKit kit) {} + + @Override + public void deleteKit(PersonalKit kit) {} + + @Override + public PersonalKit getKitInUse(int userID, String gamemode) { + return null; + } + + @Override + public Punishment getPunishmentOfPlayer(int user, Punishment.PunishmentType type) { + return null; + } + + @Override + public Map getPunishmentsOfPlayer(int user) { + return Collections.emptyMap(); + } + + private int userId = 1; + private final Map usersByUUID = new HashMap<>(); + @Override + public SteamwarUser getUserByName(String userName) { + Player player = Bukkit.getPlayer(userName); + if(player == null) + return null; + return usersByUUID.computeIfAbsent(player.getUniqueId(), uuid -> new SteamwarUser(userId++, uuid, userName, UserGroup.Member, 0, false)); + } + + @Override + public SteamwarUser getUserByUUID(UUID uuid) { + return usersByUUID.computeIfAbsent(uuid, uuid1 -> new SteamwarUser(userId++, uuid1, Objects.requireNonNull(Objects.requireNonNull(Bukkit.getOfflinePlayer(uuid1)).getName()), UserGroup.Member, 0, false)); + } + + @Override + public SteamwarUser getUserByID(int id) { + return usersByUUID.values().stream().filter(user -> user.getId() == id).findAny().get(); + } + + @Override + public void logException(String server, String message, String stacktrace) {} + + @Override + public Team getTeam(int id) { + return new Team(0, "TEST", "TestAlliancePleaseIgnore", "c"); + } + + @Override + public List getTeamMembers(Team team) { + return Collections.emptyList(); + } + + private final Map> configs = new HashMap<>(); + @Override + public String getConfig(int player, String config) { + return configs.computeIfAbsent(player, player1 -> new HashMap<>()).get(config); + } + + @Override + public void updatePlayerConfig(int id, String config, String value) { + configs.computeIfAbsent(id, player -> new HashMap<>()).put(config, value); + } + + @Override + public void removePlayerConfig(int id, String config) { + configs.computeIfAbsent(id, player -> new HashMap<>()).remove(config); + } + } diff --git a/SpigotCore_Main/src/de/steamwar/sql/SteamwarUser.java b/SpigotCore_Main/src/de/steamwar/sql/SteamwarUser.java index 05c3d8d..69ea9d5 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/SteamwarUser.java +++ b/SpigotCore_Main/src/de/steamwar/sql/SteamwarUser.java @@ -23,17 +23,12 @@ import de.steamwar.core.Core; import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class SteamwarUser { - private static final Statement getId = new Statement("SELECT * FROM UserData WHERE id = ?"); - private static final Statement getUUID = new Statement("SELECT * FROM UserData WHERE UUID = ?"); - private static final Statement getName = new Statement("SELECT * FROM UserData WHERE lower(UserName) = ?"); private static final Map byUUID = new HashMap<>(); private static final Map byName = new HashMap<>(); @@ -54,21 +49,17 @@ public class SteamwarUser { private final int team; private final boolean bedrock; - private SteamwarUser(ResultSet rs){ - try { - id = rs.getInt("id"); - uuid = java.util.UUID.fromString(rs.getString("UUID")); - userName = rs.getString("UserName"); - userGroup = UserGroup.getUsergroup(rs.getString("UserGroup")); - team = rs.getInt("Team"); - bedrock = rs.getBoolean("Bedrock"); + public SteamwarUser(int id, UUID uuid, String userName, UserGroup userGroup, int team, boolean bedrock) { + this.id = id; + this.uuid = uuid; + this.userName = userName; + this.userGroup = userGroup; + this.team = team; + this.bedrock = bedrock; - byUUID.put(uuid, this); - byName.put(userName.toLowerCase(), this); - byId.put(id, this); - } catch (SQLException e) { - throw new SecurityException("Could not instance User", e); - } + byUUID.put(uuid, this); + byName.put(userName.toLowerCase(), this); + byId.put(id, this); } public int getId() { @@ -98,31 +89,21 @@ public class SteamwarUser { public static SteamwarUser get(String userName){ SteamwarUser user = byName.get(userName.toLowerCase()); if(user == null) - user = getName.select(rs -> { - if(rs.next()) - return new SteamwarUser(rs); - return null; - }, userName.toLowerCase()); + user = Provider.impl.getUserByName(userName); return user; } public static SteamwarUser get(UUID uuid){ SteamwarUser user = byUUID.get(uuid); if(user == null) - user = getUUID.select(rs -> { - rs.next(); - return new SteamwarUser(rs); - }, uuid.toString()); + user = Provider.impl.getUserByUUID(uuid); return user; } public static SteamwarUser get(int id) { SteamwarUser user = byId.get(id); if(user == null) - user = getId.select(rs -> { - rs.next(); - return new SteamwarUser(rs); - }, id); + user = Provider.impl.getUserByID(id); return user; } diff --git a/SpigotCore_Main/src/de/steamwar/sql/Team.java b/SpigotCore_Main/src/de/steamwar/sql/Team.java index c12e994..a432ba8 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/Team.java +++ b/SpigotCore_Main/src/de/steamwar/sql/Team.java @@ -19,16 +19,10 @@ package de.steamwar.sql; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; import java.util.List; public class Team { - private static final Statement get = new Statement("SELECT * FROM Team WHERE TeamID = ?"); - private static final Statement getMembers = new Statement("SELECT id FROM UserData WHERE Team = ?"); - private final int teamId; private final String teamKuerzel; private final String teamName; @@ -36,24 +30,17 @@ public class Team { private static final Team pub = new Team(0, "PUB", "Öffentlich", "8"); - private Team(int teamId, String teamKuerzel, String teamName, String teamColor){ + public Team(int teamId, String teamKuerzel, String teamName, String teamColor) { this.teamId = teamId; this.teamKuerzel = teamKuerzel; this.teamName = teamName; this.teamColor = teamColor; } - private Team(ResultSet rs) throws SQLException { - this(rs.getInt("TeamID"), rs.getString("TeamKuerzel"), rs.getString("TeamName"), rs.getString("TeamColor")); - } - public static Team get(int id){ if(id == 0) return pub; - return get.select(rs -> { - rs.next(); - return new Team(rs); - }, id); + return Provider.impl.getTeam(id); } public int getTeamId() { @@ -73,11 +60,6 @@ public class Team { } public List getMembers(){ - return getMembers.select(rs -> { - List members = new ArrayList<>(); - while(rs.next()) - members.add(rs.getInt("id")); - return members; - }, teamId); + return Provider.impl.getTeamMembers(this); } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/TeamTeilnahme.java b/SpigotCore_Main/src/de/steamwar/sql/TeamTeilnahme.java deleted file mode 100644 index 4a3dd5e..0000000 --- a/SpigotCore_Main/src/de/steamwar/sql/TeamTeilnahme.java +++ /dev/null @@ -1,54 +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.sql; - -import java.sql.ResultSet; -import java.util.HashSet; -import java.util.Set; - -public class TeamTeilnahme { - private TeamTeilnahme(){} - - 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 boolean nimmtTeil(int teamID, int eventID){ - return byEventTeam.select(ResultSet::next, teamID, eventID); - } - - public static Set getTeams(int eventID){ - return byEvent.select(rs -> { - Set teams = new HashSet<>(); - while(rs.next()) - teams.add(Team.get(rs.getInt("TeamID"))); - return teams; - }, eventID); - } - - public static Set getEvents(int teamID){ - return byTeam.select(rs -> { - Set events = new HashSet<>(); - while(rs.next()) - events.add(Event.get(rs.getInt("EventID"))); - return events; - }, teamID); - } -} diff --git a/SpigotCore_Main/src/de/steamwar/sql/UserConfig.java b/SpigotCore_Main/src/de/steamwar/sql/UserConfig.java index a47932a..8547b3b 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/UserConfig.java +++ b/SpigotCore_Main/src/de/steamwar/sql/UserConfig.java @@ -24,20 +24,12 @@ import java.util.UUID; public class UserConfig { private UserConfig() {} - private static final Statement get = new Statement("SELECT Value FROM UserConfig WHERE User = ? AND Config = ?"); - private static final Statement set = new Statement("INSERT INTO UserConfig (User, Config, Value) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE Value = VALUES(Value)"); - private static final Statement delete = new Statement("DELETE FROM UserConfig WHERE User = ? AND Config = ?"); - public static String getConfig(UUID player, String config) { return getConfig(SteamwarUser.get(player).getId(), config); } public static String getConfig(int player, String config) { - return get.select(rs -> { - if(rs.next()) - return rs.getString("Value"); - return null; - }, player, config); + return Provider.impl.getConfig(player, config); } public static void updatePlayerConfig(UUID uuid, String config, String value) { @@ -49,7 +41,7 @@ public class UserConfig { removePlayerConfig(id, config); return; } - set.update(id, config, value); + Provider.impl.updatePlayerConfig(id, config, value); } public static void removePlayerConfig(UUID uuid, String config) { @@ -57,6 +49,6 @@ public class UserConfig { } public static void removePlayerConfig(int id, String config) { - delete.update(id, config); + Provider.impl.removePlayerConfig(id, config); } } -- 2.39.5 From 91aada8a622e9763d3d4e5737f3597e08fb52d36 Mon Sep 17 00:00:00 2001 From: Lixfel Date: Wed, 2 Feb 2022 11:37:44 +0100 Subject: [PATCH 3/9] Provide embedded capability --- .../src/de/steamwar/core/Core.java | 57 ++++++++++--------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/SpigotCore_Main/src/de/steamwar/core/Core.java b/SpigotCore_Main/src/de/steamwar/core/Core.java index 7caba9d..1ef9272 100644 --- a/SpigotCore_Main/src/de/steamwar/core/Core.java +++ b/SpigotCore_Main/src/de/steamwar/core/Core.java @@ -39,11 +39,9 @@ import java.util.logging.Level; public class Core extends JavaPlugin{ + public static final Message MESSAGE = new Message("SpigotCore", Core.class.getClassLoader()); + private static final int VERSION; - public static final Message MESSAGE; - - private static Core instance; - static{ String packageName = Bukkit.getServer().getClass().getPackage().getName(); if(packageName.contains("1_18")) @@ -62,13 +60,30 @@ public class Core extends JavaPlugin{ VERSION = 8; else VERSION = 18; + } + public static int getVersion(){ + return VERSION; + } - MESSAGE = new Message("SpigotCore", Core.class.getClassLoader()); + private static JavaPlugin instance; + public static JavaPlugin getInstance() { + return instance; + } + public static void setInstance(JavaPlugin instance) { + Core.instance = instance; + } + + private static boolean standalone = true; + public static boolean standalone() { + return standalone; + } + + private static File sqlConfig; + public static File sqlConfig() { + return sqlConfig; } private ErrorHandler errorHandler; - private File sqlConfig; - private boolean standalone; @Override public void onLoad() { @@ -77,8 +92,7 @@ public class Core extends JavaPlugin{ @Override public void onEnable() { - sqlConfig = new File(Core.getInstance().getDataFolder(), "MySQL.yml"); - standalone = !sqlConfig.exists(); + setSqlConfig(); errorHandler = new ErrorHandler(); Bukkit.getPluginManager().registerEvents(new PlayerJoinedEvent(), this); @@ -99,26 +113,13 @@ public class Core extends JavaPlugin{ public void onDisable() { TinyProtocol.instance.close(); errorHandler.unregister(); - Statement.close(); + if(!standalone) { + Statement.close(); + } } - public static File sqlConfig() { - return instance.sqlConfig; - } - - public static boolean standalone() { - return instance.standalone; - } - - public static Core getInstance() { - return instance; - } - - public static int getVersion(){ - return VERSION; - } - - private static void setInstance(Core instance) { - Core.instance = instance; + private static void setSqlConfig() { + sqlConfig = new File(Core.getInstance().getDataFolder(), "MySQL.yml"); + standalone = !sqlConfig.exists(); } } -- 2.39.5 From fc7e4884714c9aeed031c779700cdd6837d6283e Mon Sep 17 00:00:00 2001 From: Chaos Date: Wed, 2 Feb 2022 16:46:17 +0100 Subject: [PATCH 4/9] Add SchematicNode.java to Standalone --- .../src/de/steamwar/sql/Provider.java | 21 ++ .../src/de/steamwar/sql/SQLProvider.java | 248 ++++++++++++++++++ .../src/de/steamwar/sql/SchematicNode.java | 246 ++++------------- .../de/steamwar/sql/StandaloneProvider.java | 86 ++++++ 4 files changed, 406 insertions(+), 195 deletions(-) diff --git a/SpigotCore_Main/src/de/steamwar/sql/Provider.java b/SpigotCore_Main/src/de/steamwar/sql/Provider.java index 962bdba..3cdadcf 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/Provider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/Provider.java @@ -21,6 +21,7 @@ package de.steamwar.sql; import de.steamwar.core.Core; +import java.io.IOException; import java.io.InputStream; import java.sql.Timestamp; import java.util.List; @@ -80,4 +81,24 @@ public interface Provider { String getConfig(int player, String config); void updatePlayerConfig(int id, String config, String value); void removePlayerConfig(int id, String config); + + void createSchematicNode(int owner, String name, Integer parent, String type, String item); + SchematicNode getSchematicNode(int owner, String name, Integer parent); + List getSchematicNodeInNode(Integer parent); + List getSchematicDirectoryInNode(Integer parent); + SchematicNode getSchematicDirectory(String name, Integer parent); + SchematicNode getSchematicNode(String name, Integer parent); + SchematicNode getSchematicNode(int id); + List getAccessibleSchematicsOfTypeInParent(int owner, String schemType, Integer parent); + List getAllAccessibleSchematicsOfType(int user, String schemType); + List getAllSchematicsOfType(int owner, String schemType); + List getAllSchematicsOfType(String schemType); + List getSchematicsAccessibleByUser(int user, Integer parent); + List getAllSchematicsAccessibleByUser(int user); + List getAllParentsOfNode(int node); + Integer countNodes(); + void updateSchematicNode(SchematicNode node); + void deleteSchematicNode(SchematicNode node); + InputStream getSchematicData(SchematicNode node) throws IOException; + void saveSchematicNode(SchematicNode node, InputStream blob, boolean newFormat); } diff --git a/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java b/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java index da12849..0fdb551 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/SQLProvider.java @@ -19,12 +19,15 @@ package de.steamwar.sql; +import java.io.IOException; import java.io.InputStream; +import java.sql.Blob; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.*; import java.util.function.Consumer; +import java.util.zip.GZIPInputStream; public class SQLProvider implements Provider { @@ -354,4 +357,249 @@ public class SQLProvider implements Provider { public void removePlayerConfig(int id, String config) { deleteConfig.update(id, config); } + + private static final Statement createNode = new Statement("INSERT INTO SchematicNode (NodeName, NodeOwner, ParentNode, NodeType, NodeItem) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE NodeName = VALUES(NodeName), ParentNode = VALUES(ParentNode), NodeItem = VALUES(NodeItem), NodeType = VALUES(NodeType), NodeItem = VALUES(NodeItem)"); + private static final Statement getSchematicNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL"); + private static final Statement getSchematicNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?"); + private static final Statement getSchematicsInNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode is NULL ORDER BY NodeName"); + private static final Statement getSchematicsInNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode = ? ORDER BY NodeName"); + private static final Statement getDirsInNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode is NULL AND NodeType is NULL ORDER BY NodeName"); + private static final Statement getDirsInNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode = ? AND NodeType is NULL ORDER BY NodeName"); + private static final Statement getSchematicDirectory_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL ORDER BY NodeName"); + private static final Statement getSchematicDirectory = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ? ORDER BY NodeName"); + private static final Statement getSchematicNodeO_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL "); + private static final Statement getSchematicNodeO = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ? ORDER BY NodeName"); + private static final Statement getSchematicNodeId = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ?"); + private static final Statement getAllSchemsOfTypeOwner = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeType = ? ORDER BY NodeName"); + private static final Statement getAllSchemsOfType = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeType = ? ORDER BY NodeName"); + private static final Statement getAccessibleByUser = new Statement("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) AND ((s.NodeOwner = ? AND s.ParentNode IS NULL) OR NOT s.NodeOwner = ?) GROUP BY s.NodeId ORDER BY s.NodeName"); + private static final Statement getAccessibleByUserByTypeInNode = new Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode = ? ORDER BY NodeName"); + private static final Statement getAccessibleByUserByTypeInNode_Null = new Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode is null ORDER BY NodeName"); + private static final Statement getAccessibleByUserByType = new Statement("WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? ORDER BY NodeName"); + private static final Statement getAllSchematicsAccessibleByUser = new Statement("WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN ORDER BY NodeName"); + private static final Statement isSchematicAccessibleForUser = new Statement("WITH RECURSIVE RSN AS (SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.ParentNode, SN.NodeType, SN.NodeItem, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT COUNT(RSN.NodeId) AS `Accessible` FROM RSN LEFT Join NodeMember NM On NM.NodeId = RSN.NodeId WHERE NodeOwner = ? OR UserId = ? LIMIT 1"); + private static final Statement getAllParentsOfNode = new Statement("WITH RECURSIVE RSN AS (SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ? UNION SELECT SN.NodeId, SN.NodeName, SN.NodeOwner, SN.ParentNode, SN.NodeType, SN.NodeItem, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT * FROM RSN ORDER BY NodeName"); + private static final Statement countNodes = new Statement("SELECT COUNT(NodeId) AS 'count' FROM SchematicNode"); + private static final Statement updateDB = new Statement("UPDATE SchematicNode SET NodeName = ?, NodeOwner = ?, ParentNode = ?, NodeItem = ?, NodeType = ?, NodeRank = ? WHERE NodeId = ?"); + private static final Statement updateDatabase = new Statement("UPDATE SchematicNode SET NodeData = ?, NodeFormat = ? WHERE NodeId = ?"); + private static final Statement selSchemData = new Statement("SELECT NodeData FROM SchematicNode WHERE NodeId = ?"); + private static final Statement deleteNode = new Statement("DELETE FROM SchematicNode WHERE NodeId = ?"); + + private static final Statement.ResultSetUser> toSchematicList = rs -> { + List nodes = new ArrayList<>(); + while (rs.next()) { + nodes.add(nodeFromResultSet(rs)); + } + return nodes; + }; + private static final Statement.ResultSetUser toSchematicNode = rs -> { + if (rs.next()) { + return nodeFromResultSet(rs); + } + return null; + }; + + private static SchematicNode nodeFromResultSet(ResultSet set) throws SQLException { + Integer parent = set.getInt("ParentNode"); + if(set.wasNull()) { + parent = null; + } + String type = set.getString("NodeType"); + boolean isDir = true; + Integer rank = null; + boolean schemFormat = false; + if (type != null) { + isDir = false; + rank = set.getInt("NodeRank"); + schemFormat = set.getBoolean("NodeFormat"); + } + return new SchematicNode( + set.getInt("NodeId"), + set.getInt("NodeOwner"), + set.getString("NodeName"), + parent, + set.getString("NodeItem"), + type, + isDir, + rank, + set.getTimestamp("LastUpdate"), + schemFormat + ); + } + + @Override + public void createSchematicNode(int owner, String name, Integer parent, String type, String item) { + createNode.update(owner, name, parent, type, item); + } + + @Override + public SchematicNode getSchematicNode(int owner, String name, Integer parent) { + + if(parent == null) { + return getSchematicNode_Null.select(toSchematicNode, owner, name); + } else { + return getSchematicNode.select(toSchematicNode, owner, name, parent); + } + } + + @Override + public List getSchematicNodeInNode(Integer parent) { + if(parent == null) { + return getSchematicsInNode_Null.select(toSchematicList); + }else { + return getSchematicsInNode.select(toSchematicList, parent); + } + } + + @Override + public List getSchematicDirectoryInNode(Integer parent) { + if(parent == null) { + return getDirsInNode_Null.select(toSchematicList); + }else { + return getDirsInNode.select(toSchematicList, parent); + } + } + + @Override + public SchematicNode getSchematicDirectory(String name, Integer parent) { + Statement.ResultSetUser user = rs -> { + while (rs.next()) { + SchematicNode node = nodeFromResultSet(rs); + if(node.isDir()) + return node; + } + return null; + }; + + if(parent == null) { + return getSchematicDirectory_Null.select(user, name); + }else { + return getSchematicDirectory.select(user, name, parent); + } + } + + @Override + public SchematicNode getSchematicNode(String name, Integer parent) { + if(parent == null) { + return getSchematicNodeO_Null.select(toSchematicNode, name); + }else { + return getSchematicNodeO.select(toSchematicNode, name, parent); + } + } + + @Override + public SchematicNode getSchematicNode(int id) { + return getSchematicNodeId.select(rs -> { + if (!rs.next()) + return null; + return nodeFromResultSet(rs); + }, id); + } + + @Override + public List getAccessibleSchematicsOfTypeInParent(int owner, String schemType, Integer parent) { + if(parent == null || parent == 0) { + return getAccessibleByUserByTypeInNode_Null.select(toSchematicList, owner, owner, schemType); + } else { + return getAccessibleByUserByTypeInNode.select(toSchematicList, owner, owner, schemType, parent); + } + } + + @Override + public List getAllAccessibleSchematicsOfType(int user, String schemType) { + return getAccessibleByUserByType.select(toSchematicList, user, user, schemType); + } + + @Override + public List getAllSchematicsOfType(int owner, String schemType) { + return getAllSchemsOfTypeOwner.select(toSchematicList, owner, schemType); + } + + @Override + public List getAllSchematicsOfType(String schemType) { + return getAllSchemsOfType.select(toSchematicList, schemType); + } + + @Override + public List getSchematicsAccessibleByUser(int user, Integer parent) { + if (parent != null && parent != 0) { + if(Boolean.TRUE.equals(isSchematicAccessibleForUser.select(rs -> { + rs.next(); + return rs.getInt("Accessible") > 0; + }, parent, user, user))) { + return getSchematicNodeInNode(parent); + } + } else { + return getAccessibleByUser.select(rs -> { + List nodes = new ArrayList<>(); + while(rs.next()) + nodes.add(nodeFromResultSet(rs)); + return nodes; + }, user, user, user, user); + } + return Collections.emptyList(); + } + + @Override + public List getAllSchematicsAccessibleByUser(int user) { + return getAllSchematicsAccessibleByUser.select(toSchematicList, user, user); + } + + @Override + public List getAllParentsOfNode(int node) { + return getAllParentsOfNode.select(toSchematicList, node); + } + + @Override + public Integer countNodes() { + return countNodes.select(rs -> { + if (rs.next()) { + return rs.getInt("count"); + } + return 0; + }); + } + + @Override + public void updateSchematicNode(SchematicNode node) { + updateDB.update( + node.getName(), + node.getOwner(), + node.getParent(), + node.getItem(), + node.getType(), + node.getRank(), + node.getId() + ); + } + + @Override + public void deleteSchematicNode(SchematicNode node) { + deleteNode.update(node.getId()); + } + + @Override + public InputStream getSchematicData(SchematicNode node) throws IOException { + try { + return selSchemData.select(rs -> { + rs.next(); + Blob schemData = rs.getBlob("NodeData"); + if(schemData == null) { + throw new SecurityException("SchemData is null"); + } + try { + return new GZIPInputStream(schemData.getBinaryStream()); + } catch (IOException e) { + throw new SecurityException("SchemData is wrong", e); + } + }, node.getId()); + } catch (Exception e) { + throw new IOException(e); + } + } + + @Override + public void saveSchematicNode(SchematicNode node, InputStream blob, boolean newFormat) { + updateDatabase.update(blob, newFormat, node.getId()); + } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/SchematicNode.java b/SpigotCore_Main/src/de/steamwar/sql/SchematicNode.java index 32c3d51..34439ea 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/SchematicNode.java +++ b/SpigotCore_Main/src/de/steamwar/sql/SchematicNode.java @@ -39,33 +39,6 @@ import java.util.zip.GZIPInputStream; public class SchematicNode { - private static final Statement createNode = new Statement("INSERT INTO SchematicNode (NodeName, NodeOwner, ParentNode, NodeType, NodeItem) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE NodeName = VALUES(NodeName), ParentNode = VALUES(ParentNode), NodeItem = VALUES(NodeItem), NodeType = VALUES(NodeType), NodeItem = VALUES(NodeItem)"); - private static final Statement getSchematicNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode is NULL"); - private static final Statement getSchematicNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeName = ? AND ParentNode = ?"); - private static final Statement getSchematicsInNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode is NULL ORDER BY NodeName"); - private static final Statement getSchematicsInNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode = ? ORDER BY NodeName"); - private static final Statement getDirsInNode_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode is NULL AND NodeType is NULL ORDER BY NodeName"); - private static final Statement getDirsInNode = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE ParentNode = ? AND NodeType is NULL ORDER BY NodeName"); - private static final Statement getSchematicDirectory_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL ORDER BY NodeName"); - private static final Statement getSchematicDirectory = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ? ORDER BY NodeName"); - private static final Statement getSchematicNodeO_Null = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode is NULL "); - private static final Statement getSchematicNodeO = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeName = ? AND ParentNode = ? ORDER BY NodeName"); - private static final Statement getSchematicNodeId = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ?"); - private static final Statement getAllSchemsOfTypeOwner = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeOwner = ? AND NodeType = ? ORDER BY NodeName"); - private static final Statement getAllSchemsOfType = new Statement("SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeType = ? ORDER BY NodeName"); - private static final Statement getAccessibleByUser = new Statement("SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) AND ((s.NodeOwner = ? AND s.ParentNode IS NULL) OR NOT s.NodeOwner = ?) GROUP BY s.NodeId ORDER BY s.NodeName"); - private static final Statement getAccessibleByUserByTypeInNode = new Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode = ? ORDER BY NodeName"); - private static final Statement getAccessibleByUserByTypeInNode_Null = new Statement("WITH RECURSIVE RSNB AS (WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSNB WHERE SN.NodeId = RSNB.ParentNode)SELECT * FROM RSNB WHERE ParentNode is null ORDER BY NodeName"); - private static final Statement getAccessibleByUserByType = new Statement("WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN WHERE NodeType = ? ORDER BY NodeName"); - private static final Statement getAllSchematicsAccessibleByUser = new Statement("WITH RECURSIVE RSN as (SELECT s.NodeId, s.NodeName, s.NodeOwner, s.NodeItem, s.NodeType, s.ParentNode, s.NodeRank, s.NodeFormat, s.LastUpdate FROM SchematicNode s LEFT JOIN NodeMember n ON s.NodeId = n.NodeId WHERE (s.NodeOwner = ? OR n.UserId = ?) GROUP BY s.NodeId union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.NodeItem, SN.NodeType, SN.ParentNode, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode AS SN, RSN WHERE SN.ParentNode = RSN.NodeId) SELECT * FROM RSN ORDER BY NodeName"); - private static final Statement isSchematicAccessibleForUser = new Statement("WITH RECURSIVE RSN AS (SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ? union select SN.NodeId, SN.NodeName, SN.NodeOwner, SN.ParentNode, SN.NodeType, SN.NodeItem, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT COUNT(RSN.NodeId) AS `Accessible` FROM RSN LEFT Join NodeMember NM On NM.NodeId = RSN.NodeId WHERE NodeOwner = ? OR UserId = ? LIMIT 1"); - private static final Statement getAllParentsOfNode = new Statement("WITH RECURSIVE RSN AS (SELECT NodeId, NodeName, NodeOwner, ParentNode, NodeType, NodeItem, NodeRank, NodeFormat, LastUpdate FROM SchematicNode WHERE NodeId = ? UNION SELECT SN.NodeId, SN.NodeName, SN.NodeOwner, SN.ParentNode, SN.NodeType, SN.NodeItem, SN.NodeRank, SN.NodeFormat, SN.LastUpdate FROM SchematicNode SN, RSN WHERE RSN.ParentNode = SN.NodeId) SELECT * FROM RSN ORDER BY NodeName"); - private static final Statement countNodes = new Statement("SELECT COUNT(NodeId) AS 'count' FROM SchematicNode"); - private static final Statement updateDB = new Statement("UPDATE SchematicNode SET NodeName = ?, NodeOwner = ?, ParentNode = ?, NodeItem = ?, NodeType = ?, NodeRank = ? WHERE NodeId = ?"); - private static final Statement updateDatabase = new Statement("UPDATE SchematicNode SET NodeData = ?, NodeFormat = ? WHERE NodeId = ?"); - private static final Statement selSchemData = new Statement("SELECT NodeData FROM SchematicNode WHERE NodeId = ?"); - private static final Statement deleteNode = new Statement("DELETE FROM SchematicNode WHERE NodeId = ?"); - public static SchematicNode createSchematic(int owner, String name, Integer parent) { return createSchematicNode(owner, name, parent, SchematicType.Normal.toDB(), ""); } @@ -77,7 +50,7 @@ public class SchematicNode { public static SchematicNode createSchematicNode(int owner, String name, Integer parent, String type, String item) { if (parent != null && parent == 0) parent = null; - createNode.update(name, owner, parent, type, item); + Provider.impl.createSchematicNode(owner, name, parent, type, item); return getSchematicNode(owner, name, parent); } @@ -85,23 +58,29 @@ public class SchematicNode { return getSchematicNode(owner, name, parent.getId()); } - private SchematicNode(ResultSet set) throws SQLException { - id = set.getInt("NodeId"); - owner = set.getInt("NodeOwner"); - name = set.getString("NodeName"); - parent = set.getInt("ParentNode"); - if(set.wasNull()) { - parent = null; - } - item = set.getString("NodeItem"); - type = set.getString("NodeType"); - lastUpdate = set.getTimestamp("LastUpdate"); - if (type != null) { - isDir = false; - rank = set.getInt("NodeRank"); - schemFormat = set.getBoolean("NodeFormat"); - } else { - isDir = true; + public SchematicNode( + int id, + int owner, + String name, + Integer parent, + String item, + String type, + boolean isDir, + int rank, + Timestamp lastUpdate, + boolean schemFormat + ) { + this.id = id; + this.owner = owner; + this.name = name; + this.parent = parent; + this.item = item; + this.type = type; + this.lastUpdate = lastUpdate; + this.isDir = isDir; + if (!isDir) { + this.schemFormat = schemFormat; + this.rank = rank; } } @@ -117,136 +96,60 @@ public class SchematicNode { if (parent != null && parent == 0) { parent = null; } - Statement.ResultSetUser user = rs -> { - if (rs.next()) { - return new SchematicNode(rs); - } - return null; - }; - if(parent == null) { - return getSchematicNode_Null.select(user, owner, name); - } else { - return getSchematicNode.select(user, owner, name, parent); - } + return Provider.impl.getSchematicNode(owner, name, parent); } public static List getSchematicNodeInNode(Integer parent) { - if(parent != null && parent == 0) + if(parent != null && parent == 0) { parent = null; - Statement.ResultSetUser> user = rs -> { - List nodes = new ArrayList<>(); - while (rs.next()) { - nodes.add(new SchematicNode(rs)); - } - return nodes; - }; - if(parent == null) { - return getSchematicsInNode_Null.select(user); - }else { - return getSchematicsInNode.select(user, parent); } + return Provider.impl.getSchematicNodeInNode(parent); } public static List getSchematicDirectoryInNode(Integer parent) { - if(parent != null && parent == 0) + if(parent != null && parent == 0) { parent = null; - Statement.ResultSetUser> user = rs -> { - List nodes = new ArrayList<>(); - while (rs.next()) - nodes.add(new SchematicNode(rs)); - return nodes; - }; - if(parent == null) { - return getDirsInNode_Null.select(user); - }else { - return getDirsInNode.select(user, parent); } + return Provider.impl.getSchematicDirectoryInNode(parent); } public static SchematicNode getSchematicDirectory(String name, Integer parent) { - if(parent != null && parent == 0) + if(parent != null && parent == 0) { parent = null; - Statement.ResultSetUser user = rs -> { - while (rs.next()) { - SchematicNode node = new SchematicNode(rs); - if(node.isDir()) - return node; - } - return null; - }; - - if(parent == null) { - return getSchematicDirectory_Null.select(user, name); - }else { - return getSchematicDirectory.select(user, name, parent); } + return Provider.impl.getSchematicDirectory(name, parent); } public static SchematicNode getSchematicNode(String name, Integer parent) { - if(parent != null && parent == 0) + if(parent != null && parent == 0) { parent = null; - Statement.ResultSetUser user = rs -> { - while (rs.next()) { - return new SchematicNode(rs); - } - return null; - }; - if(parent == null) { - return getSchematicNodeO_Null.select(user, name); - }else { - return getSchematicNodeO.select(user, name, parent); } + return Provider.impl.getSchematicNode(name, parent); } public static SchematicNode getSchematicNode(int id) { - return getSchematicNodeId.select(rs -> { - if (!rs.next()) - return null; - return new SchematicNode(rs); - }, id); + return Provider.impl.getSchematicNode(id); } public static List getAccessibleSchematicsOfTypeInParent(int owner, String schemType, Integer parent) { - Statement.ResultSetUser> user = rs -> { - List nodes = new ArrayList<>(); - while (rs.next()) { - nodes.add(new SchematicNode(rs)); - } - return nodes; - }; - if(parent == null || parent == 0) { - return getAccessibleByUserByTypeInNode_Null.select(user, owner, owner, schemType); - } else { - return getAccessibleByUserByTypeInNode.select(user, owner, owner, schemType, parent); - } + return Provider.impl.getAccessibleSchematicsOfTypeInParent(owner, schemType, parent); } public static List getAllAccessibleSchematicsOfType(int user, String schemType) { - return getAccessibleByUserByType.select(rs -> { - List nodes = new ArrayList<>(); - while (rs.next()) { - nodes.add(new SchematicNode(rs)); - } - return nodes; - }, user, user, schemType); + return Provider.impl.getAllAccessibleSchematicsOfType(user, schemType); } public static List getAllSchematicsOfType(int owner, String schemType) { - return getAllSchemsOfTypeOwner.select(rs -> { - List nodes = new ArrayList<>(); - while (rs.next()) - nodes.add(new SchematicNode(rs)); - return nodes; - }, owner, schemType); + return Provider.impl.getAllSchematicsOfType(owner, schemType); } + @Deprecated public static List getAllSchematicsOfType(String schemType) { - return getAllSchemsOfType.select(rs -> { - List nodes = new ArrayList<>(); - while (rs.next()) - nodes.add(new SchematicNode(rs)); - return nodes; - }, schemType); + return Provider.impl.getAllSchematicsOfType(schemType); + } + + public static List getAllSchematicsOfType(SchematicType schemType) { + return Provider.impl.getAllSchematicsOfType(schemType.toDB()); } public static List deepGet(Integer parent, Predicate filter) { @@ -264,32 +167,11 @@ public class SchematicNode { } public static List getSchematicsAccessibleByUser(int user, Integer parent) { - if (parent != null && parent != 0) { - if(Boolean.TRUE.equals(isSchematicAccessibleForUser.select(rs -> { - rs.next(); - return rs.getInt("Accessible") > 0; - }, parent, user, user))) { - return getSchematicNodeInNode(parent); - } - } else { - return getAccessibleByUser.select(rs -> { - List nodes = new ArrayList<>(); - while(rs.next()) - nodes.add(new SchematicNode(rs)); - return nodes; - }, user, user, user, user); - } - return Collections.emptyList(); + return Provider.impl.getSchematicsAccessibleByUser(user, parent); } public static List getAllSchematicsAccessibleByUser(int user) { - return getAllSchematicsAccessibleByUser.select(rs -> { - List nodes = new ArrayList<>(); - while(rs.next()) { - nodes.add(new SchematicNode(rs)); - } - return nodes; - }, user, user); + return Provider.impl.getAllSchematicsAccessibleByUser(user); } public static List getAllParentsOfNode(SchematicNode node) { @@ -297,13 +179,7 @@ public class SchematicNode { } public static List getAllParentsOfNode(int node) { - return getAllParentsOfNode.select(rs -> { - List nodes = new ArrayList<>(); - while(rs.next()) { - nodes.add(new SchematicNode(rs)); - } - return nodes; - }, node); + return Provider.impl.getAllParentsOfNode(node); } public static SchematicNode getNodeFromPath(SteamwarUser user, String s) { @@ -367,12 +243,7 @@ public class SchematicNode { } public static Integer countNodes() { - return countNodes.select(rs -> { - if (rs.next()) { - return rs.getInt("count"); - } - return 0; - }); + return Provider.impl.countNodes(); } public int getId() { @@ -501,32 +372,17 @@ public class SchematicNode { } private void updateDB() { - updateDB.update(name, owner, parent, item, type, rank, id); + Provider.impl.updateSchematicNode(this); this.lastUpdate = Timestamp.from(Instant.now()); this.brCache.clear(); } public void delete() { - deleteNode.update(id); + Provider.impl.deleteSchematicNode(this); } public InputStream schemData() throws IOException { - try { - return selSchemData.select(rs -> { - rs.next(); - Blob schemData = rs.getBlob("NodeData"); - if(schemData == null) { - throw new SecurityException("SchemData is null"); - } - try { - return new GZIPInputStream(schemData.getBinaryStream()); - } catch (IOException e) { - throw new SecurityException("SchemData is wrong", e); - } - }, id); - } catch (Exception e) { - throw new IOException(e); - } + return Provider.impl.getSchematicData(this); } public Clipboard load() throws IOException, NoClipboardException { @@ -560,7 +416,7 @@ public class SchematicNode { } private void updateDatabase(InputStream blob, boolean newFormat) { - updateDatabase.update(blob, newFormat, id); + Provider.impl.saveSchematicNode(this, blob, newFormat); schemFormat = newFormat; } diff --git a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java index c005c3d..8e334ae 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java @@ -23,6 +23,7 @@ import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; +import java.io.IOException; import java.io.InputStream; import java.sql.Timestamp; import java.time.Instant; @@ -191,5 +192,90 @@ public class StandaloneProvider implements Provider { configs.computeIfAbsent(id, player -> new HashMap<>()).remove(config); } + @Override + public void createSchematicNode(int owner, String name, Integer parent, String type, String item) {} + @Override + public SchematicNode getSchematicNode(int owner, String name, Integer parent) { + return null; + } + + @Override + public List getSchematicNodeInNode(Integer parent) { + return Collections.emptyList(); + } + + @Override + public List getSchematicDirectoryInNode(Integer parent) { + return Collections.emptyList(); + } + + @Override + public SchematicNode getSchematicDirectory(String name, Integer parent) { + return null; + } + + @Override + public SchematicNode getSchematicNode(String name, Integer parent) { + return null; + } + + @Override + public SchematicNode getSchematicNode(int id) { + return null; + } + + @Override + public List getAccessibleSchematicsOfTypeInParent(int owner, String schemType, Integer parent) { + return Collections.emptyList(); + } + + @Override + public List getAllAccessibleSchematicsOfType(int user, String schemType) { + return Collections.emptyList(); + } + + @Override + public List getAllSchematicsOfType(int owner, String schemType) { + return Collections.emptyList(); + } + + @Override + public List getAllSchematicsOfType(String schemType) { + return Collections.emptyList(); + } + + @Override + public List getSchematicsAccessibleByUser(int user, Integer parent) { + return Collections.emptyList(); + } + + @Override + public List getAllSchematicsAccessibleByUser(int user) { + return Collections.emptyList(); + } + + @Override + public List getAllParentsOfNode(int node) { + return Collections.emptyList(); + } + + @Override + public Integer countNodes() { + return 0; + } + + @Override + public void updateSchematicNode(SchematicNode node) {} + + @Override + public void deleteSchematicNode(SchematicNode node) {} + + @Override + public InputStream getSchematicData(SchematicNode node) throws IOException { + return null; + } + + @Override + public void saveSchematicNode(SchematicNode node, InputStream blob, boolean newFormat) {} } -- 2.39.5 From e8357c1c6070938f3a6bc763980cce28a631b4b3 Mon Sep 17 00:00:00 2001 From: Chaos Date: Wed, 9 Feb 2022 19:19:19 +0100 Subject: [PATCH 5/9] Should be Working! --- .../de/steamwar/core/WorldEditWrapper14.java | 5 + .../de/steamwar/core/WorldEditWrapper8.java | 5 + .../de/steamwar/core/WorldEditWrapper.java | 3 +- .../de/steamwar/sql/StandaloneProvider.java | 130 ++++++++++++++---- 4 files changed, 119 insertions(+), 24 deletions(-) diff --git a/SpigotCore_14/src/de/steamwar/core/WorldEditWrapper14.java b/SpigotCore_14/src/de/steamwar/core/WorldEditWrapper14.java index f23e7fc..78a6be9 100644 --- a/SpigotCore_14/src/de/steamwar/core/WorldEditWrapper14.java +++ b/SpigotCore_14/src/de/steamwar/core/WorldEditWrapper14.java @@ -115,6 +115,11 @@ public class WorldEditWrapper14 implements WorldEditWrapper.IWorldEditWrapper { } } + @Override + public File getWorldEditSchematicFolder() { + return WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getWorkingDirectoryFile(WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getConfiguration().saveDir); + } + private static class MCEditSchematicReader extends NBTSchematicReader { private final NBTInputStream inputStream; diff --git a/SpigotCore_8/src/de/steamwar/core/WorldEditWrapper8.java b/SpigotCore_8/src/de/steamwar/core/WorldEditWrapper8.java index 2b1cb0e..d08383f 100644 --- a/SpigotCore_8/src/de/steamwar/core/WorldEditWrapper8.java +++ b/SpigotCore_8/src/de/steamwar/core/WorldEditWrapper8.java @@ -88,6 +88,11 @@ public class WorldEditWrapper8 implements WorldEditWrapper.IWorldEditWrapper { return new SchematicReader(new NBTInputStream(is)).read(WorldEdit.getInstance().getServer().getWorlds().get(0).getWorldData()); } + @Override + public File getWorldEditSchematicFolder() { + return WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getWorkingDirectoryFile(WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getConfiguration().saveDir); + } + private static class SpongeSchematicReader implements ClipboardReader { private final NBTInputStream inputStream; diff --git a/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java b/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java index 0b860ee..8cb80e4 100644 --- a/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java +++ b/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java @@ -5,6 +5,7 @@ import com.sk89q.worldedit.extent.clipboard.Clipboard; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -17,7 +18,7 @@ public class WorldEditWrapper { InputStream getPlayerClipboard(Player player, boolean schemFormat); void setPlayerClipboard(Player player, InputStream is, boolean schemFormat); Clipboard getClipboard(InputStream is, boolean schemFormat) throws IOException; - + File getWorldEditSchematicFolder(); } static WorldEditPlugin getWorldEditPlugin() { diff --git a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java index 8e334ae..4b6cde9 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java @@ -19,17 +19,25 @@ package de.steamwar.sql; +import com.google.common.collect.Maps; +import de.steamwar.core.WorldEditWrapper; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; +import java.io.ByteArrayOutputStream; +import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.sql.Timestamp; import java.time.Instant; import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; +import java.util.stream.Stream; public class StandaloneProvider implements Provider { @Override @@ -192,90 +200,166 @@ public class StandaloneProvider implements Provider { configs.computeIfAbsent(id, player -> new HashMap<>()).remove(config); } + private int nodeId = 1; + private final File schematicDir = WorldEditWrapper.impl.getWorldEditSchematicFolder(); + private final Map nodeById = new HashMap<>(); + private final Map> nodesByParent = new HashMap<>(); + private final Map nodesToPath = new HashMap<>(); + + { + nodesToPath.put(-1, schematicDir.toPath()); + } + + private List mapDir(Integer id) { + try (Stream stream = Files.list(id==null?schematicDir.toPath():nodesToPath.get(id))) { + List list = stream.map(path -> { + File file = path.toFile(); + SchematicNode node = new SchematicNode( + nodeId++, + 0, + file.getName().substring(file.getName().lastIndexOf(".")), + null, + "", + "normal", + file.isDirectory(), + 0, + Timestamp.from(Instant.now()), + file.getName().endsWith(".schem") + ); + nodesToPath.put(node.getId(), path); + nodeById.put(node.getId(), node); + return node; + }).collect(Collectors.toList()); + nodesByParent.putIfAbsent(id == null?-1:id, list); + return list; + } catch (IOException e) { + throw new SecurityException(e); + } + } + @Override - public void createSchematicNode(int owner, String name, Integer parent, String type, String item) {} + public void createSchematicNode(int owner, String name, Integer parent, String type, String item) { + + } @Override public SchematicNode getSchematicNode(int owner, String name, Integer parent) { - return null; + return nodesByParent.get(parent).stream().filter(node -> node.getName().equals(name)).findAny().orElse(null); } @Override public List getSchematicNodeInNode(Integer parent) { - return Collections.emptyList(); + return nodesByParent.computeIfAbsent(parent==null?-1:parent, integer -> mapDir(parent)); } @Override public List getSchematicDirectoryInNode(Integer parent) { - return Collections.emptyList(); + return getSchematicNodeInNode(parent).stream().filter(SchematicNode::isDir).collect(Collectors.toList()); } @Override public SchematicNode getSchematicDirectory(String name, Integer parent) { - return null; + return getSchematicDirectoryInNode(parent).stream().filter(node -> node.getName().equals(name)).findFirst().orElse(null); } @Override public SchematicNode getSchematicNode(String name, Integer parent) { - return null; + return getSchematicNodeInNode(parent).stream().filter(node -> name.equals(node.getName())).findFirst().orElse(null); } @Override public SchematicNode getSchematicNode(int id) { - return null; + return nodeById.getOrDefault(id, null); } @Override - public List getAccessibleSchematicsOfTypeInParent(int owner, String schemType, Integer parent) { - return Collections.emptyList(); + public List getAccessibleSchematicsOfTypeInParent(int ignored, String schemType, Integer parent) { + return getSchematicDirectoryInNode(parent).stream().filter(node -> node.getType().equals(schemType)).collect(Collectors.toList()); } @Override - public List getAllAccessibleSchematicsOfType(int user, String schemType) { - return Collections.emptyList(); + public List getAllAccessibleSchematicsOfType(int ignored, String schemType) { + return getAllSchematicsAccessibleByUser(ignored).stream().filter(node -> schemType.equals(node.getType())).collect(Collectors.toList()); } @Override - public List getAllSchematicsOfType(int owner, String schemType) { - return Collections.emptyList(); + public List getAllSchematicsOfType(int ignored, String schemType) { + return getAllAccessibleSchematicsOfType(ignored, schemType); } @Override public List getAllSchematicsOfType(String schemType) { - return Collections.emptyList(); + return getAllAccessibleSchematicsOfType(-1, schemType); } @Override - public List getSchematicsAccessibleByUser(int user, Integer parent) { - return Collections.emptyList(); + public List getSchematicsAccessibleByUser(int ignored, Integer parent) { + return getSchematicNodeInNode(parent); } @Override public List getAllSchematicsAccessibleByUser(int user) { - return Collections.emptyList(); + return nodesByParent.values().stream().reduce((schematicNodes, schematicNodes2) -> { + schematicNodes.addAll(schematicNodes2); + return schematicNodes; + }).orElse(new ArrayList<>()); } @Override public List getAllParentsOfNode(int node) { - return Collections.emptyList(); + List allSchematicsAccessibleByUser = getAllSchematicsAccessibleByUser(node); + allSchematicsAccessibleByUser.remove(getSchematicNode(node)); + return allSchematicsAccessibleByUser; } @Override public Integer countNodes() { - return 0; + return nodesByParent.values().stream().map(List::size).reduce((Integer::sum)).orElse(0); } @Override - public void updateSchematicNode(SchematicNode node) {} + public void updateSchematicNode(SchematicNode node) { + try { + Path newPath = new File(nodesToPath.get(node.getParent() == null?-1:node.getParent()).toFile(), node.getName() + (node.getSchemFormat()?".schem":".schematic")).toPath(); + Files.move(nodesToPath.get(node.getId()), newPath); + nodesToPath.put(node.getId(), newPath); + } catch (IOException e) { + throw new SecurityException(e); + } + } @Override - public void deleteSchematicNode(SchematicNode node) {} + public void deleteSchematicNode(SchematicNode node) { + try { + Files.deleteIfExists(nodesToPath.get(node.getId())); + nodeById.remove(node.getId()); + nodesByParent.get(node.getParent() == null?-1:node.getId()).remove(node); + nodesToPath.remove(node.getId()); + } catch (IOException e) { + throw new SecurityException(e); + } + } @Override public InputStream getSchematicData(SchematicNode node) throws IOException { - return null; + return Files.newInputStream(nodesToPath.get(node.getId())); } @Override - public void saveSchematicNode(SchematicNode node, InputStream blob, boolean newFormat) {} + public void saveSchematicNode(SchematicNode node, InputStream blob, boolean newFormat) { + try { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + byte[] bucket = new byte[1024]; + int nReadBytes; + + while((nReadBytes = blob.read(bucket, 0, bucket.length)) !=-1){ + byteArrayOutputStream.write(bucket, 0, nReadBytes); + } + + byte[] bytes = byteArrayOutputStream.toByteArray(); + Files.write(nodesToPath.get(node.getId()), bytes, StandardOpenOption.TRUNCATE_EXISTING); + } catch (IOException e) { + throw new SecurityException(e); + } + } } -- 2.39.5 From bc1f268022a8682305efe86461a29ae08e7c10a1 Mon Sep 17 00:00:00 2001 From: Chaos Date: Wed, 9 Feb 2022 19:53:43 +0100 Subject: [PATCH 6/9] Pr Stuff --- .../de/steamwar/core/WorldEditWrapper14.java | 5 ---- .../de/steamwar/core/WorldEditWrapper8.java | 5 ---- .../de/steamwar/core/WorldEditWrapper.java | 4 +++- .../de/steamwar/sql/StandaloneProvider.java | 24 +++++++------------ 4 files changed, 12 insertions(+), 26 deletions(-) diff --git a/SpigotCore_14/src/de/steamwar/core/WorldEditWrapper14.java b/SpigotCore_14/src/de/steamwar/core/WorldEditWrapper14.java index 78a6be9..f23e7fc 100644 --- a/SpigotCore_14/src/de/steamwar/core/WorldEditWrapper14.java +++ b/SpigotCore_14/src/de/steamwar/core/WorldEditWrapper14.java @@ -115,11 +115,6 @@ public class WorldEditWrapper14 implements WorldEditWrapper.IWorldEditWrapper { } } - @Override - public File getWorldEditSchematicFolder() { - return WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getWorkingDirectoryFile(WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getConfiguration().saveDir); - } - private static class MCEditSchematicReader extends NBTSchematicReader { private final NBTInputStream inputStream; diff --git a/SpigotCore_8/src/de/steamwar/core/WorldEditWrapper8.java b/SpigotCore_8/src/de/steamwar/core/WorldEditWrapper8.java index d08383f..2b1cb0e 100644 --- a/SpigotCore_8/src/de/steamwar/core/WorldEditWrapper8.java +++ b/SpigotCore_8/src/de/steamwar/core/WorldEditWrapper8.java @@ -88,11 +88,6 @@ public class WorldEditWrapper8 implements WorldEditWrapper.IWorldEditWrapper { return new SchematicReader(new NBTInputStream(is)).read(WorldEdit.getInstance().getServer().getWorlds().get(0).getWorldData()); } - @Override - public File getWorldEditSchematicFolder() { - return WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getWorkingDirectoryFile(WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getConfiguration().saveDir); - } - private static class SpongeSchematicReader implements ClipboardReader { private final NBTInputStream inputStream; diff --git a/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java b/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java index 8cb80e4..58d5ee1 100644 --- a/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java +++ b/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java @@ -18,7 +18,9 @@ public class WorldEditWrapper { InputStream getPlayerClipboard(Player player, boolean schemFormat); void setPlayerClipboard(Player player, InputStream is, boolean schemFormat); Clipboard getClipboard(InputStream is, boolean schemFormat) throws IOException; - File getWorldEditSchematicFolder(); + default File getWorldEditSchematicFolder() { + return WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getWorkingDirectoryFile(WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getConfiguration().saveDir); + } } static WorldEditPlugin getWorldEditPlugin() { diff --git a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java index 4b6cde9..97f810a 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java @@ -25,10 +25,7 @@ import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; @@ -38,8 +35,13 @@ import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; +import java.util.zip.GZIPInputStream; public class StandaloneProvider implements Provider { + public StandaloneProvider() { + nodesToPath.put(-1, schematicDir.toPath()); + } + @Override public BauweltMember getBauMember(int ownerID, int memberID) { OfflinePlayer player = Bukkit.getOfflinePlayer(SteamwarUser.get(memberID).getUUID()); @@ -206,10 +208,6 @@ public class StandaloneProvider implements Provider { private final Map> nodesByParent = new HashMap<>(); private final Map nodesToPath = new HashMap<>(); - { - nodesToPath.put(-1, schematicDir.toPath()); - } - private List mapDir(Integer id) { try (Stream stream = Files.list(id==null?schematicDir.toPath():nodesToPath.get(id))) { List list = stream.map(path -> { @@ -342,22 +340,18 @@ public class StandaloneProvider implements Provider { @Override public InputStream getSchematicData(SchematicNode node) throws IOException { - return Files.newInputStream(nodesToPath.get(node.getId())); + return new GZIPInputStream(Files.newInputStream(nodesToPath.get(node.getId()))); } @Override public void saveSchematicNode(SchematicNode node, InputStream blob, boolean newFormat) { - try { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + try (FileOutputStream stream = new FileOutputStream(nodesToPath.get(node.getId()).toFile())) { byte[] bucket = new byte[1024]; int nReadBytes; while((nReadBytes = blob.read(bucket, 0, bucket.length)) !=-1){ - byteArrayOutputStream.write(bucket, 0, nReadBytes); + stream.write(bucket, 0, nReadBytes); } - - byte[] bytes = byteArrayOutputStream.toByteArray(); - Files.write(nodesToPath.get(node.getId()), bytes, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { throw new SecurityException(e); } -- 2.39.5 From 5cc6ab21452f07b92df691be09955d18d37eb91a Mon Sep 17 00:00:00 2001 From: Chaos Date: Fri, 11 Feb 2022 21:58:44 +0100 Subject: [PATCH 7/9] refactor(standalone): Move WorldEdit Directory to StandaloneProvider feat(standalone): Add Creating Nodes --- .../de/steamwar/core/WorldEditWrapper.java | 5 +-- .../de/steamwar/sql/StandaloneProvider.java | 36 +++++++++++++++++-- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java b/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java index 58d5ee1..7cfba3b 100644 --- a/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java +++ b/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java @@ -18,12 +18,9 @@ public class WorldEditWrapper { InputStream getPlayerClipboard(Player player, boolean schemFormat); void setPlayerClipboard(Player player, InputStream is, boolean schemFormat); Clipboard getClipboard(InputStream is, boolean schemFormat) throws IOException; - default File getWorldEditSchematicFolder() { - return WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getWorkingDirectoryFile(WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getConfiguration().saveDir); - } } - static WorldEditPlugin getWorldEditPlugin() { + public static WorldEditPlugin getWorldEditPlugin() { return (WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit"); } } diff --git a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java index 97f810a..c9c6259 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java @@ -203,7 +203,7 @@ public class StandaloneProvider implements Provider { } private int nodeId = 1; - private final File schematicDir = WorldEditWrapper.impl.getWorldEditSchematicFolder(); + private final File schematicDir = WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getWorkingDirectoryFile(WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getConfiguration().saveDir); private final Map nodeById = new HashMap<>(); private final Map> nodesByParent = new HashMap<>(); private final Map nodesToPath = new HashMap<>(); @@ -215,7 +215,7 @@ public class StandaloneProvider implements Provider { SchematicNode node = new SchematicNode( nodeId++, 0, - file.getName().substring(file.getName().lastIndexOf(".")), + file.isDirectory()?file.getName():file.getName().substring(file.getName().lastIndexOf(".")), null, "", "normal", @@ -237,7 +237,35 @@ public class StandaloneProvider implements Provider { @Override public void createSchematicNode(int owner, String name, Integer parent, String type, String item) { + boolean isDir = type == null; + Path p = null; + try { + if(isDir) { + p = Files.createDirectory(new File(nodesToPath.get(parent == null?-1:parent).toFile(), name).toPath()); + } else { + p = Files.createFile(new File(nodesToPath.get(parent == null?-1:parent).toFile(), name + ".schem").toPath()); + } + } catch (IOException e) { + throw new SecurityException(e); + } + File file = p.toFile(); + int id = nodeId++; + nodesToPath.put(id, p); + SchematicNode node = new SchematicNode( + nodeId++, + 0, + file.isDirectory()?file.getName():file.getName().substring(file.getName().lastIndexOf(".")), + null, + "", + "normal", + file.isDirectory(), + 0, + Timestamp.from(Instant.now()), + file.getName().endsWith(".schem") + ); + nodeById.put(id, node); + nodesByParent.get(parent == null?-1:parent).add(node); } @Override @@ -352,6 +380,10 @@ public class StandaloneProvider implements Provider { while((nReadBytes = blob.read(bucket, 0, bucket.length)) !=-1){ stream.write(bucket, 0, nReadBytes); } + + if(newFormat != node.getSchemFormat()) { + nodesToPath.get(node.getId()).toFile().renameTo(new File(nodesToPath.get(node.getId()).toFile().getParentFile(), node.getName() + "." + (newFormat?".schem":"schematic"))); + } } catch (IOException e) { throw new SecurityException(e); } -- 2.39.5 From 73438a1b8aa386b4931b111a2ce68d80bdf7d472 Mon Sep 17 00:00:00 2001 From: Chaoscaot Date: Fri, 11 Feb 2022 22:03:11 +0100 Subject: [PATCH 8/9] fix(standalone): Imports Signed-off-by: Chaos --- SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java index 8e334ae..f83bfdd 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java @@ -19,12 +19,16 @@ package de.steamwar.sql; +import de.steamwar.core.WorldEditWrapper; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import java.io.IOException; import java.io.InputStream; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; import java.sql.Timestamp; import java.time.Instant; import java.util.*; -- 2.39.5 From 2659bdd539aca0cdfaa2fa58f415a8a70acc2c04 Mon Sep 17 00:00:00 2001 From: Chaos Date: Fri, 11 Feb 2022 22:04:45 +0100 Subject: [PATCH 9/9] fix(standalone): Imports Signed-off-by: Chaos --- SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java | 1 - SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java | 1 - 2 files changed, 2 deletions(-) diff --git a/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java b/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java index 7cfba3b..269f426 100644 --- a/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java +++ b/SpigotCore_Main/src/de/steamwar/core/WorldEditWrapper.java @@ -5,7 +5,6 @@ import com.sk89q.worldedit.extent.clipboard.Clipboard; import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import java.io.File; import java.io.IOException; import java.io.InputStream; diff --git a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java index c9c6259..722a1a0 100644 --- a/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java +++ b/SpigotCore_Main/src/de/steamwar/sql/StandaloneProvider.java @@ -28,7 +28,6 @@ import org.bukkit.entity.Player; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.StandardOpenOption; import java.sql.Timestamp; import java.time.Instant; import java.util.*; -- 2.39.5